mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-01 17:47:11 +09:00
Compare commits
No files matched your search
+48
-22
@@ -1399,29 +1399,47 @@ jobs:
|
||||
run: |
|
||||
OLD_PRIMARY="${{ steps.config.outputs.primary_vm }}"
|
||||
OLD_PRIMARY_IP="${{ steps.config.outputs.primary_ip }}"
|
||||
API_KEY=$(gcloud secrets versions access latest \
|
||||
--secret=encoding-worker-api-key --project=nomadkaraoke)
|
||||
|
||||
ACTIVE_JOBS=$(curl -sf --connect-timeout 3 --max-time 5 "http://${OLD_PRIMARY_IP}:8080/health" \
|
||||
| jq -r '.active_jobs // 0' 2>/dev/null || echo "0")
|
||||
# Probe the worker's active_jobs. Echoes a non-negative integer on a
|
||||
# successful /health response, or "unknown" if /health can't be
|
||||
# reached or parsed. We must NOT conflate "unknown" with "0": a busy
|
||||
# encoder running a 4K render pins all 32 cores and can miss the 5s
|
||||
# health window, and treating that as idle previously let us stop the
|
||||
# VM mid-render — orphaning the job and surfacing as "lost contact
|
||||
# with worker ... not found" (incident 2026-06-15).
|
||||
probe_active_jobs() {
|
||||
local body n
|
||||
body=$(curl -sf --connect-timeout 3 --max-time 5 \
|
||||
"http://${OLD_PRIMARY_IP}:8080/health" 2>/dev/null) || { echo "unknown"; return; }
|
||||
n=$(printf '%s' "$body" | jq -r '.active_jobs // empty' 2>/dev/null)
|
||||
case "$n" in
|
||||
''|*[!0-9]*) echo "unknown" ;;
|
||||
*) echo "$n" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
if [ "$ACTIVE_JOBS" -gt 0 ]; then
|
||||
echo "Old primary has $ACTIVE_JOBS active jobs, waiting for drain..."
|
||||
DRAIN_TIMEOUT=600
|
||||
ELAPSED=0
|
||||
while [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
|
||||
sleep 15
|
||||
ELAPSED=$((ELAPSED + 15))
|
||||
ACTIVE_JOBS=$(curl -sf --connect-timeout 3 --max-time 5 "http://${OLD_PRIMARY_IP}:8080/health" \
|
||||
| jq -r '.active_jobs // 0' 2>/dev/null || echo "0")
|
||||
echo "Active jobs: $ACTIVE_JOBS (${ELAPSED}s elapsed)"
|
||||
if [ "$ACTIVE_JOBS" -eq 0 ]; then
|
||||
break
|
||||
fi
|
||||
done
|
||||
# Drain: wait until /health CONFIRMS 0 active jobs, or the bounded
|
||||
# timeout elapses. "unknown" is treated as "maybe busy" and keeps us
|
||||
# waiting — we only stop on a definitive 0 (or after the timeout, so
|
||||
# a wedged worker can't block the deploy forever). 20 min comfortably
|
||||
# covers a full 4K render; the old primary only drains in-flight work
|
||||
# since new renders already route to the just-swapped new primary.
|
||||
DRAIN_TIMEOUT=1200
|
||||
ELAPSED=0
|
||||
ACTIVE_JOBS=$(probe_active_jobs)
|
||||
echo "Initial active_jobs: $ACTIVE_JOBS"
|
||||
while [ "$ACTIVE_JOBS" != "0" ] && [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
|
||||
sleep 15
|
||||
ELAPSED=$((ELAPSED + 15))
|
||||
ACTIVE_JOBS=$(probe_active_jobs)
|
||||
echo "active_jobs: $ACTIVE_JOBS (${ELAPSED}s elapsed)"
|
||||
done
|
||||
|
||||
if [ "$ACTIVE_JOBS" = "0" ]; then
|
||||
echo "Drain confirmed (0 active jobs). Stopping old primary: $OLD_PRIMARY"
|
||||
else
|
||||
echo "::warning::Drain not confirmed after ${DRAIN_TIMEOUT}s (last='${ACTIVE_JOBS}'); stopping anyway to avoid a stuck deploy"
|
||||
fi
|
||||
|
||||
echo "Stopping old primary: $OLD_PRIMARY"
|
||||
gcloud compute instances stop "$OLD_PRIMARY" \
|
||||
--zone=us-central1-c --project=nomadkaraoke || true
|
||||
|
||||
@@ -1658,8 +1676,8 @@ jobs:
|
||||
--min-instances 1 \
|
||||
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
|
||||
--vpc-egress private-ranges-only \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,EMAIL_PROVIDER=postmark,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
|
||||
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest"
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-4-8,AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
|
||||
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest"
|
||||
|
||||
- name: Update Cloud Run Jobs with new image
|
||||
run: |
|
||||
@@ -1676,6 +1694,14 @@ jobs:
|
||||
--quiet
|
||||
|
||||
# Lyrics transcription job (CPU, us-central1)
|
||||
# NOTE: image-only update. Adding --update-secrets here crashed gcloud
|
||||
# ("Invalid secret path ... in annotation") because this job's existing
|
||||
# secrets are stored via Cloud Run secret *aliases* that --update-secrets
|
||||
# re-validates and rejects. Proactive auto-correct env/secret
|
||||
# (AUTO_CORRECT_PROACTIVE_ENABLED + ANTHROPIC_API_KEY) must be wired by a
|
||||
# method that handles the alias format (see proactive-autocorrect plan
|
||||
# doc); until then the proactive flag stays unset and the worker's
|
||||
# _run_proactive_auto_correct() returns early (no-op).
|
||||
gcloud run jobs update lyrics-transcription-job \
|
||||
--image "$IMAGE" \
|
||||
--region us-central1 \
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
name: E2E Daily Test (Tenant Portals)
|
||||
|
||||
# Full production E2E per white-label tenant: submit a job with the tenant's own
|
||||
# mixed + instrumental audio, approve the lyrics review, wait for the render, and assert
|
||||
# the tenant distribution (locked theme, no YouTube, no Google Drive, Dropbox folder +
|
||||
# downloadable outputs). Mirrors the consumer e2e-daily.yml. Each run cleans up its job.
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# Daily at 00:07 UTC = ~8pm US Eastern (8:07pm EDT / 7:07pm EST). Cron is fixed
|
||||
# UTC so the local time shifts 1h across DST. Off the :00 mark to avoid the
|
||||
# top-of-hour scheduler herd.
|
||||
- cron: '7 0 * * *'
|
||||
workflow_dispatch: {}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write # for Workload Identity Federation
|
||||
|
||||
jobs:
|
||||
e2e-tenant:
|
||||
name: "Tenant E2E: ${{ matrix.tenant }}"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
# Run tenants sequentially: the GCE encoder is a single shared worker, and two
|
||||
# concurrent full renders overwhelm it ("lost contact with worker"). One at a time.
|
||||
max-parallel: 1
|
||||
matrix:
|
||||
tenant: [vocalstar, singa]
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.11'
|
||||
|
||||
- name: Authenticate to GCP
|
||||
uses: google-github-actions/auth@v2
|
||||
with:
|
||||
workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
|
||||
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install google-cloud-storage google-cloud-secret-manager
|
||||
|
||||
- name: Run tenant E2E
|
||||
id: run_test
|
||||
env:
|
||||
KARAOKE_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
run: |
|
||||
echo "=== Tenant E2E: ${{ matrix.tenant }} ==="
|
||||
python scripts/e2e/tenant_e2e.py ${{ matrix.tenant }} 2>&1 | tee e2e-output.log
|
||||
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Upload logs
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-tenant-${{ matrix.tenant }}-${{ github.run_number }}
|
||||
path: e2e-output.log
|
||||
retention-days: 14
|
||||
|
||||
- name: Discord notification (failure)
|
||||
if: ${{ steps.run_test.outputs.exit_code != '0' }}
|
||||
env:
|
||||
DISCORD_WEBHOOK: ${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}
|
||||
run: |
|
||||
if [ -n "$DISCORD_WEBHOOK" ]; then
|
||||
curl -s -H "Content-Type: application/json" \
|
||||
-d "{\"embeds\": [{\"title\": \"❌ Tenant E2E FAILED — ${{ matrix.tenant }}\", \"description\": \"Run: #${{ github.run_number }}\", \"color\": 15158332}]}" \
|
||||
"$DISCORD_WEBHOOK" || true
|
||||
fi
|
||||
|
||||
- name: Fail the job if the test failed
|
||||
if: ${{ steps.run_test.outputs.exit_code != '0' }}
|
||||
run: exit 1
|
||||
|
||||
notify-email:
|
||||
name: "Email summary"
|
||||
runs-on: ubuntu-latest
|
||||
needs: e2e-tenant
|
||||
if: ${{ always() && github.event_name == 'schedule' }}
|
||||
steps:
|
||||
- name: Send email notification
|
||||
uses: dawidd6/action-send-mail@v3
|
||||
with:
|
||||
server_address: smtp.postmarkapp.com
|
||||
server_port: 587
|
||||
username: ${{ secrets.POSTMARK_SERVER_TOKEN }}
|
||||
password: ${{ secrets.POSTMARK_SERVER_TOKEN }}
|
||||
subject: "Tenant E2E Daily ${{ needs.e2e-tenant.result == 'success' && 'PASSED' || 'FAILED' }} - Run #${{ github.run_number }}"
|
||||
to: andrew@nomadkaraoke.com
|
||||
from: "Karaoke Gen CI <noreply@nomadkaraoke.com>"
|
||||
body: |
|
||||
Tenant E2E Daily Test (Vocal Star + Singa)
|
||||
Result: ${{ needs.e2e-tenant.result }}
|
||||
Run: #${{ github.run_number }}
|
||||
Details: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
@@ -7,7 +7,7 @@ and checks karaokenerds.com for existing community karaoke versions.
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Optional
|
||||
from typing import Literal, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from pydantic import BaseModel, Field
|
||||
@@ -103,6 +103,38 @@ class CommunityCheckResponse(BaseModel):
|
||||
best_youtube_url: Optional[str] = None
|
||||
|
||||
|
||||
class MatchJudgeRequest(BaseModel):
|
||||
"""Request body for the artist/title match judge."""
|
||||
artist: str = Field(..., min_length=1)
|
||||
title: str = Field(..., min_length=1)
|
||||
# The audio search's confidence tier (1=strong..3=weak), so the judge can
|
||||
# tell whether weak results hint at a typo. Optional.
|
||||
audio_confidence_tier: Optional[int] = Field(None, ge=1, le=3)
|
||||
# "fast" = catalog-only pass (no AI, no tier needed) the client fires in
|
||||
# parallel with the audio search; "full" = complete pipeline once the tier is
|
||||
# known. Defaults to "full" so a single legacy call still works.
|
||||
stage: Literal["fast", "full"] = "full"
|
||||
|
||||
|
||||
class MatchJudgeAlternative(BaseModel):
|
||||
artist: str
|
||||
title: str
|
||||
|
||||
|
||||
class MatchJudgeResponse(BaseModel):
|
||||
"""Verdict on a typed artist/title — formatting + match acceptance."""
|
||||
kind: str # "cosmetic" | "content" | "ambiguous" | "none"
|
||||
confident: bool
|
||||
canonical_artist: str
|
||||
canonical_title: str
|
||||
alternatives: list[MatchJudgeAlternative] = []
|
||||
engine: str # "deterministic" | "catalog" | "ai"
|
||||
reason: str = ""
|
||||
# Set by a "fast" pass that couldn't decide — the client should follow up with
|
||||
# a "full" call once the audio tier is known.
|
||||
needs_ai: bool = False
|
||||
|
||||
|
||||
# --- Routes ---
|
||||
|
||||
|
||||
@@ -161,3 +193,31 @@ async def check_community_versions(
|
||||
from backend.services.karaokenerds_service import check_community_versions
|
||||
result = await check_community_versions(body.artist, body.title)
|
||||
return result
|
||||
|
||||
|
||||
@router.post("/match-judge", response_model=MatchJudgeResponse)
|
||||
async def match_judge(
|
||||
request: Request,
|
||||
body: MatchJudgeRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Judge a typed artist/title: decide official formatting + whether it matches a
|
||||
real song. Deterministic + catalog layers run first; a light AI model fires
|
||||
only when those aren't confident. Never blocks the submission flow — failures
|
||||
degrade to a "none" verdict.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale)
|
||||
|
||||
from backend.services.match_judge.service import judge_match
|
||||
verdict = await judge_match(
|
||||
body.artist, body.title,
|
||||
audio_tier=body.audio_confidence_tier,
|
||||
stage=body.stage,
|
||||
)
|
||||
logger.info(
|
||||
"match-judge stage=%s kind=%s engine=%s confident=%s needs_ai=%s",
|
||||
body.stage, verdict.kind, verdict.engine, verdict.confident, verdict.needs_ai,
|
||||
)
|
||||
return verdict.to_dict()
|
||||
@@ -57,6 +57,19 @@ def _is_youtube_url(url: str) -> bool:
|
||||
router = APIRouter(tags=["jobs"])
|
||||
|
||||
|
||||
def _select_mixed_audio_files(files):
|
||||
"""Filter a listing of ``uploads/{job_id}/audio/`` down to the mixed (with-vocals) audio.
|
||||
|
||||
When a job supplies its own instrumental (existing_instrumental flow, e.g. tenant
|
||||
submissions), that file is uploaded into the SAME ``audio/`` directory as the mixed
|
||||
audio (``existing_instrumental.*``). The ``audio/`` prefix therefore matches both, and
|
||||
because ``existing_instrumental`` sorts before most filenames, ``files[0]`` would pick
|
||||
the instrumental — so transcription would run on the backing track instead of the
|
||||
vocals. Excluding it here ensures the mixed audio is selected as the transcription input.
|
||||
"""
|
||||
return [f for f in files if not Path(f).name.startswith('existing_instrumental')]
|
||||
|
||||
|
||||
def _apply_tenant_overrides(
|
||||
dist: EffectiveDistributionSettings,
|
||||
tenant_config,
|
||||
@@ -67,12 +80,20 @@ def _apply_tenant_overrides(
|
||||
"""
|
||||
Apply tenant-specific overrides to distribution settings and job options.
|
||||
|
||||
White-label tenant config is AUTHORITATIVE: it replaces (not just fills in) the
|
||||
distribution settings, so tenant outputs never inherit the global consumer defaults
|
||||
(DEFAULT_BRAND_PREFIX / DEFAULT_DROPBOX_PATH / DEFAULT_GDRIVE_FOLDER_ID) that
|
||||
``get_effective_distribution_settings`` seeds into ``dist``. Without this, every
|
||||
tenant job would land in the shared consumer Dropbox folder and upload to the global
|
||||
Google Drive, regardless of the tenant's own config.
|
||||
|
||||
For tenant jobs:
|
||||
- Overlays brand_prefix, dropbox_path, gdrive_folder_id from tenant defaults
|
||||
(only when not already set in the request body / dist)
|
||||
- Sets brand_prefix, dropbox_path, gdrive_folder_id authoritatively from tenant config
|
||||
- Routes Dropbox / Google Drive only when the matching feature flag is enabled;
|
||||
otherwise disables that channel entirely (no global-default leak)
|
||||
- Forces is_private = True
|
||||
- Applies locked_theme as effective theme
|
||||
- Disables YouTube upload
|
||||
- Disables YouTube upload (tenants never publish to YouTube)
|
||||
|
||||
Returns:
|
||||
Tuple of (dist, effective_theme_id, is_private, enable_youtube_upload)
|
||||
@@ -81,14 +102,12 @@ def _apply_tenant_overrides(
|
||||
return dist, effective_theme_id, is_private, enable_youtube_upload
|
||||
|
||||
defaults = tenant_config.defaults
|
||||
features = tenant_config.features
|
||||
|
||||
# Overlay tenant distribution defaults (request-level values take precedence)
|
||||
if defaults.brand_prefix and not dist.brand_prefix:
|
||||
dist.brand_prefix = defaults.brand_prefix
|
||||
if defaults.dropbox_path and not dist.dropbox_path:
|
||||
dist.dropbox_path = defaults.dropbox_path
|
||||
if defaults.gdrive_folder_id and not dist.gdrive_folder_id:
|
||||
dist.gdrive_folder_id = defaults.gdrive_folder_id
|
||||
# Authoritative distribution routing (overrides any global defaults in `dist`).
|
||||
dist.brand_prefix = defaults.brand_prefix
|
||||
dist.dropbox_path = defaults.dropbox_path if features.dropbox_upload else None
|
||||
dist.gdrive_folder_id = defaults.gdrive_folder_id if features.gdrive_upload else None
|
||||
|
||||
# Force private for all tenant jobs
|
||||
is_private = True
|
||||
@@ -1382,12 +1401,14 @@ async def mark_uploads_complete(
|
||||
|
||||
# List files with this prefix to find the actual uploaded file
|
||||
files = storage_service.list_files(prefix)
|
||||
if file_type == 'audio':
|
||||
files = _select_mixed_audio_files(files)
|
||||
if not files:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"File for '{file_type}' was not uploaded to GCS. Expected prefix: {prefix}"
|
||||
)
|
||||
|
||||
|
||||
# Use the first (and should be only) file found
|
||||
gcs_path = files[0]
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from backend.workers.audio_worker import process_audio_separation
|
||||
from backend.workers.auto_correct_worker import process_proactive_auto_correct
|
||||
from backend.workers.lyrics_worker import process_lyrics_transcription
|
||||
from backend.workers.screens_worker import generate_screens
|
||||
from backend.workers.video_worker import generate_video
|
||||
@@ -227,6 +228,48 @@ async def trigger_lyrics_worker(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/workers/auto-correct", response_model=WorkerResponse)
|
||||
async def trigger_auto_correct_worker(
|
||||
request: WorkerRequest,
|
||||
http_request: Request,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""Proactively pre-generate + cache AI auto-correct suggestions for a job.
|
||||
|
||||
Called by the lyrics worker once transcription + references are ready, so
|
||||
the suggestions are cached before the reviewer opens the lyrics UI. Runs
|
||||
HERE (the API service) because the service has the working Anthropic key /
|
||||
compare-models config; the lyrics job does not.
|
||||
|
||||
Best-effort and runs synchronously within the request (the caller awaits
|
||||
with its own timeout): the work never fails the karaoke job, and the
|
||||
response just reports what happened. Gated by AUTO_CORRECT_PROACTIVE_ENABLED.
|
||||
"""
|
||||
job_id = request.job_id
|
||||
|
||||
# Extract trace context from incoming request (propagated via the trigger).
|
||||
trace_context = extract_trace_context(dict(http_request.headers))
|
||||
|
||||
logger.info(f"[job:{job_id}] WORKER_TRIGGER worker=auto-correct")
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("worker", "auto-correct")
|
||||
|
||||
# process_proactive_auto_correct already swallows its own errors; the extra
|
||||
# guard keeps the endpoint itself best-effort no matter what.
|
||||
try:
|
||||
result = await process_proactive_auto_correct(job_id)
|
||||
add_span_event("auto_correct_proactive", {"result": result.get("status", "unknown")})
|
||||
return WorkerResponse(
|
||||
status=result.get("status", "unknown"),
|
||||
job_id=job_id,
|
||||
message=f"Proactive auto-correct: {result.get('status', 'unknown')}",
|
||||
)
|
||||
except Exception as e: # noqa: BLE001 — best-effort, never fail the caller
|
||||
logger.warning(f"[job:{job_id}] auto-correct endpoint error (non-fatal): {e}")
|
||||
add_span_event("auto_correct_proactive", {"result": "error"})
|
||||
return WorkerResponse(status="error", job_id=job_id, message=f"error: {e}")
|
||||
|
||||
|
||||
@router.post("/workers/screens", response_model=WorkerResponse)
|
||||
async def trigger_screens_worker(
|
||||
request: WorkerRequest,
|
||||
|
||||
@@ -1475,6 +1475,13 @@ async def complete_review(
|
||||
try:
|
||||
# Store instrumental selection if provided (combined review flow)
|
||||
instrumental_selection = body.instrumental_selection if body else None
|
||||
# Jobs that supplied their own instrumental (existing_instrumental flow, e.g. tenant
|
||||
# submissions) have no instrumental-selection UI step. Default to 'custom' so the
|
||||
# render uses the provided instrumental instead of a separated stem that was never
|
||||
# produced (the orchestrator otherwise defaults to 'clean' and fails prerequisites).
|
||||
if not instrumental_selection and getattr(job, 'existing_instrumental_gcs_path', None):
|
||||
instrumental_selection = 'custom'
|
||||
logger.info(f"Job {job_id}: Defaulting instrumental selection to 'custom' (existing instrumental provided)")
|
||||
if instrumental_selection:
|
||||
job_manager.update_state_data(job_id, 'instrumental_selection', instrumental_selection)
|
||||
logger.info(f"Job {job_id}: Stored instrumental selection: {instrumental_selection}")
|
||||
@@ -2434,11 +2441,21 @@ async def create_job_from_search(
|
||||
from backend.services.job_defaults_service import resolve_cdg_txt_defaults
|
||||
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(effective_theme_id, None, None)
|
||||
|
||||
# Determine display values
|
||||
# Determine display values.
|
||||
# The session stores the ORIGINAL search query (e.g. "hard-fi"). body.artist/
|
||||
# body.title carry whatever is currently in the wizard's artist/title fields,
|
||||
# which reflect a "Use official formatting" correction the user may have applied
|
||||
# after searching. The displayed job name must honour that correction, so prefer
|
||||
# the request body over the stored query. An explicit display override wins above all.
|
||||
session_artist = session.get('artist', body.artist)
|
||||
session_title = session.get('title', body.title)
|
||||
effective_display_artist = body.display_artist or session_artist
|
||||
effective_display_title = body.display_title or session_title
|
||||
# body.artist/body.title are required but unvalidated for whitespace, so strip
|
||||
# them and fall back to the stored query if blank (display_* is pre-stripped to
|
||||
# None by its validator). This keeps a stray " " from becoming the job name.
|
||||
body_artist = (body.artist or "").strip()
|
||||
body_title = (body.title or "").strip()
|
||||
effective_display_artist = body.display_artist or body_artist or session_artist
|
||||
effective_display_title = body.display_title or body_title or session_title
|
||||
|
||||
tenant_id = session.get('tenant_id') or ""
|
||||
|
||||
|
||||
@@ -44,6 +44,11 @@ from backend.services.custom_lyrics_service import (
|
||||
CustomLyricsServiceError,
|
||||
get_custom_lyrics_service,
|
||||
)
|
||||
from backend.services.auto_correct import (
|
||||
AutoCorrectService,
|
||||
AutoCorrectServiceError,
|
||||
get_auto_correct_service,
|
||||
)
|
||||
|
||||
|
||||
class LineMetadataResponse(_PydBaseModel):
|
||||
@@ -70,11 +75,49 @@ class CustomLyricsResponse(_PydBaseModel):
|
||||
model: str
|
||||
|
||||
|
||||
class AutoCorrectRequest(_PydBaseModel):
|
||||
segments: list[dict] # client's current working corrected_segments
|
||||
reference_lyrics: dict # client's reference sources (incl. user-added)
|
||||
artist: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
settings: Optional[dict] = None # AutoCorrectSettings knobs
|
||||
|
||||
|
||||
class AutoCorrectSuggestionResponse(_PydBaseModel):
|
||||
id: str
|
||||
op: str # "replace" | "delete" | "insert_after"
|
||||
word_ids: list[str]
|
||||
segment_ids: list[str]
|
||||
original_text: str
|
||||
new_text: str
|
||||
reason: str
|
||||
category: str
|
||||
confidence: float
|
||||
models: list[str]
|
||||
consensus: int
|
||||
total_models: int
|
||||
conflict_group: Optional[str] = None
|
||||
|
||||
|
||||
class AutoCorrectResponse(_PydBaseModel):
|
||||
suggestions: list[AutoCorrectSuggestionResponse]
|
||||
model: str
|
||||
elapsed_seconds: float
|
||||
settings_applied: dict
|
||||
warnings: list[str]
|
||||
cached: bool = False
|
||||
|
||||
|
||||
def _get_custom_lyrics_service_dep() -> CustomLyricsService:
|
||||
"""FastAPI dependency wrapper around the singleton accessor."""
|
||||
return get_custom_lyrics_service()
|
||||
|
||||
|
||||
def _get_auto_correct_service_dep() -> AutoCorrectService:
|
||||
"""FastAPI dependency wrapper around the singleton accessor."""
|
||||
return get_auto_correct_service()
|
||||
|
||||
|
||||
async def _load_target_segments_for_custom_lyrics(
|
||||
job_id: str,
|
||||
target_lines: list[str],
|
||||
@@ -636,6 +679,79 @@ async def generate_custom_lyrics(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{job_id}/auto-correct", response_model=AutoCorrectResponse)
|
||||
async def auto_correct_suggestions(
|
||||
job_id: str,
|
||||
body: AutoCorrectRequest,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
service: AutoCorrectService = Depends(_get_auto_correct_service_dep),
|
||||
) -> AutoCorrectResponse:
|
||||
"""Generate AI auto-correction suggestions for the lyrics review UI.
|
||||
|
||||
Stateless and strictly opt-in: one whole-song LLM call comparing the
|
||||
client's current working transcription against the reference lyrics.
|
||||
Returns word-id-keyed suggestions; nothing is applied server-side —
|
||||
the reviewer accepts or rejects each suggestion individually and
|
||||
persistence happens via the existing corrections/complete paths.
|
||||
"""
|
||||
from backend.services.auto_correct.settings import settings_from_dict
|
||||
|
||||
try:
|
||||
settings = settings_from_dict(body.settings or {})
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=f"invalid settings: {exc}") from exc
|
||||
|
||||
with job_log_context(job_id), create_span("auto_correct_suggestions"):
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("segment_count", len(body.segments))
|
||||
logger.info(
|
||||
"auto-correct requested job=%s segments=%d sources=%d",
|
||||
job_id, len(body.segments), len(body.reference_lyrics),
|
||||
)
|
||||
try:
|
||||
result = await asyncio.to_thread(
|
||||
service.suggest,
|
||||
job_id=job_id,
|
||||
segments=body.segments,
|
||||
reference_lyrics=body.reference_lyrics,
|
||||
artist=body.artist,
|
||||
title=body.title,
|
||||
settings=settings,
|
||||
)
|
||||
except AutoCorrectServiceError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc
|
||||
logger.info(
|
||||
"auto-correct completed job=%s suggestions=%d model=%s elapsed=%.1fs",
|
||||
job_id, len(result.suggestions), result.model, result.elapsed_seconds,
|
||||
)
|
||||
|
||||
return AutoCorrectResponse(
|
||||
suggestions=[
|
||||
AutoCorrectSuggestionResponse(
|
||||
id=s.id,
|
||||
op=s.op,
|
||||
word_ids=s.word_ids,
|
||||
segment_ids=s.segment_ids,
|
||||
original_text=s.original_text,
|
||||
new_text=s.new_text,
|
||||
reason=s.reason,
|
||||
category=s.category,
|
||||
confidence=s.confidence,
|
||||
models=s.models,
|
||||
consensus=s.consensus,
|
||||
total_models=s.total_models,
|
||||
conflict_group=s.conflict_group,
|
||||
)
|
||||
for s in result.suggestions
|
||||
],
|
||||
model=result.model,
|
||||
elapsed_seconds=result.elapsed_seconds,
|
||||
settings_applied=result.settings_applied.to_dict(),
|
||||
warnings=result.warnings,
|
||||
cached=result.cached,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{job_id}/handlers")
|
||||
async def update_handlers(
|
||||
job_id: str,
|
||||
@@ -1817,7 +1933,8 @@ async def apply_audio_edit(
|
||||
"""
|
||||
Apply an edit operation to the input audio.
|
||||
|
||||
Supported operations: trim_start, trim_end, cut, mute, join_start, join_end.
|
||||
Supported operations: trim_start, trim_end, cut, mute, fade_in, fade_out,
|
||||
join_start, join_end.
|
||||
Returns updated waveform data and playback URL.
|
||||
"""
|
||||
import uuid
|
||||
@@ -1831,7 +1948,7 @@ async def apply_audio_edit(
|
||||
if not operation:
|
||||
raise HTTPException(status_code=400, detail="Missing 'operation' field")
|
||||
|
||||
valid_operations = {"trim_start", "trim_end", "cut", "mute", "join_start", "join_end"}
|
||||
valid_operations = {"trim_start", "trim_end", "cut", "mute", "fade_in", "fade_out", "join_start", "join_end"}
|
||||
if operation not in valid_operations:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid operation: {operation}. Valid: {valid_operations}")
|
||||
|
||||
|
||||
@@ -88,6 +88,35 @@ class Settings(BaseSettings):
|
||||
custom_lyrics_default_strictness: str = os.getenv("CUSTOM_LYRICS_DEFAULT_STRICTNESS", "balanced")
|
||||
custom_lyrics_max_output_lines_multiplier: float = float(os.getenv("CUSTOM_LYRICS_MAX_OUTPUT_LINES_MULTIPLIER", "2.0"))
|
||||
|
||||
# AI auto-correct suggestions — opt-in, user-triggered from the lyrics
|
||||
# review UI. Stateless: one whole-song LLM call returning word-level
|
||||
# suggestions the reviewer accepts/rejects individually.
|
||||
auto_correct_model: str = os.getenv("AUTO_CORRECT_MODEL", "gemini-3.1-pro-preview")
|
||||
# Models used by the multi-model "compare" mode (semicolon-separated —
|
||||
# Cloud Run --set-env-vars is comma-delimited). Empty = single-model only.
|
||||
auto_correct_compare_models: str = os.getenv("AUTO_CORRECT_COMPARE_MODELS", "")
|
||||
# Proactively generate (and cache) auto-correct suggestions in the lyrics
|
||||
# worker once transcription + references are ready, so the review UI has
|
||||
# them instantly. Best-effort: failures never block or fail the job. Only
|
||||
# meaningful where ANTHROPIC_API_KEY + AUTO_CORRECT_COMPARE_MODELS are set
|
||||
# (the lyrics-transcription-job, via ci.yml). Default off.
|
||||
auto_correct_proactive_enabled: bool = os.getenv(
|
||||
"AUTO_CORRECT_PROACTIVE_ENABLED", "false"
|
||||
).lower() in ("true", "1", "yes")
|
||||
|
||||
# Match judge — artist/title formatting + match-acceptance for the job
|
||||
# submission flow. Deterministic + catalog layers always run; the light AI
|
||||
# layer (Vertex Gemini Flash) fires only when those aren't confident.
|
||||
match_judge_enabled: bool = os.getenv("MATCH_JUDGE_ENABLED", "true").lower() in (
|
||||
"true", "1", "yes",
|
||||
)
|
||||
match_judge_model: str = os.getenv("MATCH_JUDGE_MODEL", "gemini-3.5-flash")
|
||||
# Bounds the AI call so a hung model never strands the submission UI. Kept
|
||||
# generous because Vertex returns 504 DEADLINE_EXCEEDED if generation can't
|
||||
# finish within this deadline (3s was too tight for gemini-3.5-flash); the
|
||||
# call still runs off the critical path and degrades to "none" on timeout.
|
||||
match_judge_timeout_ms: int = int(os.getenv("MATCH_JUDGE_TIMEOUT_MS", "12000"))
|
||||
|
||||
# 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)
|
||||
|
||||
@@ -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"]
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Token pricing for auto-correct model calls.
|
||||
|
||||
Used to turn the per-call token usage we capture from each provider into an
|
||||
estimated USD cost, for both the production usage logs and the offline
|
||||
measurement script (``scripts/measure_autocorrect_cost.py``).
|
||||
|
||||
Prices are USD per 1,000,000 tokens.
|
||||
|
||||
- **Anthropic** prices are authoritative (published Claude API pricing).
|
||||
``output`` is the billed output rate, which already includes adaptive
|
||||
*thinking* tokens — they are billed as output and are not separable from
|
||||
the final answer in the Anthropic usage object.
|
||||
- **Gemini** prices are a best-known ESTIMATE for the Vertex preview tier and
|
||||
are clearly marked below. Verify against current Vertex pricing before
|
||||
relying on the dollar figure. Gemini thinking tokens ARE separable
|
||||
(``thoughts_token_count``) and are billed at the output rate, so we fold
|
||||
them into the output total.
|
||||
|
||||
The raw token counts are always logged alongside the dollar figure, so the
|
||||
cost here is a derived convenience — if a rate is stale, recompute from the
|
||||
logged tokens rather than trusting the historical USD value.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional, TypedDict
|
||||
|
||||
|
||||
class TokenUsage(TypedDict):
|
||||
"""Normalized, provider-agnostic usage for one model call.
|
||||
|
||||
``output_tokens`` is the total billed output (final answer + thinking).
|
||||
``thinking_tokens`` is informational only (None when the provider does
|
||||
not report it separately) — it is already counted inside ``output_tokens``.
|
||||
"""
|
||||
|
||||
input_tokens: int
|
||||
output_tokens: int
|
||||
cache_read_tokens: int
|
||||
thinking_tokens: Optional[int]
|
||||
|
||||
|
||||
class _Rate(TypedDict):
|
||||
input: float
|
||||
output: float
|
||||
cache_read: float
|
||||
|
||||
|
||||
# USD per 1,000,000 tokens.
|
||||
MODEL_PRICING: dict[str, _Rate] = {
|
||||
# --- Anthropic (authoritative) ---
|
||||
"claude-fable-5": {"input": 10.0, "output": 50.0, "cache_read": 1.0},
|
||||
"claude-opus-4-8": {"input": 5.0, "output": 25.0, "cache_read": 0.5},
|
||||
"claude-sonnet-4-6": {"input": 3.0, "output": 15.0, "cache_read": 0.3},
|
||||
"claude-haiku-4-5": {"input": 1.0, "output": 5.0, "cache_read": 0.1},
|
||||
# --- Gemini (ESTIMATE — Vertex 3.x Pro preview, <=200K-token context
|
||||
# tier; confirm against current Google pricing before trusting USD) ---
|
||||
"gemini-3.1-pro-preview": {"input": 2.0, "output": 12.0, "cache_read": 0.2},
|
||||
}
|
||||
|
||||
|
||||
def get_rate(model: str) -> Optional[_Rate]:
|
||||
"""Return the rate card for ``model``, or None if we have no pricing.
|
||||
|
||||
Falls back to a prefix match on the model family (e.g. a dated
|
||||
``claude-fable-5-2026...`` snapshot still resolves to ``claude-fable-5``)
|
||||
so a minor model-id change doesn't silently drop cost tracking.
|
||||
"""
|
||||
if model in MODEL_PRICING:
|
||||
return MODEL_PRICING[model]
|
||||
for known, rate in MODEL_PRICING.items():
|
||||
if model.startswith(known):
|
||||
return rate
|
||||
return None
|
||||
|
||||
|
||||
def estimate_cost_usd(model: str, usage: Optional[TokenUsage]) -> Optional[float]:
|
||||
"""Estimate the USD cost of one model call from its token usage.
|
||||
|
||||
Returns None when usage is unavailable or the model has no known pricing,
|
||||
so callers can distinguish "free/zero" from "unknown".
|
||||
"""
|
||||
if not usage:
|
||||
return None
|
||||
rate = get_rate(model)
|
||||
if rate is None:
|
||||
return None
|
||||
input_tokens = usage.get("input_tokens") or 0
|
||||
output_tokens = usage.get("output_tokens") or 0
|
||||
cache_read = usage.get("cache_read_tokens") or 0
|
||||
return (
|
||||
input_tokens * rate["input"]
|
||||
+ output_tokens * rate["output"]
|
||||
+ cache_read * rate["cache_read"]
|
||||
) / 1_000_000.0
|
||||
@@ -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)
|
||||
@@ -0,0 +1,621 @@
|
||||
"""Auto-correct suggestion service: one whole-song LLM call, validated output."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from typing import Any, Optional
|
||||
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.auto_correct.pricing import TokenUsage, estimate_cost_usd
|
||||
from backend.services.auto_correct.prompts import (
|
||||
RESPONSE_SCHEMA,
|
||||
build_system_prompt,
|
||||
build_user_prompt,
|
||||
)
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
VALID_OPS = {"replace", "delete", "insert_after"}
|
||||
VALID_CATEGORIES = {
|
||||
"mishearing",
|
||||
"grammar",
|
||||
"adlib_removal",
|
||||
"repeated_chorus_fix",
|
||||
"formatting",
|
||||
"other",
|
||||
}
|
||||
|
||||
|
||||
class AutoCorrectServiceError(Exception):
|
||||
def __init__(self, message: str, *, status_code: int = 400) -> None:
|
||||
super().__init__(message)
|
||||
self.status_code = status_code
|
||||
|
||||
|
||||
@dataclass
|
||||
class Suggestion:
|
||||
id: str
|
||||
op: str # replace | delete | insert_after
|
||||
word_ids: list[str] # targeted words (replace/delete); [anchor] for insert_after
|
||||
segment_ids: list[str] # segments containing the targeted words
|
||||
original_text: str # current text of the targeted span ("" for insert_after)
|
||||
new_text: str # replacement text ("" for delete)
|
||||
reason: str
|
||||
category: str
|
||||
confidence: float
|
||||
# Multi-model compare metadata. In single-model mode models has one
|
||||
# entry and consensus == total_models == 1.
|
||||
models: list[str] = field(default_factory=list)
|
||||
consensus: int = 1
|
||||
total_models: int = 1
|
||||
# Set when other suggestions target overlapping words with a different
|
||||
# outcome — the UI lets the reviewer pick at most one per group.
|
||||
conflict_group: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class AutoCorrectResult:
|
||||
suggestions: list[Suggestion]
|
||||
model: str # comma-joined when compare mode queried several models
|
||||
elapsed_seconds: float
|
||||
settings_applied: AutoCorrectSettings
|
||||
warnings: list[str] = field(default_factory=list)
|
||||
# True when served from the per-job GCS cache (no LLM call was made).
|
||||
cached: bool = False
|
||||
|
||||
|
||||
class AutoCorrectService:
|
||||
def __init__(self) -> None:
|
||||
self.settings = get_settings()
|
||||
|
||||
def suggest(
|
||||
self,
|
||||
*,
|
||||
job_id: str,
|
||||
segments: list[dict],
|
||||
reference_lyrics: dict[str, dict],
|
||||
artist: Optional[str],
|
||||
title: Optional[str],
|
||||
settings: AutoCorrectSettings,
|
||||
) -> AutoCorrectResult:
|
||||
if not segments:
|
||||
raise AutoCorrectServiceError("segments is empty")
|
||||
if not reference_lyrics:
|
||||
raise AutoCorrectServiceError(
|
||||
"no reference lyrics available — auto-correction needs at least "
|
||||
"one internet/reference source to compare against",
|
||||
status_code=422,
|
||||
)
|
||||
|
||||
# Flat word list mirrors the prompt's global indices.
|
||||
flat: list[tuple[str, str, str]] = [] # (word_id, word_text, segment_id)
|
||||
for seg in segments:
|
||||
if not seg.get("id"):
|
||||
raise AutoCorrectServiceError("all segments must have ids")
|
||||
for w in seg.get("words") or []:
|
||||
if not w.get("id"):
|
||||
raise AutoCorrectServiceError("all words must have ids")
|
||||
flat.append((w["id"], w.get("text", ""), seg["id"]))
|
||||
|
||||
system_prompt = build_system_prompt(settings)
|
||||
user_prompt = build_user_prompt(
|
||||
segments=segments,
|
||||
reference_lyrics=reference_lyrics,
|
||||
artist=artist,
|
||||
title=title,
|
||||
)
|
||||
|
||||
models = self._models_for(settings)
|
||||
|
||||
# Re-running on byte-identical input (lyrics, references, settings,
|
||||
# models) returns the previous result instead of paying for another
|
||||
# LLM call. Word ids are part of the key, so cached suggestions
|
||||
# always reference words that still exist.
|
||||
cache_path = self._cache_path(
|
||||
job_id, models, settings, flat, reference_lyrics, artist, title
|
||||
)
|
||||
cached = self._cache_get(cache_path)
|
||||
if cached is not None:
|
||||
logger.info(
|
||||
"auto-correct cache hit job=%s suggestions=%d", job_id,
|
||||
len(cached.suggestions),
|
||||
)
|
||||
return cached
|
||||
|
||||
t0 = time.time()
|
||||
per_model: dict[str, list[Suggestion]] = {}
|
||||
# Token usage per successful model call (None when the provider's
|
||||
# usage object couldn't be read). Drives the cost log below.
|
||||
per_model_usage: dict[str, Optional[TokenUsage]] = {}
|
||||
warnings: list[str] = []
|
||||
if len(models) == 1:
|
||||
raw, usage = self._call_model(
|
||||
models[0], system_prompt, user_prompt, job_id=job_id
|
||||
)
|
||||
suggestions, vw = self._validate(raw, flat, settings)
|
||||
per_model[models[0]] = suggestions
|
||||
per_model_usage[models[0]] = usage
|
||||
warnings.extend(vw)
|
||||
else:
|
||||
import concurrent.futures as cf
|
||||
|
||||
with cf.ThreadPoolExecutor(max_workers=len(models)) as ex:
|
||||
futures = {
|
||||
ex.submit(
|
||||
self._call_model, m, system_prompt, user_prompt, job_id=job_id
|
||||
): m
|
||||
for m in models
|
||||
}
|
||||
for fut, m in futures.items():
|
||||
try:
|
||||
raw, usage = fut.result()
|
||||
suggestions, vw = self._validate(raw, flat, settings)
|
||||
except AutoCorrectServiceError as exc:
|
||||
# One model failing (call OR malformed output) must not
|
||||
# abort compare mode; the rest still return results.
|
||||
warnings.append(f"model {m} failed: {exc}")
|
||||
continue
|
||||
per_model[m] = suggestions
|
||||
per_model_usage[m] = usage
|
||||
warnings.extend(f"[{m}] {w}" for w in vw)
|
||||
if not per_model:
|
||||
raise AutoCorrectServiceError(
|
||||
"all AI models failed", status_code=502
|
||||
)
|
||||
|
||||
merged = self._merge(per_model, flat)
|
||||
elapsed = time.time() - t0
|
||||
model_label = ", ".join(per_model.keys())
|
||||
logger.info(
|
||||
"auto-correct job=%s models=%s words=%d suggestions=%d dropped_warnings=%d elapsed=%.1fs",
|
||||
job_id, model_label, len(flat), len(merged), len(warnings), elapsed,
|
||||
)
|
||||
self._log_usage(job_id, per_model_usage)
|
||||
result = AutoCorrectResult(
|
||||
suggestions=merged,
|
||||
model=model_label,
|
||||
elapsed_seconds=round(elapsed, 1),
|
||||
settings_applied=settings,
|
||||
warnings=warnings,
|
||||
)
|
||||
self._cache_put(cache_path, result)
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _log_usage(
|
||||
job_id: str, per_model_usage: dict[str, Optional[TokenUsage]]
|
||||
) -> None:
|
||||
"""Emit greppable per-model and total cost lines for one suggest() call.
|
||||
|
||||
Token counts are ground truth; the USD figures are derived from
|
||||
``pricing.MODEL_PRICING`` and use ESTIMATED Gemini rates (see that
|
||||
module). Query in Cloud Logging via ``auto-correct usage`` /
|
||||
``auto-correct cost``. Observability only — never raises.
|
||||
"""
|
||||
total_cost = 0.0
|
||||
any_cost = False
|
||||
for model, usage in per_model_usage.items():
|
||||
cost = estimate_cost_usd(model, usage)
|
||||
if cost is not None:
|
||||
total_cost += cost
|
||||
any_cost = True
|
||||
if usage is None:
|
||||
logger.info(
|
||||
"auto-correct usage job=%s model=%s tokens=unavailable",
|
||||
job_id, model,
|
||||
)
|
||||
continue
|
||||
thinking = usage.get("thinking_tokens")
|
||||
logger.info(
|
||||
"auto-correct usage job=%s model=%s input_tokens=%d "
|
||||
"output_tokens=%d thinking_tokens=%s cache_read_tokens=%d "
|
||||
"est_cost_usd=%s",
|
||||
job_id,
|
||||
model,
|
||||
usage.get("input_tokens", 0),
|
||||
usage.get("output_tokens", 0),
|
||||
"na" if thinking is None else thinking,
|
||||
usage.get("cache_read_tokens", 0),
|
||||
"unknown" if cost is None else f"{cost:.4f}",
|
||||
)
|
||||
logger.info(
|
||||
"auto-correct cost job=%s models=%s total_est_cost_usd=%s",
|
||||
job_id,
|
||||
", ".join(per_model_usage.keys()),
|
||||
f"{total_cost:.4f}" if any_cost else "unknown",
|
||||
)
|
||||
|
||||
# ---- suggestion cache (GCS, best-effort) ----
|
||||
|
||||
def _get_storage(self):
|
||||
if not hasattr(self, "_storage"):
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
self._storage = StorageService()
|
||||
return self._storage
|
||||
|
||||
@staticmethod
|
||||
def _cache_path(
|
||||
job_id: str,
|
||||
models: list[str],
|
||||
settings: AutoCorrectSettings,
|
||||
flat: list[tuple[str, str, str]],
|
||||
reference_lyrics: dict[str, dict],
|
||||
artist: Optional[str],
|
||||
title: Optional[str],
|
||||
) -> str:
|
||||
payload = {
|
||||
"v": 1,
|
||||
"models": models,
|
||||
"settings": settings.to_dict(),
|
||||
"words": [[word_id, text] for word_id, text, _seg in flat],
|
||||
"references": {
|
||||
source: [seg.get("text", "") for seg in (ref.get("segments") or [])]
|
||||
for source, ref in sorted((reference_lyrics or {}).items())
|
||||
},
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
}
|
||||
digest = hashlib.sha256(
|
||||
json.dumps(payload, sort_keys=True, ensure_ascii=False).encode()
|
||||
).hexdigest()[:24]
|
||||
return f"jobs/{job_id}/lyrics/auto_correct_cache/{digest}.json"
|
||||
|
||||
def _cache_get(self, path: str) -> Optional[AutoCorrectResult]:
|
||||
"""Best-effort: any storage/shape problem is a cache miss, never an error."""
|
||||
try:
|
||||
storage = self._get_storage()
|
||||
if not storage.bucket.blob(path).exists():
|
||||
return None
|
||||
data = storage.download_json(path)
|
||||
return AutoCorrectResult(
|
||||
suggestions=[Suggestion(**s) for s in data["suggestions"]],
|
||||
model=data["model"],
|
||||
elapsed_seconds=0.0,
|
||||
settings_applied=AutoCorrectSettings(**data["settings_applied"]),
|
||||
warnings=list(data.get("warnings") or []),
|
||||
cached=True,
|
||||
)
|
||||
except Exception:
|
||||
logger.warning("auto-correct cache read failed for %s", path, exc_info=True)
|
||||
return None
|
||||
|
||||
def _cache_put(self, path: str, result: AutoCorrectResult) -> None:
|
||||
"""Best-effort: a failed cache write never fails the request."""
|
||||
try:
|
||||
self._get_storage().upload_json(
|
||||
path,
|
||||
{
|
||||
"suggestions": [asdict(s) for s in result.suggestions],
|
||||
"model": result.model,
|
||||
"settings_applied": result.settings_applied.to_dict(),
|
||||
"warnings": result.warnings,
|
||||
"elapsed_seconds": result.elapsed_seconds,
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
logger.warning("auto-correct cache write failed for %s", path, exc_info=True)
|
||||
|
||||
def _models_for(self, settings: AutoCorrectSettings) -> list[str]:
|
||||
if settings.compare_models:
|
||||
configured = [
|
||||
m.strip()
|
||||
for m in self.settings.auto_correct_compare_models.replace(",", ";").split(";")
|
||||
if m.strip()
|
||||
]
|
||||
# De-dupe while preserving order.
|
||||
seen: set[str] = set()
|
||||
models = [m for m in configured if not (m in seen or seen.add(m))]
|
||||
if len(models) >= 2:
|
||||
return models
|
||||
logger.warning(
|
||||
"compare_models requested but AUTO_CORRECT_COMPARE_MODELS has "
|
||||
"%d usable entries; falling back to single model", len(models),
|
||||
)
|
||||
return [self.settings.auto_correct_model]
|
||||
|
||||
@staticmethod
|
||||
def _merge(
|
||||
per_model: dict[str, list[Suggestion]],
|
||||
flat: list[tuple[str, str, str]],
|
||||
) -> list[Suggestion]:
|
||||
"""Deduplicate identical suggestions across models, tag consensus,
|
||||
assign conflict groups to overlapping non-identical suggestions, and
|
||||
sort by document position."""
|
||||
total = len(per_model)
|
||||
merged: dict[tuple, Suggestion] = {}
|
||||
for model, suggestions in per_model.items():
|
||||
for s in suggestions:
|
||||
key = (s.op, tuple(s.word_ids), " ".join(s.new_text.lower().split()))
|
||||
existing = merged.get(key)
|
||||
if existing is None:
|
||||
s.models = [model]
|
||||
s.consensus = 1
|
||||
s.total_models = total
|
||||
merged[key] = s
|
||||
else:
|
||||
existing.models.append(model)
|
||||
existing.consensus += 1
|
||||
existing.confidence = max(existing.confidence, s.confidence)
|
||||
|
||||
result = list(merged.values())
|
||||
|
||||
# Conflict groups: suggestions sharing any target word but not merged
|
||||
# above disagree about the same span — reviewer picks at most one.
|
||||
# (insert_after anchors are excluded: inserting after a word does not
|
||||
# conflict with editing that word.)
|
||||
by_word: dict[str, list[int]] = {}
|
||||
for i, s in enumerate(result):
|
||||
if s.op == "insert_after":
|
||||
continue
|
||||
for wid in s.word_ids:
|
||||
by_word.setdefault(wid, []).append(i)
|
||||
parent = list(range(len(result)))
|
||||
|
||||
def find(x: int) -> int:
|
||||
while parent[x] != x:
|
||||
parent[x] = parent[parent[x]]
|
||||
x = parent[x]
|
||||
return x
|
||||
|
||||
for overlapping in by_word.values():
|
||||
for other in overlapping[1:]:
|
||||
parent[find(other)] = find(overlapping[0])
|
||||
roots: dict[int, list[int]] = {}
|
||||
for i in range(len(result)):
|
||||
roots.setdefault(find(i), []).append(i)
|
||||
for members in roots.values():
|
||||
if len(members) < 2:
|
||||
continue
|
||||
group = str(uuid.uuid4())
|
||||
for i in members:
|
||||
result[i].conflict_group = group
|
||||
|
||||
position = {word_id: i for i, (word_id, _, _) in enumerate(flat)}
|
||||
result.sort(key=lambda s: position.get(s.word_ids[0], 0) if s.word_ids else 0)
|
||||
return result
|
||||
|
||||
# ---- internals ----
|
||||
|
||||
def _call_model(
|
||||
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
|
||||
) -> tuple[Any, Optional[TokenUsage]]:
|
||||
"""Return (parsed_json, token_usage). Usage is None if unreadable."""
|
||||
if model.startswith("claude"):
|
||||
return self._call_anthropic(model, system_prompt, user_prompt, job_id=job_id)
|
||||
return self._call_gemini(model, system_prompt, user_prompt, job_id=job_id)
|
||||
|
||||
@staticmethod
|
||||
def _anthropic_usage(response: Any) -> Optional[TokenUsage]:
|
||||
"""Best-effort usage from an Anthropic response.
|
||||
|
||||
``output_tokens`` already includes adaptive thinking tokens (billed as
|
||||
output); they are not separable here, so thinking_tokens is None.
|
||||
Returns None on any shape problem — usage must never break the call.
|
||||
"""
|
||||
try:
|
||||
u = response.usage
|
||||
return TokenUsage(
|
||||
input_tokens=int(getattr(u, "input_tokens", 0) or 0),
|
||||
output_tokens=int(getattr(u, "output_tokens", 0) or 0),
|
||||
cache_read_tokens=int(getattr(u, "cache_read_input_tokens", 0) or 0),
|
||||
thinking_tokens=None,
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("auto-correct: could not read Anthropic usage", exc_info=True)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _gemini_usage(response: Any) -> Optional[TokenUsage]:
|
||||
"""Best-effort usage from a Gemini (Vertex) response.
|
||||
|
||||
Gemini reports thinking separately (``thoughts_token_count``); it is
|
||||
billed at the output rate, so it's folded into output_tokens and also
|
||||
reported separately for visibility. Returns None on any shape problem.
|
||||
"""
|
||||
try:
|
||||
u = response.usage_metadata
|
||||
prompt = int(getattr(u, "prompt_token_count", 0) or 0)
|
||||
candidates = int(getattr(u, "candidates_token_count", 0) or 0)
|
||||
thoughts = int(getattr(u, "thoughts_token_count", 0) or 0)
|
||||
cached = int(getattr(u, "cached_content_token_count", 0) or 0)
|
||||
return TokenUsage(
|
||||
input_tokens=prompt,
|
||||
output_tokens=candidates + thoughts,
|
||||
cache_read_tokens=cached,
|
||||
thinking_tokens=thoughts,
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("auto-correct: could not read Gemini usage", exc_info=True)
|
||||
return None
|
||||
|
||||
def _call_anthropic(
|
||||
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
|
||||
) -> tuple[Any, Optional[TokenUsage]]:
|
||||
import os
|
||||
|
||||
import anthropic
|
||||
|
||||
if not os.environ.get("ANTHROPIC_API_KEY"):
|
||||
# No silent fallback to another provider — surface the
|
||||
# misconfiguration so it gets fixed, not masked.
|
||||
logger.error(
|
||||
"auto-correct model %s requires ANTHROPIC_API_KEY which is not set "
|
||||
"(job=%s)", model, job_id,
|
||||
)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model is not configured", status_code=502
|
||||
)
|
||||
|
||||
# Structured outputs require additionalProperties: false on objects;
|
||||
# the Vertex variant of the schema omits it, so inject here. Deep-copy
|
||||
# because the google-genai SDK mutates schema dicts in place (it adds
|
||||
# 'property_ordering', which the Anthropic API rejects).
|
||||
import copy
|
||||
|
||||
base = copy.deepcopy(RESPONSE_SCHEMA)
|
||||
for obj in (base, base["properties"]["suggestions"]["items"]):
|
||||
obj.pop("property_ordering", None)
|
||||
obj.pop("propertyOrdering", None)
|
||||
obj["additionalProperties"] = False
|
||||
strict_schema = base
|
||||
client = anthropic.Anthropic(timeout=120.0)
|
||||
try:
|
||||
response = client.messages.create(
|
||||
model=model,
|
||||
max_tokens=16000,
|
||||
system=system_prompt,
|
||||
messages=[{"role": "user", "content": user_prompt}],
|
||||
thinking={"type": "adaptive"},
|
||||
output_config={"format": {"type": "json_schema", "schema": strict_schema}},
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception("auto-correct model call failed job=%s model=%s", job_id, model)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model call failed", status_code=502
|
||||
) from exc
|
||||
usage = self._anthropic_usage(response)
|
||||
try:
|
||||
text = next(b.text for b in response.content if b.type == "text")
|
||||
return json.loads(text), usage
|
||||
except (StopIteration, json.JSONDecodeError, TypeError) as exc:
|
||||
logger.exception(
|
||||
"auto-correct model returned non-JSON job=%s model=%s", job_id, model
|
||||
)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI returned non-JSON output", status_code=502
|
||||
) from exc
|
||||
|
||||
def _call_gemini(
|
||||
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
|
||||
) -> tuple[Any, Optional[TokenUsage]]:
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=self.settings.google_cloud_project,
|
||||
location="global",
|
||||
# Milliseconds; bounds the call so a hung model never strands the UI.
|
||||
http_options=types.HttpOptions(timeout=120_000),
|
||||
)
|
||||
# Deep-copy: the google-genai SDK mutates the schema dict in place,
|
||||
# which would poison the shared module-level constant for other
|
||||
# providers running in the same process.
|
||||
import copy
|
||||
|
||||
try:
|
||||
response = client.models.generate_content(
|
||||
model=model,
|
||||
contents=[user_prompt],
|
||||
config=types.GenerateContentConfig(
|
||||
system_instruction=system_prompt,
|
||||
response_mime_type="application/json",
|
||||
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
|
||||
),
|
||||
)
|
||||
except Exception as exc: # surface as 502, never a stuck job
|
||||
logger.exception("auto-correct model call failed job=%s model=%s", job_id, model)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model call failed", status_code=502
|
||||
) from exc
|
||||
usage = self._gemini_usage(response)
|
||||
try:
|
||||
return json.loads(response.text), usage
|
||||
except (json.JSONDecodeError, TypeError) as exc:
|
||||
logger.exception(
|
||||
"auto-correct model returned non-JSON job=%s model=%s", job_id, model
|
||||
)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI returned non-JSON output", status_code=502
|
||||
) from exc
|
||||
|
||||
def _validate(
|
||||
self,
|
||||
raw: Any,
|
||||
flat: list[tuple[str, str, str]],
|
||||
settings: AutoCorrectSettings,
|
||||
) -> tuple[list[Suggestion], list[str]]:
|
||||
if not isinstance(raw, dict) or not isinstance(raw.get("suggestions"), list):
|
||||
raise AutoCorrectServiceError(
|
||||
"AI response missing 'suggestions' list", status_code=502
|
||||
)
|
||||
n = len(flat)
|
||||
out: list[Suggestion] = []
|
||||
warnings: list[str] = []
|
||||
for i, s in enumerate(raw["suggestions"]):
|
||||
problem = self._check(s, n, settings)
|
||||
if problem:
|
||||
warnings.append(f"dropped suggestion {i}: {problem}")
|
||||
continue
|
||||
start, end = int(s["start_idx"]), int(s["end_idx"])
|
||||
if s["op"] == "insert_after":
|
||||
word_ids = [flat[start][0]]
|
||||
segment_ids = [flat[start][2]]
|
||||
original_text = ""
|
||||
else:
|
||||
span = flat[start : end + 1]
|
||||
word_ids = [w[0] for w in span]
|
||||
segment_ids = sorted({w[2] for w in span})
|
||||
original_text = " ".join(w[1] for w in span)
|
||||
out.append(
|
||||
Suggestion(
|
||||
id=str(uuid.uuid4()),
|
||||
op=s["op"],
|
||||
word_ids=word_ids,
|
||||
segment_ids=segment_ids,
|
||||
original_text=original_text,
|
||||
new_text="" if s["op"] == "delete" else str(s["new_text"]).strip(),
|
||||
reason=str(s.get("reason", "")),
|
||||
category=s["category"] if s.get("category") in VALID_CATEGORIES else "other",
|
||||
confidence=max(0.0, min(1.0, float(s["confidence"]))),
|
||||
)
|
||||
)
|
||||
return out, warnings
|
||||
|
||||
@staticmethod
|
||||
def _check(s: Any, n_words: int, settings: AutoCorrectSettings) -> Optional[str]:
|
||||
if not isinstance(s, dict):
|
||||
return "not an object"
|
||||
op = s.get("op")
|
||||
if op not in VALID_OPS:
|
||||
return f"invalid op {op!r}"
|
||||
try:
|
||||
start, end = int(s["start_idx"]), int(s["end_idx"])
|
||||
confidence = float(s["confidence"])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return "missing/invalid indices or confidence"
|
||||
if not (0 <= start <= end < n_words):
|
||||
return f"indices out of range ({start}..{end} of {n_words})"
|
||||
if op == "insert_after" and not settings.allow_insertions:
|
||||
return "insertions disabled by settings"
|
||||
if op == "insert_after" and start != end:
|
||||
return "insert_after requires start_idx == end_idx"
|
||||
new_text = str(s.get("new_text", "")).strip()
|
||||
if op in ("replace", "insert_after") and not new_text:
|
||||
return f"{op} with empty new_text"
|
||||
if op == "delete" and new_text:
|
||||
return "delete with non-empty new_text"
|
||||
if confidence < settings.min_confidence:
|
||||
return f"confidence {confidence:.2f} below threshold"
|
||||
if (
|
||||
s.get("category") == "adlib_removal"
|
||||
and not settings.suggest_adlib_removal
|
||||
):
|
||||
return "adlib removal disabled by settings"
|
||||
return None
|
||||
|
||||
|
||||
_service_instance: Optional[AutoCorrectService] = None
|
||||
|
||||
|
||||
def get_auto_correct_service() -> AutoCorrectService:
|
||||
global _service_instance
|
||||
if _service_instance is None:
|
||||
_service_instance = AutoCorrectService()
|
||||
return _service_instance
|
||||
@@ -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)
|
||||
@@ -350,6 +350,7 @@ class EncodingService:
|
||||
timeout: float = 30.0,
|
||||
job_id: str = "unknown",
|
||||
path: Optional[str] = None,
|
||||
allow_failover: bool = True,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Make an HTTP request with retry logic for transient failures.
|
||||
@@ -371,6 +372,13 @@ class EncodingService:
|
||||
fallback VM in another zone) and invalidate the URL cache; the
|
||||
next retry then targets the freshly-routed URL instead of the
|
||||
original primary which is dead.
|
||||
allow_failover: When True (default), a connection error fires the
|
||||
fallback-VM warmup and lets retries re-resolve the URL. Set False
|
||||
for requests pinned to a specific worker (in-flight status polls):
|
||||
a pinned poll must never re-route to active_url nor spin up a
|
||||
fallback VM, because a different/fresh VM cannot have the job — it
|
||||
would only return "not found" and orphan a render that is actually
|
||||
succeeding on the pinned worker (incident 2026-06-16, job d3af33ae).
|
||||
|
||||
Returns:
|
||||
Dict with keys:
|
||||
@@ -392,7 +400,7 @@ class EncodingService:
|
||||
# active_override change made by the warmup actually takes effect.
|
||||
# Without this, all 8 retry attempts hammer the original (dead)
|
||||
# URL even though the warmup successfully routed to a fallback VM.
|
||||
if path and warmup_ran and self._worker_manager is not None:
|
||||
if allow_failover and path and warmup_ran and self._worker_manager is not None:
|
||||
resolved = f"{self._get_worker_url()}{path}"
|
||||
if resolved != url:
|
||||
logger.info(
|
||||
@@ -424,7 +432,7 @@ class EncodingService:
|
||||
}
|
||||
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError, asyncio.TimeoutError) as e:
|
||||
last_exception = e
|
||||
if attempt == 0:
|
||||
if allow_failover and attempt == 0:
|
||||
try:
|
||||
await self._warmup_encoding_worker_fallback(job_id)
|
||||
warmup_ran = True
|
||||
@@ -530,12 +538,23 @@ class EncodingService:
|
||||
|
||||
return resp["json"]
|
||||
|
||||
async def get_job_status(self, job_id: str) -> Dict[str, Any]:
|
||||
async def get_job_status(
|
||||
self, job_id: str, worker_url: Optional[str] = None
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Get the status of an encoding job.
|
||||
|
||||
Args:
|
||||
job_id: Job identifier
|
||||
worker_url: When set, pin the request to this worker base URL instead
|
||||
of resolving the current active_url. In-flight polls must stay on
|
||||
the worker that accepted the job: a blue-green deploy can swap the
|
||||
active_url primary pointer mid-render, and an unpinned poll would
|
||||
migrate to the new primary — which never received the job and 404s
|
||||
"not found", orphaning a render that is succeeding on the original
|
||||
worker (incident 2026-06-16, job d3af33ae). A pinned poll also
|
||||
disables failover (allow_failover=False) so it never re-routes nor
|
||||
starts a fallback VM.
|
||||
|
||||
Returns:
|
||||
Job status including: status, progress, error, output_files
|
||||
@@ -546,7 +565,10 @@ class EncodingService:
|
||||
raise RuntimeError("Encoding service not configured")
|
||||
|
||||
path = f"/status/{job_id}"
|
||||
url = f"{self._get_worker_url()}{path}"
|
||||
if worker_url:
|
||||
url = f"{worker_url}{path}"
|
||||
else:
|
||||
url = f"{self._get_worker_url()}{path}"
|
||||
headers = {"X-API-Key": self._api_key}
|
||||
|
||||
resp = await self._request_with_retry(
|
||||
@@ -555,7 +577,10 @@ class EncodingService:
|
||||
headers=headers,
|
||||
timeout=30.0,
|
||||
job_id=job_id,
|
||||
path=path,
|
||||
# When pinned, never re-resolve or fail over — the job lives on this
|
||||
# exact worker; do not pass `path` (which drives re-resolution).
|
||||
path=None if worker_url else path,
|
||||
allow_failover=not worker_url,
|
||||
)
|
||||
|
||||
if resp["status"] == 401:
|
||||
@@ -573,6 +598,7 @@ class EncodingService:
|
||||
poll_interval: float = 10.0,
|
||||
timeout: float = 3600.0,
|
||||
progress_callback=None,
|
||||
worker_url: Optional[str] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Poll for encoding job completion with tolerance for transient failures.
|
||||
@@ -587,6 +613,11 @@ class EncodingService:
|
||||
poll_interval: Seconds between status checks
|
||||
timeout: Maximum time to wait (default 1 hour)
|
||||
progress_callback: Optional callback(progress: int) for progress updates
|
||||
worker_url: Worker base URL the job was submitted to. When set, every
|
||||
poll is pinned to this worker (see get_job_status) so a mid-render
|
||||
blue-green primary swap can't migrate the poll to a worker that
|
||||
never received the job. When None, polls resolve active_url (legacy
|
||||
behaviour, e.g. direct callers/tests).
|
||||
|
||||
Returns:
|
||||
Final job status with output files
|
||||
@@ -607,7 +638,7 @@ class EncodingService:
|
||||
raise TimeoutError(f"Encoding job {job_id} timed out after {timeout}s")
|
||||
|
||||
try:
|
||||
status = await self.get_job_status(job_id)
|
||||
status = await self.get_job_status(job_id, worker_url=worker_url)
|
||||
# Reset failure counter on successful poll
|
||||
consecutive_failures = 0
|
||||
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError,
|
||||
@@ -708,11 +739,14 @@ class EncodingService:
|
||||
if submit_status == "in_progress":
|
||||
logger.info(f"[job:{job_id}] Encoding already in progress, joining poll")
|
||||
|
||||
# Pin polls to the worker the job landed on (see render_video_on_gce).
|
||||
pinned_url = self._get_worker_url()
|
||||
|
||||
# Wait for completion (still holding the slot — the worker is
|
||||
# actually doing CPU work for `job_id` until poll returns
|
||||
# complete/failed).
|
||||
return await self.wait_for_completion(
|
||||
job_id, progress_callback=progress_callback
|
||||
job_id, progress_callback=progress_callback, worker_url=pinned_url
|
||||
)
|
||||
|
||||
async def submit_preview_encoding_job(
|
||||
@@ -837,11 +871,15 @@ class EncodingService:
|
||||
if submit_status == "in_progress":
|
||||
logger.info(f"[job:{job_id}] Preview encoding already in progress, waiting")
|
||||
|
||||
# Pin polls to the worker the job landed on (see render_video_on_gce).
|
||||
pinned_url = self._get_worker_url()
|
||||
|
||||
# Wait for completion with shorter timeout
|
||||
return await self.wait_for_completion(
|
||||
job_id=job_id,
|
||||
poll_interval=poll_interval,
|
||||
timeout=timeout,
|
||||
worker_url=pinned_url,
|
||||
)
|
||||
|
||||
async def submit_render_video_job(
|
||||
@@ -961,11 +999,18 @@ class EncodingService:
|
||||
if submit_status == "in_progress":
|
||||
logger.info(f"[job:{job_id}] Render-video already in progress, joining poll")
|
||||
|
||||
# Pin status polls to the worker the job actually landed on. Resolving
|
||||
# AFTER submit captures a capacity-fallback re-route (warmup invalidates
|
||||
# the URL cache) while being BEFORE any later blue-green deploy swap —
|
||||
# so the poll follows the job, not the floating active_url primary
|
||||
# pointer (incident 2026-06-16, job d3af33ae).
|
||||
pinned_url = self._get_worker_url()
|
||||
|
||||
# Wait for completion (still holding the slot — the worker is
|
||||
# actively rendering for `job_id` until poll returns
|
||||
# complete/failed).
|
||||
return await self.wait_for_completion(
|
||||
job_id, progress_callback=progress_callback
|
||||
job_id, progress_callback=progress_callback, worker_url=pinned_url
|
||||
)
|
||||
|
||||
async def health_check(self) -> Dict[str, Any]:
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
"""Artist/title match-judge: deterministic + catalog + light-AI formatting and
|
||||
match-acceptance decisions for the job-submission flow.
|
||||
|
||||
See docs/archive/2026-06-15-artist-title-matching-rework-plan.md.
|
||||
"""
|
||||
from backend.services.match_judge.verdict import MatchVerdict
|
||||
|
||||
__all__ = ["MatchVerdict"]
|
||||
@@ -0,0 +1,174 @@
|
||||
"""The light-AI layer of the match judge.
|
||||
|
||||
Invoked only when the deterministic+catalog classifier can't decide. Uses a
|
||||
small Vertex Gemini model to judge whether the typed artist/title is a real
|
||||
song, what its canonical formatting is, and whether any change is cosmetic,
|
||||
content-level, or ambiguous. The model call is injectable for testing.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from typing import Awaitable, Callable, Optional
|
||||
|
||||
from backend.services.match_judge.verdict import (
|
||||
KIND_AMBIGUOUS,
|
||||
KIND_CONTENT,
|
||||
KIND_COSMETIC,
|
||||
KIND_NONE,
|
||||
MatchVerdict,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_VALID_KINDS = {KIND_COSMETIC, KIND_CONTENT, KIND_AMBIGUOUS}
|
||||
|
||||
Generate = Callable[[str, str, str], Awaitable[dict]]
|
||||
|
||||
_SYSTEM_PROMPT = (
|
||||
"You normalise song metadata for a karaoke service. Given what a user typed "
|
||||
"for an artist and title (plus optional catalog candidates), decide whether it "
|
||||
"refers to a real, released song and how its artist/title should be formatted.\n"
|
||||
"Return JSON with: kind, confident, canonical_artist, canonical_title, "
|
||||
"alternatives, reason.\n"
|
||||
"kind:\n"
|
||||
" 'cosmetic' – same song, only formatting/casing/punctuation/diacritics differ.\n"
|
||||
" 'content' – the user made a typo or used a wrong/variant title; the correct "
|
||||
"song text differs in actual characters.\n"
|
||||
" 'ambiguous' – more than one plausible song matches; list them in alternatives.\n"
|
||||
" 'none' – already correct, or you cannot confidently suggest anything.\n"
|
||||
"confident: true only when you are sure. Never invent songs. Prefer the user's "
|
||||
"input when unsure (kind='none'). canonical_artist/canonical_title must use "
|
||||
"official formatting. alternatives is a list of {artist,title}."
|
||||
)
|
||||
|
||||
# OpenAPI-style schema handed to the Vertex genai client at runtime.
|
||||
RESPONSE_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"kind": {"type": "string", "enum": ["cosmetic", "content", "ambiguous", "none"]},
|
||||
"confident": {"type": "boolean"},
|
||||
"canonical_artist": {"type": "string"},
|
||||
"canonical_title": {"type": "string"},
|
||||
"alternatives": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"artist": {"type": "string"},
|
||||
"title": {"type": "string"},
|
||||
},
|
||||
},
|
||||
},
|
||||
"reason": {"type": "string"},
|
||||
},
|
||||
"required": ["kind", "confident"],
|
||||
}
|
||||
|
||||
|
||||
def _model() -> str:
|
||||
try:
|
||||
from backend.config import settings
|
||||
return getattr(settings, "match_judge_model", "gemini-3.5-flash")
|
||||
except Exception: # pragma: no cover - config import guard
|
||||
return "gemini-3.5-flash"
|
||||
|
||||
|
||||
def build_prompts(
|
||||
artist: str, title: str, candidates: list[dict], audio_tier: Optional[int]
|
||||
) -> tuple[str, str]:
|
||||
lines = [f'User typed: artist="{artist}" title="{title}"']
|
||||
if audio_tier is not None:
|
||||
lines.append(
|
||||
f"Audio-search confidence tier: {audio_tier} "
|
||||
"(1 = strong match found, 3 = weak/no results — a weak tier hints the "
|
||||
"title may be misspelled)."
|
||||
)
|
||||
if candidates:
|
||||
lines.append("Catalog candidates (canonical formatting):")
|
||||
for c in candidates:
|
||||
lines.append(f'- {c.get("artist_name", "")} — {c.get("track_name", "")}')
|
||||
else:
|
||||
lines.append("No catalog candidates were found.")
|
||||
return _SYSTEM_PROMPT, "\n".join(lines)
|
||||
|
||||
|
||||
def _verdict_from_response(
|
||||
data: object, *, fallback_artist: str, fallback_title: str
|
||||
) -> MatchVerdict:
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
kind = data.get("kind")
|
||||
if kind not in _VALID_KINDS:
|
||||
return MatchVerdict(
|
||||
KIND_NONE, True, fallback_artist, fallback_title,
|
||||
engine="ai", reason="no suggestion",
|
||||
)
|
||||
canonical_artist = (data.get("canonical_artist") or "").strip() or fallback_artist
|
||||
canonical_title = (data.get("canonical_title") or "").strip() or fallback_title
|
||||
alternatives = []
|
||||
for alt in data.get("alternatives") or []:
|
||||
if isinstance(alt, dict) and alt.get("artist") and alt.get("title"):
|
||||
alternatives.append(
|
||||
{"artist": str(alt["artist"]), "title": str(alt["title"])}
|
||||
)
|
||||
return MatchVerdict(
|
||||
kind=kind,
|
||||
confident=bool(data.get("confident", False)),
|
||||
canonical_artist=canonical_artist,
|
||||
canonical_title=canonical_title,
|
||||
alternatives=alternatives,
|
||||
engine="ai",
|
||||
reason=str(data.get("reason") or ""),
|
||||
)
|
||||
|
||||
|
||||
async def ai_judge_match(
|
||||
artist: str,
|
||||
title: str,
|
||||
candidates: list[dict],
|
||||
audio_tier: Optional[int],
|
||||
*,
|
||||
model: Optional[str] = None,
|
||||
generate: Optional[Generate] = None,
|
||||
) -> MatchVerdict:
|
||||
model = model or _model()
|
||||
gen = generate or _default_generate
|
||||
system_prompt, user_prompt = build_prompts(artist, title, candidates, audio_tier)
|
||||
data = await gen(model, system_prompt, user_prompt)
|
||||
return _verdict_from_response(
|
||||
data, fallback_artist=artist, fallback_title=title
|
||||
)
|
||||
|
||||
|
||||
async def _default_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
|
||||
return await asyncio.to_thread(_blocking_generate, model, system_prompt, user_prompt)
|
||||
|
||||
|
||||
def _blocking_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
|
||||
import copy
|
||||
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
timeout_ms = int(getattr(settings, "match_judge_timeout_ms", 3000))
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=settings.google_cloud_project,
|
||||
location="global",
|
||||
http_options=types.HttpOptions(timeout=timeout_ms),
|
||||
)
|
||||
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),
|
||||
temperature=0,
|
||||
),
|
||||
)
|
||||
return json.loads(response.text)
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Deterministic + catalog match classification (no AI, no network).
|
||||
|
||||
`classify_catalog_match` returns a confident :class:`MatchVerdict` when the
|
||||
typed artist/title clearly correspond to a catalog candidate (a cosmetic
|
||||
formatting fix, or nothing to change). When it cannot confidently decide, it
|
||||
returns ``None`` — the caller should then escalate to the AI judge.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
from typing import Optional
|
||||
|
||||
from karaoke_gen.utils import normalize_text
|
||||
|
||||
from backend.services.match_judge.verdict import (
|
||||
KIND_COSMETIC,
|
||||
KIND_NONE,
|
||||
MatchVerdict,
|
||||
)
|
||||
|
||||
_NON_ALNUM = re.compile(r"[^0-9a-z\s]")
|
||||
_WS = re.compile(r"\s+")
|
||||
|
||||
|
||||
def _fold_accents(text: str) -> str:
|
||||
"""Drop combining marks so 'Beyoncé' and 'beyonce' compare equal."""
|
||||
decomposed = unicodedata.normalize("NFKD", text)
|
||||
return "".join(c for c in decomposed if not unicodedata.combining(c))
|
||||
|
||||
|
||||
def normalize_for_match(text: str) -> str:
|
||||
"""Aggressive key used only for equality comparison (never displayed).
|
||||
|
||||
Folds casing, accents, punctuation, whitespace, and treats '&' as 'and'.
|
||||
"""
|
||||
s = normalize_text(text or "")
|
||||
s = s.replace("&", " and ")
|
||||
s = _fold_accents(s)
|
||||
s = s.casefold()
|
||||
s = _NON_ALNUM.sub(" ", s)
|
||||
s = _WS.sub(" ", s).strip()
|
||||
return s
|
||||
|
||||
|
||||
def classify_catalog_match(
|
||||
artist: str, title: str, candidates: list[dict]
|
||||
) -> Optional[MatchVerdict]:
|
||||
"""Return a confident verdict from catalog candidates, or None to escalate.
|
||||
|
||||
candidates: dicts with ``artist_name`` and ``track_name`` (Spotify/MB canonical).
|
||||
"""
|
||||
key_artist = normalize_for_match(artist)
|
||||
key_title = normalize_for_match(title)
|
||||
|
||||
for cand in candidates:
|
||||
cand_artist = cand.get("artist_name") or ""
|
||||
cand_title = cand.get("track_name") or ""
|
||||
if (
|
||||
normalize_for_match(cand_artist) == key_artist
|
||||
and normalize_for_match(cand_title) == key_title
|
||||
):
|
||||
# Same song. Cosmetic fix unless the user already typed it exactly.
|
||||
if cand_artist == artist and cand_title == title:
|
||||
return MatchVerdict(
|
||||
kind=KIND_NONE,
|
||||
confident=True,
|
||||
canonical_artist=artist,
|
||||
canonical_title=title,
|
||||
engine="catalog",
|
||||
reason="already canonical",
|
||||
)
|
||||
return MatchVerdict(
|
||||
kind=KIND_COSMETIC,
|
||||
confident=True,
|
||||
canonical_artist=cand_artist,
|
||||
canonical_title=cand_title,
|
||||
engine="catalog",
|
||||
reason="formatting differs from catalog",
|
||||
)
|
||||
|
||||
return None
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Match-judge orchestration.
|
||||
|
||||
Composes the deterministic+catalog classifier with the AI judge. The AI judge
|
||||
runs ONLY when the classifier can't confidently decide, and never blocks or
|
||||
errors the caller — any failure degrades to "no suggestion".
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Awaitable, Callable, Literal, Optional
|
||||
|
||||
from backend.services.match_judge.classifier import classify_catalog_match
|
||||
from backend.services.match_judge.verdict import KIND_NONE, MatchVerdict
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
CATALOG_CANDIDATE_LIMIT = 8
|
||||
|
||||
Stage = Literal["fast", "full"]
|
||||
|
||||
# Audio tiers at or above this are "weak" (poor / no results). A weak tier hints
|
||||
# the typed title may be a typo, so even a confident catalog match is verified
|
||||
# with the AI judge (it can be a junk/misspelled Spotify entry).
|
||||
WEAK_TIER = 3
|
||||
|
||||
SearchTracks = Callable[[str, Optional[str], int], Awaitable[list[dict]]]
|
||||
AiJudge = Callable[[str, str, list[dict], Optional[int]], Awaitable[MatchVerdict]]
|
||||
|
||||
|
||||
async def _default_search_tracks(query: str, artist: Optional[str], limit: int) -> list[dict]:
|
||||
from backend.services.catalog_proxy_service import search_tracks
|
||||
return await search_tracks(query, artist, limit)
|
||||
|
||||
|
||||
async def _default_ai_judge(
|
||||
artist: str, title: str, candidates: list[dict], audio_tier: Optional[int]
|
||||
) -> MatchVerdict:
|
||||
from backend.services.match_judge.ai import ai_judge_match
|
||||
return await ai_judge_match(artist, title, candidates, audio_tier)
|
||||
|
||||
|
||||
def _default_enabled() -> bool:
|
||||
try:
|
||||
from backend.config import settings
|
||||
return bool(getattr(settings, "match_judge_enabled", True))
|
||||
except Exception: # pragma: no cover - config import guard
|
||||
return True
|
||||
|
||||
|
||||
async def judge_match(
|
||||
artist: str,
|
||||
title: str,
|
||||
audio_tier: Optional[int] = None,
|
||||
*,
|
||||
stage: Stage = "full",
|
||||
search_tracks: Optional[SearchTracks] = None,
|
||||
ai_judge: Optional[AiJudge] = None,
|
||||
enabled: Optional[bool] = None,
|
||||
) -> MatchVerdict:
|
||||
"""Return a :class:`MatchVerdict` for the typed artist/title.
|
||||
|
||||
audio_tier: the audio search's confidence tier (1=best..3=poor), used by the
|
||||
AI judge to decide whether weak results suggest a typo. May be None.
|
||||
|
||||
stage:
|
||||
"fast" — catalog-only pass (no AI, tier ignored). Runs in parallel with the
|
||||
audio search so the common cosmetic tidy is ready before results render.
|
||||
Returns the catalog verdict if confident, else a ``needs_ai=True`` marker
|
||||
telling the caller to make a "full" call once the tier is known.
|
||||
"full" — the complete pipeline: catalog, then the AI judge when catalog isn't
|
||||
confident OR (item 4) when a confident catalog match coincides with a weak
|
||||
audio tier (the match may be a junk/typo'd entry — let AI override).
|
||||
"""
|
||||
search = search_tracks or _default_search_tracks
|
||||
ai = ai_judge or _default_ai_judge
|
||||
if enabled is None:
|
||||
enabled = _default_enabled()
|
||||
|
||||
try:
|
||||
candidates = await search(title, artist, CATALOG_CANDIDATE_LIMIT)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"match-judge catalog search failed; continuing without candidates",
|
||||
exc_info=True,
|
||||
)
|
||||
candidates = []
|
||||
|
||||
catalog_verdict = classify_catalog_match(artist, title, candidates)
|
||||
|
||||
# Fast pass: catalog only. Never touches the AI layer.
|
||||
if stage == "fast":
|
||||
if catalog_verdict is not None:
|
||||
return catalog_verdict
|
||||
return MatchVerdict(
|
||||
KIND_NONE, False, artist, title,
|
||||
engine="catalog", reason="needs ai", needs_ai=True,
|
||||
)
|
||||
|
||||
# Full pass.
|
||||
if catalog_verdict is not None:
|
||||
weak = audio_tier is not None and audio_tier >= WEAK_TIER
|
||||
if not (enabled and weak):
|
||||
return catalog_verdict
|
||||
# Item 4: weak audio results make the typo hypothesis plausible even though
|
||||
# the catalog "matched" — verify with AI and let a confident verdict override.
|
||||
try:
|
||||
ai_verdict = await ai(artist, title, candidates, audio_tier)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"match-judge AI verification failed; keeping catalog verdict"
|
||||
)
|
||||
return catalog_verdict
|
||||
if ai_verdict.confident and ai_verdict.kind != KIND_NONE:
|
||||
return ai_verdict
|
||||
return catalog_verdict
|
||||
|
||||
if not enabled:
|
||||
return MatchVerdict(
|
||||
KIND_NONE, True, artist, title, engine="deterministic", reason="ai disabled"
|
||||
)
|
||||
|
||||
try:
|
||||
return await ai(artist, title, candidates, audio_tier)
|
||||
except Exception:
|
||||
logger.exception("match-judge AI call failed; returning no-suggestion")
|
||||
return MatchVerdict(
|
||||
KIND_NONE, True, artist, title, engine="ai", reason="ai failed"
|
||||
)
|
||||
@@ -0,0 +1,47 @@
|
||||
"""The verdict returned by the match judge."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Literal
|
||||
|
||||
|
||||
# kind values:
|
||||
# "cosmetic" – same song, formatting-only fix → apply invisibly
|
||||
# "content" – actual characters change (typo/different title) → surface + maybe re-search
|
||||
# "ambiguous" – more than one plausible song → ask the user first
|
||||
# "none" – nothing to change (already correct, or no confident suggestion)
|
||||
KIND_COSMETIC = "cosmetic"
|
||||
KIND_CONTENT = "content"
|
||||
KIND_AMBIGUOUS = "ambiguous"
|
||||
KIND_NONE = "none"
|
||||
|
||||
|
||||
Kind = Literal["cosmetic", "content", "ambiguous", "none"]
|
||||
Engine = Literal["deterministic", "catalog", "ai"]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MatchVerdict:
|
||||
kind: Kind
|
||||
confident: bool
|
||||
canonical_artist: str
|
||||
canonical_title: str
|
||||
alternatives: list[dict] = field(default_factory=list) # [{"artist","title"}]
|
||||
engine: Engine = "deterministic"
|
||||
reason: str = ""
|
||||
# True only from a "fast" (catalog-only) pass that couldn't confidently decide:
|
||||
# the caller should escalate to a "full" pass (with the audio tier) for an AI
|
||||
# verdict. Always False on a full-pass verdict.
|
||||
needs_ai: bool = False
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"kind": self.kind,
|
||||
"confident": self.confident,
|
||||
"canonical_artist": self.canonical_artist,
|
||||
"canonical_title": self.canonical_title,
|
||||
"alternatives": self.alternatives,
|
||||
"engine": self.engine,
|
||||
"reason": self.reason,
|
||||
"needs_ai": self.needs_ai,
|
||||
}
|
||||
@@ -59,6 +59,17 @@ class StorageService:
|
||||
logger.error(f"Error downloading file {source_path}: {e}")
|
||||
raise
|
||||
|
||||
def copy_blob(self, source_path: str, destination_path: str) -> str:
|
||||
"""Server-side copy of a blob within the bucket (no download/upload)."""
|
||||
try:
|
||||
src = self.bucket.blob(source_path)
|
||||
self.bucket.copy_blob(src, self.bucket, destination_path)
|
||||
logger.info(f"Copied gs://{settings.gcs_bucket_name}/{source_path} -> {destination_path}")
|
||||
return destination_path
|
||||
except Exception as e:
|
||||
logger.error(f"Error copying blob {source_path} -> {destination_path}: {e}")
|
||||
raise
|
||||
|
||||
def generate_signed_url(self, blob_path: str, expiration_minutes: int = 60) -> str:
|
||||
"""Generate a signed URL for downloading a file.
|
||||
|
||||
|
||||
@@ -410,6 +410,34 @@ class WorkerService:
|
||||
async def trigger_screens_worker(self, job_id: str) -> bool:
|
||||
"""Trigger screen generation worker."""
|
||||
return await self.trigger_worker("screens", job_id)
|
||||
|
||||
async def trigger_auto_correct(self, job_id: str, timeout_seconds: int = 200) -> bool:
|
||||
"""Trigger proactive auto-correct generation on the API service.
|
||||
|
||||
Direct, awaited HTTP call (NOT Cloud Tasks): the endpoint runs the work
|
||||
synchronously, so awaiting it keeps both the caller (lyrics job) and the
|
||||
service instance alive until the cache is written. Best-effort — returns
|
||||
False on any failure and never raises, so it can't affect the job.
|
||||
"""
|
||||
if not self._base_url:
|
||||
logger.info(f"[job:{job_id}] auto-correct trigger skipped: no service base URL")
|
||||
return False
|
||||
url = f"{self._base_url}/api/internal/workers/auto-correct"
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if self._admin_token:
|
||||
headers["X-Admin-Token"] = self._admin_token
|
||||
# Propagate trace context so the service-side span links to this job.
|
||||
headers = inject_trace_context(headers)
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=timeout_seconds) as client:
|
||||
resp = await client.post(url, json={"job_id": job_id}, headers=headers)
|
||||
logger.info(
|
||||
f"[job:{job_id}] auto-correct trigger -> HTTP {resp.status_code}"
|
||||
)
|
||||
return resp.status_code < 400
|
||||
except Exception as e: # noqa: BLE001 — best-effort, never fatal
|
||||
logger.warning(f"[job:{job_id}] auto-correct trigger failed (non-fatal): {e}")
|
||||
return False
|
||||
|
||||
def _warmup_encoding_worker(self, job_id: str) -> None:
|
||||
"""Fire-and-forget warmup of the encoding worker VM.
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Route tests for POST /api/review/{job_id}/auto-correct."""
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.main import app
|
||||
from backend.services.auto_correct.service import (
|
||||
AutoCorrectResult,
|
||||
AutoCorrectServiceError,
|
||||
Suggestion,
|
||||
)
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def bypass_auth(monkeypatch):
|
||||
"""Bypass require_review_auth for these tests."""
|
||||
from backend.api.dependencies import require_review_auth as real_dep
|
||||
|
||||
async def fake_dep():
|
||||
return ("test-job", "full")
|
||||
|
||||
app.dependency_overrides[real_dep] = fake_dep
|
||||
yield
|
||||
app.dependency_overrides.pop(real_dep, None)
|
||||
|
||||
|
||||
def _override_service(result_or_exc):
|
||||
from backend.api.routes.review import _get_auto_correct_service_dep
|
||||
|
||||
mock_service = MagicMock()
|
||||
if isinstance(result_or_exc, Exception):
|
||||
mock_service.suggest.side_effect = result_or_exc
|
||||
else:
|
||||
mock_service.suggest.return_value = result_or_exc
|
||||
app.dependency_overrides[_get_auto_correct_service_dep] = lambda: mock_service
|
||||
return mock_service
|
||||
|
||||
|
||||
def teardown_function(_): # noqa: ANN001
|
||||
from backend.api.routes.review import _get_auto_correct_service_dep
|
||||
|
||||
app.dependency_overrides.pop(_get_auto_correct_service_dep, None)
|
||||
|
||||
|
||||
def _make_result(suggestions=None) -> AutoCorrectResult:
|
||||
return AutoCorrectResult(
|
||||
suggestions=suggestions
|
||||
if suggestions is not None
|
||||
else [
|
||||
Suggestion(
|
||||
id="sug-1",
|
||||
op="replace",
|
||||
word_ids=["w3"],
|
||||
segment_ids=["seg-1"],
|
||||
original_text="glory",
|
||||
new_text="chlorine",
|
||||
reason="matches reference",
|
||||
category="mishearing",
|
||||
confidence=0.95,
|
||||
)
|
||||
],
|
||||
model="gemini-test",
|
||||
elapsed_seconds=12.3,
|
||||
settings_applied=AutoCorrectSettings(),
|
||||
warnings=["dropped suggestion 3: out of range"],
|
||||
)
|
||||
|
||||
|
||||
BODY = {
|
||||
"segments": [{"id": "seg-1", "words": [{"id": "w3", "text": "glory"}]}],
|
||||
"reference_lyrics": {"genius": {"segments": [{"text": "chlorine"}]}},
|
||||
"artist": "Twenty One Pilots",
|
||||
"title": "Chlorine",
|
||||
}
|
||||
|
||||
|
||||
def test_happy_path(client: TestClient) -> None:
|
||||
mock = _override_service(_make_result())
|
||||
resp = client.post("/api/review/test-job/auto-correct", json=BODY)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["model"] == "gemini-test"
|
||||
assert len(data["suggestions"]) == 1
|
||||
s = data["suggestions"][0]
|
||||
assert s["op"] == "replace"
|
||||
assert s["word_ids"] == ["w3"]
|
||||
assert s["new_text"] == "chlorine"
|
||||
assert data["warnings"] == ["dropped suggestion 3: out of range"]
|
||||
assert data["settings_applied"]["suggest_adlib_removal"] is True
|
||||
mock.suggest.assert_called_once()
|
||||
|
||||
|
||||
def test_settings_passed_through(client: TestClient) -> None:
|
||||
mock = _override_service(_make_result([]))
|
||||
resp = client.post(
|
||||
"/api/review/test-job/auto-correct",
|
||||
json={**BODY, "settings": {"suggest_adlib_removal": False, "min_confidence": 0.8}},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
settings = mock.suggest.call_args.kwargs["settings"]
|
||||
assert settings.suggest_adlib_removal is False
|
||||
assert settings.min_confidence == 0.8
|
||||
|
||||
|
||||
def test_invalid_settings_400(client: TestClient) -> None:
|
||||
_override_service(_make_result([]))
|
||||
resp = client.post(
|
||||
"/api/review/test-job/auto-correct",
|
||||
json={**BODY, "settings": {"bogus_knob": True}},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
assert "invalid settings" in resp.json()["detail"]
|
||||
|
||||
|
||||
def test_no_references_422_propagates(client: TestClient) -> None:
|
||||
_override_service(AutoCorrectServiceError("no reference lyrics", status_code=422))
|
||||
resp = client.post("/api/review/test-job/auto-correct", json=BODY)
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
def test_model_failure_502_propagates(client: TestClient) -> None:
|
||||
_override_service(AutoCorrectServiceError("AI model call failed", status_code=502))
|
||||
resp = client.post("/api/review/test-job/auto-correct", json=BODY)
|
||||
assert resp.status_code == 502
|
||||
|
||||
|
||||
def test_missing_body_fields_422(client: TestClient) -> None:
|
||||
_override_service(_make_result([]))
|
||||
resp = client.post("/api/review/test-job/auto-correct", json={"segments": []})
|
||||
assert resp.status_code == 422 # reference_lyrics is required
|
||||
Whitespace-only changes.
@@ -0,0 +1,203 @@
|
||||
"""Tests for the per-job auto-correct suggestion cache."""
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from backend.services.auto_correct.service import (
|
||||
AutoCorrectResult,
|
||||
AutoCorrectService,
|
||||
Suggestion,
|
||||
)
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
|
||||
SEGMENTS = [
|
||||
{
|
||||
"id": "seg-1",
|
||||
"words": [
|
||||
{"id": "w0", "text": "straight"},
|
||||
{"id": "w1", "text": "glory"},
|
||||
],
|
||||
},
|
||||
]
|
||||
REFS = {"genius": {"segments": [{"text": "straight chlorine"}]}}
|
||||
RAW = {
|
||||
"suggestions": [
|
||||
{
|
||||
"op": "replace",
|
||||
"start_idx": 1,
|
||||
"end_idx": 1,
|
||||
"new_text": "chlorine",
|
||||
"reason": "r",
|
||||
"category": "mishearing",
|
||||
"confidence": 0.9,
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
FLAT = [("w0", "straight", "seg-1"), ("w1", "glory", "seg-1")]
|
||||
|
||||
|
||||
def _suggest(service, **overrides):
|
||||
kwargs = dict(
|
||||
job_id="job-1",
|
||||
segments=SEGMENTS,
|
||||
reference_lyrics=REFS,
|
||||
artist="A",
|
||||
title="T",
|
||||
settings=AutoCorrectSettings(),
|
||||
)
|
||||
kwargs.update(overrides)
|
||||
return service.suggest(**kwargs)
|
||||
|
||||
|
||||
def test_cache_hit_skips_model_call() -> None:
|
||||
service = AutoCorrectService()
|
||||
cached_result = AutoCorrectResult(
|
||||
suggestions=[
|
||||
Suggestion(
|
||||
id="cached-1",
|
||||
op="replace",
|
||||
word_ids=["w1"],
|
||||
segment_ids=["seg-1"],
|
||||
original_text="glory",
|
||||
new_text="chlorine",
|
||||
reason="r",
|
||||
category="mishearing",
|
||||
confidence=0.9,
|
||||
)
|
||||
],
|
||||
model="claude-fable-5",
|
||||
elapsed_seconds=0.0,
|
||||
settings_applied=AutoCorrectSettings(),
|
||||
cached=True,
|
||||
)
|
||||
with patch.object(service, "_cache_get", return_value=cached_result), \
|
||||
patch.object(service, "_call_model") as call, \
|
||||
patch.object(service, "_cache_put") as put:
|
||||
result = _suggest(service)
|
||||
call.assert_not_called()
|
||||
put.assert_not_called()
|
||||
assert result.cached is True
|
||||
assert result.suggestions[0].id == "cached-1"
|
||||
|
||||
|
||||
def test_cache_miss_calls_model_and_writes_cache() -> None:
|
||||
service = AutoCorrectService()
|
||||
with patch.object(service, "_cache_get", return_value=None), \
|
||||
patch.object(service, "_call_model", return_value=(RAW, None)) as call, \
|
||||
patch.object(service, "_cache_put") as put:
|
||||
result = _suggest(service)
|
||||
call.assert_called_once()
|
||||
put.assert_called_once()
|
||||
assert result.cached is False
|
||||
assert put.call_args.args[1] is result
|
||||
|
||||
|
||||
def test_cache_key_stable_for_identical_input() -> None:
|
||||
s = AutoCorrectSettings()
|
||||
k1 = AutoCorrectService._cache_path("j", ["m"], s, FLAT, REFS, "A", "T")
|
||||
k2 = AutoCorrectService._cache_path("j", ["m"], s, FLAT, REFS, "A", "T")
|
||||
assert k1 == k2
|
||||
assert k1.startswith("jobs/j/lyrics/auto_correct_cache/")
|
||||
|
||||
|
||||
def test_cache_key_changes_with_input() -> None:
|
||||
s = AutoCorrectSettings()
|
||||
base = AutoCorrectService._cache_path("j", ["m"], s, FLAT, REFS, "A", "T")
|
||||
edited_words = [("w0", "straight", "seg-1"), ("w1", "chlorine", "seg-1")]
|
||||
assert AutoCorrectService._cache_path("j", ["m"], s, edited_words, REFS, "A", "T") != base
|
||||
assert AutoCorrectService._cache_path("j", ["m", "m2"], s, FLAT, REFS, "A", "T") != base
|
||||
other_settings = AutoCorrectSettings(min_confidence=0.8)
|
||||
assert AutoCorrectService._cache_path("j", ["m"], other_settings, FLAT, REFS, "A", "T") != base
|
||||
other_refs = {"genius": {"segments": [{"text": "different text"}]}}
|
||||
assert AutoCorrectService._cache_path("j", ["m"], s, FLAT, other_refs, "A", "T") != base
|
||||
|
||||
|
||||
def test_cache_get_round_trips_via_storage_payload() -> None:
|
||||
"""_cache_put's payload must be readable by _cache_get."""
|
||||
service = AutoCorrectService()
|
||||
stored = {}
|
||||
|
||||
class FakeBlob:
|
||||
def exists(self):
|
||||
return bool(stored)
|
||||
|
||||
class FakeStorage:
|
||||
class bucket: # noqa: N801 - mimic attribute access
|
||||
@staticmethod
|
||||
def blob(path):
|
||||
return FakeBlob()
|
||||
|
||||
@staticmethod
|
||||
def upload_json(path, data):
|
||||
stored[path] = data
|
||||
|
||||
@staticmethod
|
||||
def download_json(path):
|
||||
return stored[path]
|
||||
|
||||
with patch.object(service, "_get_storage", return_value=FakeStorage()):
|
||||
original = AutoCorrectResult(
|
||||
suggestions=[
|
||||
Suggestion(
|
||||
id="s1",
|
||||
op="replace",
|
||||
word_ids=["w1"],
|
||||
segment_ids=["seg-1"],
|
||||
original_text="glory",
|
||||
new_text="chlorine",
|
||||
reason="r",
|
||||
category="mishearing",
|
||||
confidence=0.9,
|
||||
models=["m1", "m2"],
|
||||
consensus=2,
|
||||
total_models=2,
|
||||
conflict_group=None,
|
||||
)
|
||||
],
|
||||
model="m1, m2",
|
||||
elapsed_seconds=5.0,
|
||||
settings_applied=AutoCorrectSettings(compare_models=True),
|
||||
warnings=["w"],
|
||||
)
|
||||
service._cache_put("p", original)
|
||||
restored = service._cache_get("p")
|
||||
|
||||
assert restored is not None
|
||||
assert restored.cached is True
|
||||
assert restored.model == "m1, m2"
|
||||
assert restored.warnings == ["w"]
|
||||
assert restored.settings_applied == AutoCorrectSettings(compare_models=True)
|
||||
s = restored.suggestions[0]
|
||||
assert s.consensus == 2 and s.models == ["m1", "m2"]
|
||||
|
||||
|
||||
def test_corrupt_cache_entry_is_a_miss() -> None:
|
||||
service = AutoCorrectService()
|
||||
|
||||
class FakeBlob:
|
||||
def exists(self):
|
||||
return True
|
||||
|
||||
class FakeStorage:
|
||||
class bucket: # noqa: N801
|
||||
@staticmethod
|
||||
def blob(path):
|
||||
return FakeBlob()
|
||||
|
||||
@staticmethod
|
||||
def download_json(path):
|
||||
return {"suggestions": [{"bogus": True}], "model": "m"}
|
||||
|
||||
with patch.object(service, "_get_storage", return_value=FakeStorage()):
|
||||
assert service._cache_get("p") is None
|
||||
|
||||
|
||||
def test_storage_failure_never_breaks_request() -> None:
|
||||
service = AutoCorrectService()
|
||||
with patch.object(service, "_get_storage", side_effect=RuntimeError("no gcs")), \
|
||||
patch.object(service, "_call_model", return_value=(RAW, None)):
|
||||
result = _suggest(service)
|
||||
assert result.cached is False
|
||||
assert len(result.suggestions) == 1
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Tests for multi-model compare: parallel calls, dedup, consensus, conflicts."""
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services.auto_correct.service import (
|
||||
AutoCorrectService,
|
||||
AutoCorrectServiceError,
|
||||
)
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
|
||||
SEGMENTS = [
|
||||
{
|
||||
"id": "seg-1",
|
||||
"words": [
|
||||
{"id": "w0", "text": "Sippin'"},
|
||||
{"id": "w1", "text": "on"},
|
||||
{"id": "w2", "text": "straight"},
|
||||
{"id": "w3", "text": "glory"},
|
||||
{"id": "w4", "text": "today"},
|
||||
],
|
||||
},
|
||||
]
|
||||
REFS = {"genius": {"segments": [{"text": "Sippin' on straight chlorine"}]}}
|
||||
COMPARE = AutoCorrectSettings(compare_models=True)
|
||||
|
||||
|
||||
def _sugg(start, end, text, op="replace", confidence=0.9):
|
||||
return {
|
||||
"op": op,
|
||||
"start_idx": start,
|
||||
"end_idx": end,
|
||||
"new_text": text,
|
||||
"reason": "r",
|
||||
"category": "mishearing",
|
||||
"confidence": confidence,
|
||||
}
|
||||
|
||||
|
||||
def _run_compare(responses_by_model, compare_models_env="model-a;model-b",
|
||||
settings=COMPARE, single_model="gemini-3.1-pro-preview"):
|
||||
"""responses_by_model: model name -> raw dict response or Exception."""
|
||||
service = AutoCorrectService()
|
||||
|
||||
def fake_call(model, system_prompt, user_prompt, *, job_id):
|
||||
resp = responses_by_model[model]
|
||||
if isinstance(resp, Exception):
|
||||
raise resp
|
||||
# _call_model now returns (parsed_json, token_usage).
|
||||
return resp, None
|
||||
|
||||
with patch.object(
|
||||
service.settings, "auto_correct_compare_models", compare_models_env
|
||||
), patch.object(
|
||||
service.settings, "auto_correct_model", single_model
|
||||
), patch.object(service, "_cache_get", return_value=None), \
|
||||
patch.object(service, "_cache_put"), \
|
||||
patch.object(service, "_call_model", side_effect=fake_call):
|
||||
return service.suggest(
|
||||
job_id="job-1",
|
||||
segments=SEGMENTS,
|
||||
reference_lyrics=REFS,
|
||||
artist="A",
|
||||
title="T",
|
||||
settings=settings,
|
||||
)
|
||||
|
||||
|
||||
def test_identical_suggestions_deduped_with_consensus() -> None:
|
||||
result = _run_compare({
|
||||
"model-a": {"suggestions": [_sugg(3, 3, "chlorine", confidence=0.9)]},
|
||||
"model-b": {"suggestions": [_sugg(3, 3, "chlorine", confidence=0.95)]},
|
||||
})
|
||||
assert len(result.suggestions) == 1
|
||||
s = result.suggestions[0]
|
||||
assert sorted(s.models) == ["model-a", "model-b"]
|
||||
assert s.consensus == 2
|
||||
assert s.total_models == 2
|
||||
assert s.confidence == 0.95 # max across models
|
||||
assert s.conflict_group is None
|
||||
assert result.model == "model-a, model-b"
|
||||
|
||||
|
||||
def test_conflicting_suggestions_share_group() -> None:
|
||||
result = _run_compare({
|
||||
"model-a": {"suggestions": [_sugg(3, 3, "chlorine")]},
|
||||
"model-b": {"suggestions": [_sugg(2, 3, "straight chlorine gas")]},
|
||||
})
|
||||
assert len(result.suggestions) == 2
|
||||
groups = {s.conflict_group for s in result.suggestions}
|
||||
assert len(groups) == 1 and None not in groups
|
||||
assert all(s.consensus == 1 and s.total_models == 2 for s in result.suggestions)
|
||||
|
||||
|
||||
def test_non_overlapping_suggestions_have_no_group() -> None:
|
||||
result = _run_compare({
|
||||
"model-a": {"suggestions": [_sugg(3, 3, "chlorine")]},
|
||||
"model-b": {"suggestions": [_sugg(0, 0, "Sipping")]},
|
||||
})
|
||||
assert all(s.conflict_group is None for s in result.suggestions)
|
||||
# sorted by document position
|
||||
assert [s.word_ids[0] for s in result.suggestions] == ["w0", "w3"]
|
||||
|
||||
|
||||
def test_insert_after_does_not_conflict_with_replace_on_anchor() -> None:
|
||||
result = _run_compare({
|
||||
"model-a": {"suggestions": [_sugg(3, 3, "chlorine")]},
|
||||
"model-b": {"suggestions": [_sugg(3, 3, "up", op="insert_after")]},
|
||||
})
|
||||
assert all(s.conflict_group is None for s in result.suggestions)
|
||||
|
||||
|
||||
def test_one_model_failing_produces_warning_not_error() -> None:
|
||||
result = _run_compare({
|
||||
"model-a": {"suggestions": [_sugg(3, 3, "chlorine")]},
|
||||
"model-b": AutoCorrectServiceError("AI model call failed", status_code=502),
|
||||
})
|
||||
assert len(result.suggestions) == 1
|
||||
assert result.suggestions[0].total_models == 1 # only one model answered
|
||||
assert any("model-b failed" in w for w in result.warnings)
|
||||
assert result.model == "model-a"
|
||||
|
||||
|
||||
def test_malformed_model_output_warns_instead_of_aborting_compare() -> None:
|
||||
result = _run_compare({
|
||||
"model-a": {"suggestions": [_sugg(3, 3, "chlorine")]},
|
||||
"model-b": {"not_suggestions": []}, # malformed -> _validate raises
|
||||
})
|
||||
assert len(result.suggestions) == 1
|
||||
assert any("model-b failed" in w for w in result.warnings)
|
||||
assert result.model == "model-a"
|
||||
|
||||
|
||||
def test_all_models_failing_raises_502() -> None:
|
||||
with pytest.raises(AutoCorrectServiceError) as exc_info:
|
||||
_run_compare({
|
||||
"model-a": AutoCorrectServiceError("boom", status_code=502),
|
||||
"model-b": AutoCorrectServiceError("boom", status_code=502),
|
||||
})
|
||||
assert exc_info.value.status_code == 502
|
||||
|
||||
|
||||
def test_compare_falls_back_to_single_when_unconfigured() -> None:
|
||||
result = _run_compare(
|
||||
{"gemini-3.1-pro-preview": {"suggestions": [_sugg(3, 3, "chlorine")]}},
|
||||
compare_models_env="",
|
||||
)
|
||||
s = result.suggestions[0]
|
||||
assert s.total_models == 1
|
||||
assert s.consensus == 1
|
||||
|
||||
|
||||
def test_single_model_mode_unchanged() -> None:
|
||||
result = _run_compare(
|
||||
{"gemini-3.1-pro-preview": {"suggestions": [_sugg(3, 3, "chlorine")]}},
|
||||
settings=AutoCorrectSettings(), # compare off
|
||||
)
|
||||
assert len(result.suggestions) == 1
|
||||
assert result.suggestions[0].models == ["gemini-3.1-pro-preview"]
|
||||
|
||||
|
||||
def test_three_way_conflict_chain_unifies_groups() -> None:
|
||||
# a: w2-w3, b: w3-w4, c: w4 — chained overlaps must land in ONE group
|
||||
result = _run_compare({
|
||||
"model-a": {"suggestions": [_sugg(2, 3, "x y")]},
|
||||
"model-b": {"suggestions": [_sugg(3, 4, "y z"), _sugg(4, 4, "z")]},
|
||||
})
|
||||
groups = {s.conflict_group for s in result.suggestions}
|
||||
assert len(groups) == 1 and None not in groups
|
||||
@@ -0,0 +1,173 @@
|
||||
"""Tests for auto-correct token pricing and usage extraction/logging."""
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from backend.services.auto_correct.pricing import (
|
||||
MODEL_PRICING,
|
||||
estimate_cost_usd,
|
||||
get_rate,
|
||||
)
|
||||
from backend.services.auto_correct.service import AutoCorrectService
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
|
||||
# ---- pricing ----
|
||||
|
||||
def test_estimate_cost_fable_known_rates() -> None:
|
||||
# 5000 in @ $10/M + 4000 out @ $50/M = 0.05 + 0.20 = 0.25
|
||||
usage = {
|
||||
"input_tokens": 5000,
|
||||
"output_tokens": 4000,
|
||||
"cache_read_tokens": 0,
|
||||
"thinking_tokens": None,
|
||||
}
|
||||
cost = estimate_cost_usd("claude-fable-5", usage)
|
||||
assert cost == round(0.05 + 0.20, 10)
|
||||
|
||||
|
||||
def test_estimate_cost_includes_cache_read() -> None:
|
||||
usage = {
|
||||
"input_tokens": 1_000_000,
|
||||
"output_tokens": 0,
|
||||
"cache_read_tokens": 1_000_000,
|
||||
"thinking_tokens": None,
|
||||
}
|
||||
# 1M input @ $10 + 1M cache_read @ $1 = 11.0
|
||||
assert estimate_cost_usd("claude-fable-5", usage) == 11.0
|
||||
|
||||
|
||||
def test_estimate_cost_none_usage_returns_none() -> None:
|
||||
assert estimate_cost_usd("claude-fable-5", None) is None
|
||||
|
||||
|
||||
def test_estimate_cost_unknown_model_returns_none() -> None:
|
||||
usage = {
|
||||
"input_tokens": 1000,
|
||||
"output_tokens": 1000,
|
||||
"cache_read_tokens": 0,
|
||||
"thinking_tokens": None,
|
||||
}
|
||||
assert estimate_cost_usd("some-unknown-model-9", usage) is None
|
||||
|
||||
|
||||
def test_get_rate_prefix_match_for_dated_snapshot() -> None:
|
||||
# A dated snapshot id still resolves to its family rate card.
|
||||
assert get_rate("claude-fable-5-20260601") == MODEL_PRICING["claude-fable-5"]
|
||||
|
||||
|
||||
# ---- usage extraction ----
|
||||
|
||||
def test_anthropic_usage_extraction() -> None:
|
||||
response = SimpleNamespace(
|
||||
usage=SimpleNamespace(
|
||||
input_tokens=4321,
|
||||
output_tokens=3210,
|
||||
cache_read_input_tokens=100,
|
||||
)
|
||||
)
|
||||
usage = AutoCorrectService._anthropic_usage(response)
|
||||
assert usage == {
|
||||
"input_tokens": 4321,
|
||||
"output_tokens": 3210, # already includes thinking
|
||||
"cache_read_tokens": 100,
|
||||
"thinking_tokens": None,
|
||||
}
|
||||
|
||||
|
||||
def test_gemini_usage_folds_thoughts_into_output() -> None:
|
||||
response = SimpleNamespace(
|
||||
usage_metadata=SimpleNamespace(
|
||||
prompt_token_count=4000,
|
||||
candidates_token_count=500,
|
||||
thoughts_token_count=2500,
|
||||
cached_content_token_count=0,
|
||||
)
|
||||
)
|
||||
usage = AutoCorrectService._gemini_usage(response)
|
||||
assert usage == {
|
||||
"input_tokens": 4000,
|
||||
"output_tokens": 3000, # 500 visible + 2500 thinking
|
||||
"cache_read_tokens": 0,
|
||||
"thinking_tokens": 2500,
|
||||
}
|
||||
|
||||
|
||||
def test_usage_extraction_never_raises_on_bad_shape() -> None:
|
||||
# Missing usage attribute entirely -> None, not an exception.
|
||||
assert AutoCorrectService._anthropic_usage(SimpleNamespace()) is None
|
||||
assert AutoCorrectService._gemini_usage(SimpleNamespace()) is None
|
||||
|
||||
|
||||
# ---- logging ----
|
||||
|
||||
SEGMENTS = [
|
||||
{"id": "seg-1", "words": [{"id": "w0", "text": "glory"}]},
|
||||
]
|
||||
REFS = {"genius": {"segments": [{"text": "chlorine"}]}}
|
||||
|
||||
|
||||
def _raw():
|
||||
return {
|
||||
"suggestions": [
|
||||
{
|
||||
"op": "replace",
|
||||
"start_idx": 0,
|
||||
"end_idx": 0,
|
||||
"new_text": "chlorine",
|
||||
"reason": "r",
|
||||
"category": "mishearing",
|
||||
"confidence": 0.9,
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def test_suggest_logs_per_model_and_total_cost(caplog) -> None:
|
||||
service = AutoCorrectService()
|
||||
usage = {
|
||||
"input_tokens": 5000,
|
||||
"output_tokens": 4000,
|
||||
"cache_read_tokens": 0,
|
||||
"thinking_tokens": None,
|
||||
}
|
||||
with patch.object(service, "_cache_get", return_value=None), \
|
||||
patch.object(service, "_cache_put"), \
|
||||
patch.object(service, "_call_model", return_value=(_raw(), usage)), \
|
||||
patch.object(service.settings, "auto_correct_model", "claude-fable-5"):
|
||||
with caplog.at_level("INFO"):
|
||||
service.suggest(
|
||||
job_id="job-1",
|
||||
segments=SEGMENTS,
|
||||
reference_lyrics=REFS,
|
||||
artist="A",
|
||||
title="T",
|
||||
settings=AutoCorrectSettings(),
|
||||
)
|
||||
text = caplog.text
|
||||
assert "auto-correct usage job=job-1 model=claude-fable-5" in text
|
||||
assert "input_tokens=5000" in text
|
||||
assert "output_tokens=4000" in text
|
||||
assert "est_cost_usd=0.2500" in text
|
||||
assert "auto-correct cost job=job-1" in text
|
||||
assert "total_est_cost_usd=0.2500" in text
|
||||
|
||||
|
||||
def test_suggest_logs_unavailable_usage_without_crashing(caplog) -> None:
|
||||
service = AutoCorrectService()
|
||||
with patch.object(service, "_cache_get", return_value=None), \
|
||||
patch.object(service, "_cache_put"), \
|
||||
patch.object(service, "_call_model", return_value=(_raw(), None)), \
|
||||
patch.object(service.settings, "auto_correct_model", "claude-fable-5"):
|
||||
with caplog.at_level("INFO"):
|
||||
service.suggest(
|
||||
job_id="job-2",
|
||||
segments=SEGMENTS,
|
||||
reference_lyrics=REFS,
|
||||
artist="A",
|
||||
title="T",
|
||||
settings=AutoCorrectSettings(),
|
||||
)
|
||||
assert "auto-correct usage job=job-2 model=claude-fable-5 tokens=unavailable" in caplog.text
|
||||
assert "total_est_cost_usd=unknown" in caplog.text
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Tests for auto-correct prompt construction."""
|
||||
from __future__ import annotations
|
||||
|
||||
from backend.services.auto_correct.prompts import (
|
||||
build_system_prompt,
|
||||
build_user_prompt,
|
||||
)
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
|
||||
def test_system_prompt_default_allows_adlib_suggestions() -> None:
|
||||
p = build_system_prompt(AutoCorrectSettings())
|
||||
assert "adlib_removal" in p
|
||||
assert "NEVER suggest deleting backing vocals" not in p
|
||||
assert "insert_after" in p
|
||||
|
||||
|
||||
def test_system_prompt_adlib_disabled() -> None:
|
||||
p = build_system_prompt(AutoCorrectSettings(suggest_adlib_removal=False))
|
||||
assert "NEVER suggest deleting backing vocals" in p
|
||||
|
||||
|
||||
def test_system_prompt_insertions_disabled() -> None:
|
||||
p = build_system_prompt(AutoCorrectSettings(allow_insertions=False))
|
||||
assert 'NEVER use the "insert_after" operation' in p
|
||||
|
||||
|
||||
def test_user_prompt_word_indices_are_global_and_sequential() -> None:
|
||||
segments = [
|
||||
{"id": "s1", "words": [{"id": "a", "text": "Hello"}, {"id": "b", "text": "there"}]},
|
||||
{"id": "s2", "words": [{"id": "c", "text": "world"}]},
|
||||
]
|
||||
refs = {
|
||||
"genius": {"segments": [{"text": "Hello there"}, {"text": "world"}]},
|
||||
"lrclib": {"segments": [{"text": "Hello their world"}]},
|
||||
}
|
||||
p = build_user_prompt(
|
||||
segments=segments, reference_lyrics=refs, artist="Artist", title="Title"
|
||||
)
|
||||
assert "ARTIST: Artist" in p
|
||||
assert "[L000] 0:Hello 1:there" in p
|
||||
assert "[L001] 2:world" in p
|
||||
assert "REFERENCE LYRICS (genius):" in p
|
||||
assert "REFERENCE LYRICS (lrclib):" in p
|
||||
assert "Hello their world" in p
|
||||
|
||||
|
||||
def test_user_prompt_handles_missing_metadata() -> None:
|
||||
p = build_user_prompt(
|
||||
segments=[{"id": "s1", "words": []}],
|
||||
reference_lyrics={},
|
||||
artist=None,
|
||||
title=None,
|
||||
)
|
||||
assert "ARTIST: unknown" in p
|
||||
assert "TITLE: unknown" in p
|
||||
@@ -0,0 +1,281 @@
|
||||
"""Tests for AutoCorrectService validation and suggestion mapping."""
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services.auto_correct.service import (
|
||||
AutoCorrectService,
|
||||
AutoCorrectServiceError,
|
||||
)
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
|
||||
SEGMENTS = [
|
||||
{
|
||||
"id": "seg-1",
|
||||
"words": [
|
||||
{"id": "w0", "text": "Sippin'"},
|
||||
{"id": "w1", "text": "on"},
|
||||
{"id": "w2", "text": "straight"},
|
||||
{"id": "w3", "text": "glory"},
|
||||
],
|
||||
},
|
||||
{
|
||||
"id": "seg-2",
|
||||
"words": [
|
||||
{"id": "w4", "text": "yeah"},
|
||||
{"id": "w5", "text": "yeah"},
|
||||
],
|
||||
},
|
||||
]
|
||||
REFS = {"genius": {"segments": [{"text": "Sippin' on straight chlorine"}]}}
|
||||
|
||||
|
||||
def _suggest(raw_response, settings=None):
|
||||
service = AutoCorrectService()
|
||||
with patch.object(service, "_call_model", return_value=(raw_response, None)), \
|
||||
patch.object(service, "_cache_get", return_value=None), \
|
||||
patch.object(service, "_cache_put"):
|
||||
return service.suggest(
|
||||
job_id="job-1",
|
||||
segments=SEGMENTS,
|
||||
reference_lyrics=REFS,
|
||||
artist="A",
|
||||
title="T",
|
||||
settings=settings or AutoCorrectSettings(),
|
||||
)
|
||||
|
||||
|
||||
def _raw(op="replace", start=3, end=3, text="chlorine", category="mishearing",
|
||||
confidence=0.95):
|
||||
return {
|
||||
"suggestions": [
|
||||
{
|
||||
"op": op,
|
||||
"start_idx": start,
|
||||
"end_idx": end,
|
||||
"new_text": text,
|
||||
"reason": "matches reference",
|
||||
"category": category,
|
||||
"confidence": confidence,
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def test_replace_maps_indices_to_word_ids() -> None:
|
||||
result = _suggest(_raw())
|
||||
assert len(result.suggestions) == 1
|
||||
s = result.suggestions[0]
|
||||
assert s.op == "replace"
|
||||
assert s.word_ids == ["w3"]
|
||||
assert s.segment_ids == ["seg-1"]
|
||||
assert s.original_text == "glory"
|
||||
assert s.new_text == "chlorine"
|
||||
assert result.warnings == []
|
||||
|
||||
|
||||
def test_multi_word_span_crossing_segments() -> None:
|
||||
result = _suggest(_raw(start=3, end=4, text="chlorine yeah"))
|
||||
s = result.suggestions[0]
|
||||
assert s.word_ids == ["w3", "w4"]
|
||||
assert sorted(s.segment_ids) == ["seg-1", "seg-2"]
|
||||
assert s.original_text == "glory yeah"
|
||||
|
||||
|
||||
def test_delete_suggestion() -> None:
|
||||
result = _suggest(_raw(op="delete", start=4, end=5, text=""))
|
||||
s = result.suggestions[0]
|
||||
assert s.op == "delete"
|
||||
assert s.new_text == ""
|
||||
assert s.word_ids == ["w4", "w5"]
|
||||
|
||||
|
||||
def test_insert_after_uses_anchor_word() -> None:
|
||||
result = _suggest(_raw(op="insert_after", start=2, end=2, text="up"))
|
||||
s = result.suggestions[0]
|
||||
assert s.op == "insert_after"
|
||||
assert s.word_ids == ["w2"]
|
||||
|
||||
|
||||
def test_out_of_range_indices_dropped_with_warning() -> None:
|
||||
result = _suggest(_raw(start=99, end=99))
|
||||
assert result.suggestions == []
|
||||
assert len(result.warnings) == 1
|
||||
assert "out of range" in result.warnings[0]
|
||||
|
||||
|
||||
def test_replace_with_empty_text_dropped() -> None:
|
||||
result = _suggest(_raw(text=" "))
|
||||
assert result.suggestions == []
|
||||
assert "empty new_text" in result.warnings[0]
|
||||
|
||||
|
||||
def test_below_min_confidence_dropped() -> None:
|
||||
result = _suggest(
|
||||
_raw(confidence=0.4), settings=AutoCorrectSettings(min_confidence=0.6)
|
||||
)
|
||||
assert result.suggestions == []
|
||||
assert "below threshold" in result.warnings[0]
|
||||
|
||||
|
||||
def test_adlib_removal_dropped_when_disabled() -> None:
|
||||
result = _suggest(
|
||||
_raw(op="delete", start=4, end=5, text="", category="adlib_removal"),
|
||||
settings=AutoCorrectSettings(suggest_adlib_removal=False),
|
||||
)
|
||||
assert result.suggestions == []
|
||||
assert "adlib removal disabled" in result.warnings[0]
|
||||
|
||||
|
||||
def test_insertions_dropped_when_disabled() -> None:
|
||||
result = _suggest(
|
||||
_raw(op="insert_after", start=2, end=2, text="up"),
|
||||
settings=AutoCorrectSettings(allow_insertions=False),
|
||||
)
|
||||
assert result.suggestions == []
|
||||
assert "insertions disabled" in result.warnings[0]
|
||||
|
||||
|
||||
def test_unknown_category_coerced_to_other() -> None:
|
||||
result = _suggest(_raw(category="weird"))
|
||||
assert result.suggestions[0].category == "other"
|
||||
|
||||
|
||||
def test_confidence_clamped() -> None:
|
||||
result = _suggest(_raw(confidence=1.7))
|
||||
assert result.suggestions[0].confidence == 1.0
|
||||
|
||||
|
||||
def test_no_reference_lyrics_raises_422() -> None:
|
||||
service = AutoCorrectService()
|
||||
with pytest.raises(AutoCorrectServiceError) as exc_info:
|
||||
service.suggest(
|
||||
job_id="job-1",
|
||||
segments=SEGMENTS,
|
||||
reference_lyrics={},
|
||||
artist=None,
|
||||
title=None,
|
||||
settings=AutoCorrectSettings(),
|
||||
)
|
||||
assert exc_info.value.status_code == 422
|
||||
|
||||
|
||||
def test_empty_segments_raises_400() -> None:
|
||||
service = AutoCorrectService()
|
||||
with pytest.raises(AutoCorrectServiceError) as exc_info:
|
||||
service.suggest(
|
||||
job_id="job-1",
|
||||
segments=[],
|
||||
reference_lyrics=REFS,
|
||||
artist=None,
|
||||
title=None,
|
||||
settings=AutoCorrectSettings(),
|
||||
)
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
|
||||
def test_missing_segment_ids_raises() -> None:
|
||||
service = AutoCorrectService()
|
||||
with pytest.raises(AutoCorrectServiceError, match="segments must have ids"):
|
||||
service.suggest(
|
||||
job_id="job-1",
|
||||
segments=[{"words": [{"id": "w0", "text": "hi"}]}],
|
||||
reference_lyrics=REFS,
|
||||
artist=None,
|
||||
title=None,
|
||||
settings=AutoCorrectSettings(),
|
||||
)
|
||||
|
||||
|
||||
def test_missing_word_ids_raises() -> None:
|
||||
service = AutoCorrectService()
|
||||
with pytest.raises(AutoCorrectServiceError, match="ids"):
|
||||
service.suggest(
|
||||
job_id="job-1",
|
||||
segments=[{"id": "s", "words": [{"text": "no-id"}]}],
|
||||
reference_lyrics=REFS,
|
||||
artist=None,
|
||||
title=None,
|
||||
settings=AutoCorrectSettings(),
|
||||
)
|
||||
|
||||
|
||||
def test_malformed_model_response_raises_502() -> None:
|
||||
with pytest.raises(AutoCorrectServiceError) as exc_info:
|
||||
_suggest({"not_suggestions": []})
|
||||
assert exc_info.value.status_code == 502
|
||||
|
||||
|
||||
def test_non_dict_suggestion_entries_dropped() -> None:
|
||||
result = _suggest({"suggestions": ["bogus", 42]})
|
||||
assert result.suggestions == []
|
||||
assert len(result.warnings) == 2
|
||||
|
||||
|
||||
def test_call_model_dispatches_claude_to_anthropic() -> None:
|
||||
service = AutoCorrectService()
|
||||
with patch.object(service, "_call_anthropic", return_value=({"suggestions": []}, None)) as anth, \
|
||||
patch.object(service, "_call_gemini", return_value=({"suggestions": []}, None)) as gem:
|
||||
service._call_model("claude-fable-5", "s", "u", job_id="j")
|
||||
anth.assert_called_once()
|
||||
gem.assert_not_called()
|
||||
service._call_model("gemini-3.1-pro-preview", "s", "u", job_id="j")
|
||||
gem.assert_called_once()
|
||||
|
||||
|
||||
def test_anthropic_schema_strips_genai_pollution(monkeypatch) -> None:
|
||||
"""google-genai mutates schema dicts in place (adds property_ordering);
|
||||
the anthropic path must send a clean strict schema regardless."""
|
||||
from unittest.mock import MagicMock
|
||||
import backend.services.auto_correct.service as svc_mod
|
||||
|
||||
import copy
|
||||
|
||||
monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")
|
||||
# Deep copy so this test never mutates the real module-level schema.
|
||||
polluted = copy.deepcopy(svc_mod.RESPONSE_SCHEMA)
|
||||
polluted["property_ordering"] = ["suggestions"]
|
||||
polluted["properties"]["suggestions"]["items"]["property_ordering"] = ["op"]
|
||||
monkeypatch.setattr(svc_mod, "RESPONSE_SCHEMA", polluted)
|
||||
|
||||
captured = {}
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, **kwargs):
|
||||
self.messages = MagicMock()
|
||||
|
||||
def create(**ckwargs):
|
||||
captured.update(ckwargs)
|
||||
block = MagicMock()
|
||||
block.type = "text"
|
||||
block.text = '{"suggestions": []}'
|
||||
resp = MagicMock()
|
||||
resp.content = [block]
|
||||
return resp
|
||||
|
||||
self.messages.create = create
|
||||
|
||||
import anthropic as anthropic_sdk
|
||||
|
||||
monkeypatch.setattr(anthropic_sdk, "Anthropic", FakeClient)
|
||||
service = AutoCorrectService()
|
||||
raw, _usage = service._call_anthropic("claude-fable-5", "s", "u", job_id="j")
|
||||
assert raw == {"suggestions": []}
|
||||
schema = captured["output_config"]["format"]["schema"]
|
||||
assert "property_ordering" not in schema
|
||||
assert "property_ordering" not in schema["properties"]["suggestions"]["items"]
|
||||
assert schema["additionalProperties"] is False
|
||||
# and the polluted module constant was not further mutated
|
||||
assert "property_ordering" in polluted
|
||||
|
||||
|
||||
def test_anthropic_without_api_key_raises_502(monkeypatch) -> None:
|
||||
monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)
|
||||
service = AutoCorrectService()
|
||||
with pytest.raises(AutoCorrectServiceError) as exc_info:
|
||||
service._call_anthropic("claude-fable-5", "s", "u", job_id="j")
|
||||
assert exc_info.value.status_code == 502
|
||||
assert "not configured" in str(exc_info.value)
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Tests for AutoCorrectSettings parsing/validation."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services.auto_correct.settings import (
|
||||
AutoCorrectSettings,
|
||||
settings_from_dict,
|
||||
)
|
||||
|
||||
|
||||
def test_default_settings() -> None:
|
||||
s = AutoCorrectSettings()
|
||||
assert s.suggest_adlib_removal is True
|
||||
assert s.allow_insertions is True
|
||||
assert s.min_confidence == 0.0
|
||||
|
||||
|
||||
def test_settings_from_dict_defaults_when_empty() -> None:
|
||||
assert settings_from_dict({}) == AutoCorrectSettings()
|
||||
|
||||
|
||||
def test_settings_from_dict_partial() -> None:
|
||||
s = settings_from_dict({"suggest_adlib_removal": False})
|
||||
assert s.suggest_adlib_removal is False
|
||||
assert s.allow_insertions is True
|
||||
|
||||
|
||||
def test_settings_from_dict_full() -> None:
|
||||
s = settings_from_dict(
|
||||
{
|
||||
"suggest_adlib_removal": False,
|
||||
"allow_insertions": False,
|
||||
"min_confidence": 0.75,
|
||||
}
|
||||
)
|
||||
assert s == AutoCorrectSettings(
|
||||
suggest_adlib_removal=False, allow_insertions=False, min_confidence=0.75
|
||||
)
|
||||
|
||||
|
||||
def test_settings_from_dict_unknown_key_raises() -> None:
|
||||
with pytest.raises(ValueError, match="unknown settings"):
|
||||
settings_from_dict({"bogus": 1})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [-0.1, 1.5, "high", None, True, False])
|
||||
def test_settings_from_dict_invalid_confidence_raises(value) -> None:
|
||||
with pytest.raises(ValueError, match="min_confidence"):
|
||||
settings_from_dict({"min_confidence": value})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", ["suggest_adlib_removal", "allow_insertions"])
|
||||
def test_settings_from_dict_non_bool_flag_raises(key) -> None:
|
||||
with pytest.raises(ValueError, match=key):
|
||||
settings_from_dict({key: "yes"})
|
||||
|
||||
|
||||
def test_to_dict_round_trip() -> None:
|
||||
s = AutoCorrectSettings(suggest_adlib_removal=False, min_confidence=0.5)
|
||||
assert settings_from_dict(s.to_dict()) == s
|
||||
Whitespace-only changes.
@@ -0,0 +1,103 @@
|
||||
"""Tests for the AI judge: prompt construction + response→verdict mapping.
|
||||
|
||||
The model call (`generate`) is injected, so these tests are offline and
|
||||
deterministic. The real `generate` wraps the Vertex genai client.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from backend.services.match_judge.ai import ai_judge_match, build_prompts
|
||||
from backend.services.match_judge.verdict import (
|
||||
KIND_AMBIGUOUS,
|
||||
KIND_CONTENT,
|
||||
KIND_NONE,
|
||||
)
|
||||
|
||||
|
||||
def _gen(response: dict):
|
||||
async def generate(model, system_prompt, user_prompt):
|
||||
return response
|
||||
return generate
|
||||
|
||||
|
||||
class TestBuildPrompts:
|
||||
def test_prompt_includes_input_candidates_and_tier(self):
|
||||
system, user = build_prompts(
|
||||
"queen",
|
||||
"bohemian rapsody",
|
||||
[{"artist_name": "Queen", "track_name": "Bohemian Rhapsody"}],
|
||||
audio_tier=3,
|
||||
)
|
||||
assert "bohemian rapsody" in user
|
||||
assert "Bohemian Rhapsody" in user # candidate shown
|
||||
# The poor-results signal must reach the model so it can favour a typo fix.
|
||||
assert "3" in user
|
||||
|
||||
|
||||
class TestResponseMapping:
|
||||
@pytest.mark.asyncio
|
||||
async def test_confident_content_correction(self):
|
||||
verdict = await ai_judge_match(
|
||||
"queen",
|
||||
"bohemian rapsody",
|
||||
[],
|
||||
3,
|
||||
generate=_gen(
|
||||
{
|
||||
"kind": "content",
|
||||
"confident": True,
|
||||
"canonical_artist": "Queen",
|
||||
"canonical_title": "Bohemian Rhapsody",
|
||||
"alternatives": [],
|
||||
"reason": "typo",
|
||||
}
|
||||
),
|
||||
)
|
||||
assert verdict.kind == KIND_CONTENT
|
||||
assert verdict.confident is True
|
||||
assert verdict.canonical_title == "Bohemian Rhapsody"
|
||||
assert verdict.engine == "ai"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ambiguous_carries_alternatives(self):
|
||||
verdict = await ai_judge_match(
|
||||
"",
|
||||
"bruises",
|
||||
[],
|
||||
3,
|
||||
generate=_gen(
|
||||
{
|
||||
"kind": "ambiguous",
|
||||
"confident": False,
|
||||
"canonical_artist": "Lewis Capaldi",
|
||||
"canonical_title": "Bruises",
|
||||
"alternatives": [{"artist": "Fox Stevenson", "title": "Bruises"}],
|
||||
"reason": "multiple artists",
|
||||
}
|
||||
),
|
||||
)
|
||||
assert verdict.kind == KIND_AMBIGUOUS
|
||||
assert verdict.alternatives == [{"artist": "Fox Stevenson", "title": "Bruises"}]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unknown_kind_is_treated_as_none(self):
|
||||
verdict = await ai_judge_match(
|
||||
"queen",
|
||||
"bohemian rhapsody",
|
||||
[],
|
||||
1,
|
||||
generate=_gen({"kind": "garbage", "confident": True}),
|
||||
)
|
||||
assert verdict.kind == KIND_NONE
|
||||
assert verdict.canonical_artist == "queen" # falls back to user input
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_missing_canonical_falls_back_to_input(self):
|
||||
verdict = await ai_judge_match(
|
||||
"queen",
|
||||
"bohemian rhapsody",
|
||||
[],
|
||||
1,
|
||||
generate=_gen({"kind": "content", "confident": True}),
|
||||
)
|
||||
assert verdict.canonical_artist == "queen"
|
||||
assert verdict.canonical_title == "bohemian rhapsody"
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Tests for the deterministic + catalog match classifier.
|
||||
|
||||
The classifier decides, WITHOUT any AI/network call, whether a typed
|
||||
artist/title cosmetically matches a catalog candidate (so we can silently
|
||||
tidy formatting) or whether the decision must be escalated to the AI judge.
|
||||
"""
|
||||
from backend.services.match_judge.classifier import (
|
||||
normalize_for_match,
|
||||
classify_catalog_match,
|
||||
)
|
||||
|
||||
|
||||
def _cand(artist: str, title: str) -> dict:
|
||||
return {"artist_name": artist, "track_name": title}
|
||||
|
||||
|
||||
class TestNormalizeForMatch:
|
||||
def test_casing_and_whitespace_collapse_to_same_key(self):
|
||||
assert normalize_for_match("Paramore") == normalize_for_match(" paramore ")
|
||||
|
||||
def test_punctuation_is_ignored(self):
|
||||
assert normalize_for_match("Big Man, Little Dignity") == normalize_for_match(
|
||||
"big man little dignity"
|
||||
)
|
||||
|
||||
def test_ampersand_and_and_are_equivalent(self):
|
||||
assert normalize_for_match("Jay-Z & Beyonce") == normalize_for_match(
|
||||
"Jay Z and Beyonce"
|
||||
)
|
||||
|
||||
|
||||
class TestClassifyCatalogMatch:
|
||||
def test_casing_only_difference_is_cosmetic(self):
|
||||
verdict = classify_catalog_match(
|
||||
"paramore",
|
||||
"big man, little dignity",
|
||||
[_cand("Paramore", "Big Man, Little Dignity")],
|
||||
)
|
||||
assert verdict is not None
|
||||
assert verdict.kind == "cosmetic"
|
||||
assert verdict.confident is True
|
||||
assert verdict.canonical_artist == "Paramore"
|
||||
assert verdict.canonical_title == "Big Man, Little Dignity"
|
||||
assert verdict.engine == "catalog"
|
||||
|
||||
def test_exact_match_needs_no_change(self):
|
||||
verdict = classify_catalog_match(
|
||||
"Paramore",
|
||||
"Big Man, Little Dignity",
|
||||
[_cand("Paramore", "Big Man, Little Dignity")],
|
||||
)
|
||||
assert verdict is not None
|
||||
assert verdict.kind == "none"
|
||||
assert verdict.confident is True
|
||||
|
||||
def test_no_catalog_match_escalates_to_ai(self):
|
||||
# Returns None => the service should call the AI judge.
|
||||
verdict = classify_catalog_match(
|
||||
"queen",
|
||||
"bohemian rhapsody",
|
||||
[_cand("Paramore", "Big Man, Little Dignity")],
|
||||
)
|
||||
assert verdict is None
|
||||
|
||||
def test_empty_candidates_escalates_to_ai(self):
|
||||
assert classify_catalog_match("queen", "bohemian rhapsody", []) is None
|
||||
@@ -0,0 +1,272 @@
|
||||
"""Orchestration tests for the match-judge service.
|
||||
|
||||
The service composes the deterministic+catalog classifier with the AI judge:
|
||||
the AI judge is invoked ONLY when the classifier can't confidently decide.
|
||||
Catalog search and the AI judge are injected so these tests touch no network.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from backend.services.match_judge.service import judge_match
|
||||
from backend.services.match_judge.verdict import (
|
||||
KIND_AMBIGUOUS,
|
||||
KIND_COSMETIC,
|
||||
KIND_CONTENT,
|
||||
KIND_NONE,
|
||||
MatchVerdict,
|
||||
)
|
||||
|
||||
|
||||
def _candidates(*pairs):
|
||||
async def _search(query, artist, limit):
|
||||
return [{"artist_name": a, "track_name": t} for a, t in pairs]
|
||||
return _search
|
||||
|
||||
|
||||
def _ai_never(*_a, **_k):
|
||||
raise AssertionError("AI judge must not be called")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_catalog_cosmetic_match_skips_ai():
|
||||
calls = {"ai": 0}
|
||||
|
||||
async def ai(*_a, **_k):
|
||||
calls["ai"] += 1
|
||||
raise AssertionError("should not run")
|
||||
|
||||
verdict = await judge_match(
|
||||
"paramore",
|
||||
"big man, little dignity",
|
||||
search_tracks=_candidates(("Paramore", "Big Man, Little Dignity")),
|
||||
ai_judge=ai,
|
||||
enabled=True,
|
||||
)
|
||||
assert verdict.kind == KIND_COSMETIC
|
||||
assert verdict.engine == "catalog"
|
||||
assert calls["ai"] == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_catalog_match_calls_ai():
|
||||
seen = {}
|
||||
|
||||
async def ai(artist, title, candidates, audio_tier):
|
||||
seen["candidates"] = candidates
|
||||
seen["tier"] = audio_tier
|
||||
return MatchVerdict(
|
||||
kind=KIND_CONTENT,
|
||||
confident=True,
|
||||
canonical_artist="Queen",
|
||||
canonical_title="Bohemian Rhapsody",
|
||||
engine="ai",
|
||||
reason="typo fix",
|
||||
)
|
||||
|
||||
verdict = await judge_match(
|
||||
"queen",
|
||||
"bohemian rapsody",
|
||||
audio_tier=3,
|
||||
search_tracks=_candidates(("Queen", "Radio Ga Ga")),
|
||||
ai_judge=ai,
|
||||
enabled=True,
|
||||
)
|
||||
assert verdict.kind == KIND_CONTENT
|
||||
assert verdict.engine == "ai"
|
||||
assert seen["tier"] == 3
|
||||
assert seen["candidates"] == [{"artist_name": "Queen", "track_name": "Radio Ga Ga"}]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_disabled_flag_skips_ai_and_returns_none():
|
||||
verdict = await judge_match(
|
||||
"queen",
|
||||
"bohemian rapsody",
|
||||
search_tracks=_candidates(("Queen", "Radio Ga Ga")),
|
||||
ai_judge=_ai_never,
|
||||
enabled=False,
|
||||
)
|
||||
assert verdict.kind == KIND_NONE
|
||||
assert verdict.confident is True
|
||||
assert verdict.canonical_artist == "queen" # leaves user input untouched
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ai_failure_falls_back_to_none():
|
||||
async def ai(*_a, **_k):
|
||||
raise RuntimeError("model exploded")
|
||||
|
||||
verdict = await judge_match(
|
||||
"queen",
|
||||
"bohemian rapsody",
|
||||
search_tracks=_candidates(("Queen", "Radio Ga Ga")),
|
||||
ai_judge=ai,
|
||||
enabled=True,
|
||||
)
|
||||
assert verdict.kind == KIND_NONE
|
||||
assert verdict.canonical_title == "bohemian rapsody"
|
||||
|
||||
|
||||
# --- Fast stage (catalog-only parallel pass) ---
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fast_stage_returns_catalog_verdict_without_ai():
|
||||
verdict = await judge_match(
|
||||
"paramore",
|
||||
"big man, little dignity",
|
||||
stage="fast",
|
||||
search_tracks=_candidates(("Paramore", "Big Man, Little Dignity")),
|
||||
ai_judge=_ai_never,
|
||||
enabled=True,
|
||||
)
|
||||
assert verdict.kind == KIND_COSMETIC
|
||||
assert verdict.engine == "catalog"
|
||||
assert verdict.needs_ai is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fast_stage_undecided_signals_needs_ai_without_calling_ai():
|
||||
verdict = await judge_match(
|
||||
"queen",
|
||||
"bohemian rapsody",
|
||||
stage="fast",
|
||||
search_tracks=_candidates(("Queen", "Radio Ga Ga")),
|
||||
ai_judge=_ai_never,
|
||||
enabled=True,
|
||||
)
|
||||
assert verdict.kind == KIND_NONE
|
||||
assert verdict.needs_ai is True
|
||||
assert verdict.confident is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fast_stage_never_calls_ai_even_when_undecided():
|
||||
# _ai_never raises if called; reaching here proves the fast pass skipped AI.
|
||||
verdict = await judge_match(
|
||||
"queen", "bohemian rapsody", stage="fast",
|
||||
search_tracks=_candidates(), ai_judge=_ai_never, enabled=True,
|
||||
)
|
||||
assert verdict.needs_ai is True
|
||||
|
||||
|
||||
# --- Item 4: verify a confident catalog match with AI when the audio tier is weak ---
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_weak_tier_catalog_match_is_verified_and_overridden_by_ai():
|
||||
async def ai(artist, title, candidates, audio_tier):
|
||||
return MatchVerdict(
|
||||
KIND_CONTENT, True, "Queen", "Bohemian Rhapsody",
|
||||
engine="ai", reason="typo",
|
||||
)
|
||||
|
||||
# Catalog "matched" the user's exact typo (junk entry) → would normally be
|
||||
# 'none'/already-canonical. Weak tier (3) makes us verify with AI, which overrides.
|
||||
verdict = await judge_match(
|
||||
"Queen", "Bohemian Rapsody",
|
||||
audio_tier=3,
|
||||
search_tracks=_candidates(("Queen", "Bohemian Rapsody")),
|
||||
ai_judge=ai,
|
||||
enabled=True,
|
||||
)
|
||||
assert verdict.kind == KIND_CONTENT
|
||||
assert verdict.canonical_title == "Bohemian Rhapsody"
|
||||
assert verdict.engine == "ai"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_strong_tier_catalog_match_still_skips_ai():
|
||||
verdict = await judge_match(
|
||||
"Queen", "Bohemian Rapsody",
|
||||
audio_tier=1,
|
||||
search_tracks=_candidates(("Queen", "Bohemian Rapsody")),
|
||||
ai_judge=_ai_never,
|
||||
enabled=True,
|
||||
)
|
||||
# Strong audio results → trust the catalog match, no AI.
|
||||
assert verdict.engine == "catalog"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_weak_tier_keeps_catalog_verdict_when_ai_unconfident():
|
||||
async def ai(artist, title, candidates, audio_tier):
|
||||
return MatchVerdict(KIND_NONE, False, artist, title, engine="ai")
|
||||
|
||||
verdict = await judge_match(
|
||||
"paramore", "big man, little dignity",
|
||||
audio_tier=3,
|
||||
search_tracks=_candidates(("Paramore", "Big Man, Little Dignity")),
|
||||
ai_judge=ai,
|
||||
enabled=True,
|
||||
)
|
||||
# AI wasn't confident about a change → keep the cosmetic catalog tidy.
|
||||
assert verdict.kind == KIND_COSMETIC
|
||||
assert verdict.engine == "catalog"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_weak_tier_keeps_catalog_verdict_when_ai_fails():
|
||||
async def ai(*_a, **_k):
|
||||
raise RuntimeError("model exploded")
|
||||
|
||||
verdict = await judge_match(
|
||||
"paramore", "big man, little dignity",
|
||||
audio_tier=3,
|
||||
search_tracks=_candidates(("Paramore", "Big Man, Little Dignity")),
|
||||
ai_judge=ai,
|
||||
enabled=True,
|
||||
)
|
||||
assert verdict.kind == KIND_COSMETIC
|
||||
assert verdict.engine == "catalog"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_weak_tier_does_not_verify_when_ai_disabled():
|
||||
verdict = await judge_match(
|
||||
"paramore", "big man, little dignity",
|
||||
audio_tier=3,
|
||||
search_tracks=_candidates(("Paramore", "Big Man, Little Dignity")),
|
||||
ai_judge=_ai_never,
|
||||
enabled=False,
|
||||
)
|
||||
assert verdict.kind == KIND_COSMETIC
|
||||
assert verdict.engine == "catalog"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_weak_tier_ai_can_escalate_to_ambiguous():
|
||||
async def ai(artist, title, candidates, audio_tier):
|
||||
return MatchVerdict(
|
||||
KIND_AMBIGUOUS, True, "Lewis Capaldi", "Bruises",
|
||||
alternatives=[{"artist": "Fox Stevenson", "title": "Bruises"}],
|
||||
engine="ai",
|
||||
)
|
||||
|
||||
verdict = await judge_match(
|
||||
"capaldi", "bruises",
|
||||
audio_tier=3,
|
||||
search_tracks=_candidates(("Lewis Capaldi", "Bruises")),
|
||||
ai_judge=ai,
|
||||
enabled=True,
|
||||
)
|
||||
assert verdict.kind == KIND_AMBIGUOUS
|
||||
assert verdict.alternatives == [{"artist": "Fox Stevenson", "title": "Bruises"}]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_catalog_search_failure_still_lets_ai_run():
|
||||
async def failing_search(query, artist, limit):
|
||||
raise RuntimeError("catalog down")
|
||||
|
||||
async def ai(artist, title, candidates, audio_tier):
|
||||
assert candidates == [] # gracefully degraded to no candidates
|
||||
return MatchVerdict(KIND_NONE, True, artist, title, engine="ai")
|
||||
|
||||
verdict = await judge_match(
|
||||
"queen",
|
||||
"bohemian rhapsody",
|
||||
search_tracks=failing_search,
|
||||
ai_judge=ai,
|
||||
enabled=True,
|
||||
)
|
||||
assert verdict.engine == "ai"
|
||||
@@ -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={})
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
"""
|
||||
Regression tests for AudioShake leading-padding handling.
|
||||
|
||||
Some user-provided audio (e.g. the Vocal Star bulk-batch MP3s) begins with a block of
|
||||
null bytes before the first ID3/MPEG frame. ffmpeg tolerates it, but AudioShake rejects
|
||||
the asset with "Error fetching or processing asset" (400 on /tasks). The AudioUploadOptimizer
|
||||
must detect this and losslessly remux before upload — while leaving clean files and
|
||||
container formats (.mp4/.mov, which legitimately start with null box-size bytes) untouched.
|
||||
"""
|
||||
import os
|
||||
import tempfile
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from karaoke_gen.lyrics_transcriber.transcribers.audioshake import AudioUploadOptimizer
|
||||
|
||||
|
||||
def _write(tmp_path, name, head: bytes):
|
||||
p = os.path.join(tmp_path, name)
|
||||
with open(p, "wb") as f:
|
||||
f.write(head + b"\x00" * 2048)
|
||||
return p
|
||||
|
||||
|
||||
def test_has_leading_padding_detects_null_start(tmp_path):
|
||||
opt = AudioUploadOptimizer(MagicMock())
|
||||
padded = _write(str(tmp_path), "padded.mp3", b"\x00\x00\x00\x00")
|
||||
assert opt._has_leading_padding(padded) is True
|
||||
|
||||
|
||||
def test_has_leading_padding_false_for_id3(tmp_path):
|
||||
opt = AudioUploadOptimizer(MagicMock())
|
||||
clean = _write(str(tmp_path), "clean.mp3", b"ID3\x04")
|
||||
assert opt._has_leading_padding(clean) is False
|
||||
|
||||
|
||||
def test_has_leading_padding_false_for_frame_sync(tmp_path):
|
||||
opt = AudioUploadOptimizer(MagicMock())
|
||||
clean = _write(str(tmp_path), "sync.mp3", b"\xff\xfb\xc0\x04")
|
||||
assert opt._has_leading_padding(clean) is False
|
||||
|
||||
|
||||
def test_padded_mp3_is_remuxed(tmp_path):
|
||||
opt = AudioUploadOptimizer(MagicMock())
|
||||
padded = _write(str(tmp_path), "padded.mp3", b"\x00\x00\x00\x00")
|
||||
with patch.object(opt, "_remux_clean", return_value=("/tmp/clean.mp3", "/tmp/clean.mp3")) as remux:
|
||||
result = opt.prepare_for_upload(padded)
|
||||
remux.assert_called_once()
|
||||
assert result == ("/tmp/clean.mp3", "/tmp/clean.mp3")
|
||||
|
||||
|
||||
def test_clean_mp3_uploaded_directly(tmp_path):
|
||||
opt = AudioUploadOptimizer(MagicMock())
|
||||
clean = _write(str(tmp_path), "clean.mp3", b"ID3\x04")
|
||||
with patch.object(opt, "_remux_clean") as remux:
|
||||
result = opt.prepare_for_upload(clean)
|
||||
remux.assert_not_called()
|
||||
assert result == (clean, None)
|
||||
|
||||
|
||||
def test_container_format_not_remuxed_despite_null_start(tmp_path):
|
||||
""".mp4/.mov begin with a null box-size prefix — must NOT be treated as padding."""
|
||||
opt = AudioUploadOptimizer(MagicMock())
|
||||
mp4 = _write(str(tmp_path), "video.mp4", b"\x00\x00\x00\x20ftyp")
|
||||
with patch.object(opt, "_remux_clean") as remux:
|
||||
result = opt.prepare_for_upload(mp4)
|
||||
remux.assert_not_called()
|
||||
assert result == (mp4, None)
|
||||
@@ -601,7 +601,7 @@ class TestWaitForCompletionPollTolerance:
|
||||
"""Tolerates up to MAX_CONSECUTIVE_POLL_FAILURES-1 consecutive failures."""
|
||||
call_count = 0
|
||||
|
||||
async def mock_get_status(job_id):
|
||||
async def mock_get_status(job_id, worker_url=None):
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
if call_count <= 2:
|
||||
@@ -623,7 +623,7 @@ class TestWaitForCompletionPollTolerance:
|
||||
@pytest.mark.asyncio
|
||||
async def test_fails_after_max_consecutive_poll_failures(self, encoding_service):
|
||||
"""Fails after MAX_CONSECUTIVE_POLL_FAILURES consecutive failures."""
|
||||
async def always_fail(job_id):
|
||||
async def always_fail(job_id, worker_url=None):
|
||||
raise aiohttp.ClientConnectorError(
|
||||
connection_key=MagicMock(), os_error=OSError("Connection refused")
|
||||
)
|
||||
@@ -640,7 +640,7 @@ class TestWaitForCompletionPollTolerance:
|
||||
"""A successful poll resets the consecutive failure counter."""
|
||||
call_count = 0
|
||||
|
||||
async def intermittent_failures(job_id):
|
||||
async def intermittent_failures(job_id, worker_url=None):
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
# Fail for 2, succeed (running), fail for 2 more, succeed (complete)
|
||||
@@ -752,3 +752,128 @@ class TestFormatException:
|
||||
e = aiohttp.ClientConnectorError(MagicMock(), OSError())
|
||||
# Type name should always appear
|
||||
assert "ClientConnectorError" in _format_exception(e)
|
||||
|
||||
|
||||
class TestWorkerUrlPinning:
|
||||
"""Status polls must stay pinned to the worker that ACCEPTED the job.
|
||||
|
||||
Regression for incident 2026-06-16 (job d3af33ae): a blue-green deploy
|
||||
swapped the primary pointer mid-render, and because status polls re-resolved
|
||||
`active_url` on every call, they migrated from the worker actually encoding
|
||||
the job (old primary) to the freshly-swapped new primary — which 404'd
|
||||
"Encoding job ... not found" and failed the render after 5 polls, even though
|
||||
the original worker finished the encode fine.
|
||||
"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_job_status_targets_pinned_url(self, encoding_service):
|
||||
"""A pinned poll hits the given worker_url, not active_url, and disables
|
||||
failover (a pinned poll must never re-resolve or spin up a fallback VM —
|
||||
a fresh VM cannot have the in-flight job)."""
|
||||
# active_url would resolve to worker-b, but the job lives on worker-a.
|
||||
captured = {}
|
||||
|
||||
async def fake_request(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return {"status": 200, "json": {"status": "running", "progress": 40}, "text": None}
|
||||
|
||||
with patch.object(encoding_service, "_get_worker_url", return_value="http://worker-b:8080"), \
|
||||
patch.object(encoding_service, "_request_with_retry", side_effect=fake_request):
|
||||
result = await encoding_service.get_job_status("d3af33ae", worker_url="http://worker-a:8080")
|
||||
|
||||
assert result["status"] == "running"
|
||||
assert captured["url"] == "http://worker-a:8080/status/d3af33ae"
|
||||
assert captured["allow_failover"] is False
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_job_status_without_pin_uses_active_url(self, encoding_service):
|
||||
"""Regression: unpinned polls still resolve the current active_url."""
|
||||
captured = {}
|
||||
|
||||
async def fake_request(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return {"status": 200, "json": {"status": "running"}, "text": None}
|
||||
|
||||
with patch.object(encoding_service, "_get_worker_url", return_value="http://worker-b:8080"), \
|
||||
patch.object(encoding_service, "_request_with_retry", side_effect=fake_request):
|
||||
await encoding_service.get_job_status("d3af33ae")
|
||||
|
||||
assert captured["url"] == "http://worker-b:8080/status/d3af33ae"
|
||||
# Unpinned keeps the existing failover/re-resolution behaviour.
|
||||
assert captured.get("allow_failover", True) is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_wait_for_completion_threads_pinned_url_into_polls(self, encoding_service):
|
||||
"""wait_for_completion forwards its worker_url to every status poll."""
|
||||
seen_urls = []
|
||||
|
||||
async def mock_get_status(job_id, worker_url=None):
|
||||
seen_urls.append(worker_url)
|
||||
return {"status": "complete", "output_files": ["a.mp4"]}
|
||||
|
||||
with patch.object(encoding_service, "get_job_status", side_effect=mock_get_status), \
|
||||
patch("asyncio.sleep", new_callable=AsyncMock), \
|
||||
patch("asyncio.get_event_loop") as mock_loop:
|
||||
mock_loop.return_value.time.return_value = 0
|
||||
result = await encoding_service.wait_for_completion(
|
||||
"d3af33ae", worker_url="http://worker-a:8080"
|
||||
)
|
||||
|
||||
assert result["status"] == "complete"
|
||||
assert seen_urls == ["http://worker-a:8080"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_request_with_retry_no_failover_when_disabled(self, encoding_service):
|
||||
"""With allow_failover=False, a connection error must NOT trigger the
|
||||
fallback-VM warmup nor URL re-resolution — it just retries the same URL
|
||||
and surfaces the failure to the caller's own poll-tolerance loop."""
|
||||
encoding_service.set_worker_manager(MagicMock())
|
||||
warmup = AsyncMock()
|
||||
|
||||
with patch.object(encoding_service, "_warmup_encoding_worker_fallback", warmup), \
|
||||
patch("asyncio.sleep", new_callable=AsyncMock), \
|
||||
patch("aiohttp.ClientSession") as mock_session:
|
||||
mock_session.side_effect = aiohttp.ClientConnectorError(
|
||||
MagicMock(), OSError("Connection refused")
|
||||
)
|
||||
with pytest.raises(aiohttp.ClientConnectorError):
|
||||
await encoding_service._request_with_retry(
|
||||
method="GET",
|
||||
url="http://worker-a:8080/status/j1",
|
||||
headers={},
|
||||
job_id="j1",
|
||||
path=None,
|
||||
allow_failover=False,
|
||||
)
|
||||
|
||||
warmup.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_render_video_keeps_polling_submission_worker_after_swap(self, encoding_service):
|
||||
"""End-to-end: when active_url has swapped to a worker that 404s, the
|
||||
render keeps polling the worker the job was submitted to and completes.
|
||||
|
||||
This FAILS before the fix (the poll follows active_url to worker-b and
|
||||
gets "not found"), and PASSES after (the poll is pinned to worker-a)."""
|
||||
encoding_service.set_worker_manager(MagicMock())
|
||||
|
||||
async def fake_submit(job_id, render_config):
|
||||
return {"status": "accepted", "job_id": job_id}
|
||||
|
||||
async def fake_get_status(job_id, worker_url=None):
|
||||
# worker-a owns the job; the post-swap active worker (worker-b, or an
|
||||
# unpinned None) has never seen it.
|
||||
if worker_url == "http://worker-a:8080":
|
||||
return {"status": "complete", "output_files": ["4k.mp4"]}
|
||||
raise RuntimeError(f"Encoding job {job_id} not found")
|
||||
|
||||
with patch.object(encoding_service, "_get_worker_url", return_value="http://worker-a:8080"), \
|
||||
patch.object(encoding_service, "submit_render_video_job", side_effect=fake_submit), \
|
||||
patch.object(encoding_service, "get_job_status", side_effect=fake_get_status), \
|
||||
patch("asyncio.sleep", new_callable=AsyncMock), \
|
||||
patch("asyncio.get_event_loop") as mock_loop:
|
||||
mock_loop.return_value.time.return_value = 0
|
||||
result = await encoding_service.render_video_on_gce("d3af33ae", {"foo": "bar"})
|
||||
|
||||
assert result["status"] == "complete"
|
||||
assert result["output_files"] == ["4k.mp4"]
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Tests for POST /api/catalog/match-judge."""
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, patch, MagicMock
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.main import app
|
||||
from backend.services.match_judge.verdict import MatchVerdict, KIND_COSMETIC, KIND_NONE
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def auth_headers():
|
||||
return {"Authorization": "Bearer test-admin-token"}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clear_rate_limits():
|
||||
from backend.api.routes.catalog import _rate_limit_windows
|
||||
_rate_limit_windows.clear()
|
||||
yield
|
||||
_rate_limit_windows.clear()
|
||||
|
||||
|
||||
@patch("backend.api.routes.catalog.require_auth")
|
||||
@patch("backend.services.match_judge.service.judge_match", new_callable=AsyncMock)
|
||||
def test_match_judge_returns_verdict(mock_judge, mock_auth, client, auth_headers):
|
||||
mock_auth.return_value = MagicMock(user_email="t@example.com", token_id="t")
|
||||
mock_judge.return_value = MatchVerdict(
|
||||
kind=KIND_COSMETIC,
|
||||
confident=True,
|
||||
canonical_artist="Paramore",
|
||||
canonical_title="Big Man, Little Dignity",
|
||||
engine="catalog",
|
||||
reason="casing",
|
||||
)
|
||||
|
||||
resp = client.post(
|
||||
"/api/catalog/match-judge",
|
||||
json={"artist": "paramore", "title": "big man, little dignity"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["kind"] == "cosmetic"
|
||||
assert data["confident"] is True
|
||||
assert data["canonical_artist"] == "Paramore"
|
||||
assert data["canonical_title"] == "Big Man, Little Dignity"
|
||||
assert data["engine"] == "catalog"
|
||||
|
||||
|
||||
@patch("backend.api.routes.catalog.require_auth")
|
||||
@patch("backend.services.match_judge.service.judge_match", new_callable=AsyncMock)
|
||||
def test_match_judge_passes_audio_tier(mock_judge, mock_auth, client, auth_headers):
|
||||
mock_auth.return_value = MagicMock(user_email="t@example.com", token_id="t")
|
||||
mock_judge.return_value = MatchVerdict("none", True, "q", "b", engine="ai")
|
||||
|
||||
client.post(
|
||||
"/api/catalog/match-judge",
|
||||
json={"artist": "q", "title": "b", "audio_confidence_tier": 3},
|
||||
headers=auth_headers,
|
||||
)
|
||||
# judge_match(artist, title, audio_tier=...) — tier forwarded
|
||||
_, kwargs = mock_judge.call_args
|
||||
assert kwargs.get("audio_tier") == 3 or mock_judge.call_args.args[2] == 3
|
||||
|
||||
|
||||
@patch("backend.api.routes.catalog.require_auth")
|
||||
@patch("backend.services.match_judge.service.judge_match", new_callable=AsyncMock)
|
||||
def test_match_judge_defaults_to_full_stage(mock_judge, mock_auth, client, auth_headers):
|
||||
mock_auth.return_value = MagicMock(user_email="t@example.com", token_id="t")
|
||||
mock_judge.return_value = MatchVerdict("none", True, "q", "b", engine="ai")
|
||||
|
||||
client.post(
|
||||
"/api/catalog/match-judge",
|
||||
json={"artist": "q", "title": "b"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
_, kwargs = mock_judge.call_args
|
||||
assert kwargs.get("stage") == "full"
|
||||
|
||||
|
||||
@patch("backend.api.routes.catalog.require_auth")
|
||||
@patch("backend.services.match_judge.service.judge_match", new_callable=AsyncMock)
|
||||
def test_match_judge_forwards_fast_stage(mock_judge, mock_auth, client, auth_headers):
|
||||
mock_auth.return_value = MagicMock(user_email="t@example.com", token_id="t")
|
||||
mock_judge.return_value = MatchVerdict(
|
||||
KIND_NONE, False, "q", "b", engine="catalog", reason="needs ai", needs_ai=True
|
||||
)
|
||||
|
||||
resp = client.post(
|
||||
"/api/catalog/match-judge",
|
||||
json={"artist": "q", "title": "b", "stage": "fast"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["needs_ai"] is True
|
||||
_, kwargs = mock_judge.call_args
|
||||
assert kwargs.get("stage") == "fast"
|
||||
|
||||
|
||||
def test_match_judge_rejects_unknown_stage(client, auth_headers):
|
||||
resp = client.post(
|
||||
"/api/catalog/match-judge",
|
||||
json={"artist": "q", "title": "b", "stage": "turbo"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
def test_match_judge_validation_error(client, auth_headers):
|
||||
resp = client.post(
|
||||
"/api/catalog/match-judge",
|
||||
json={"artist": "", "title": "Dreams"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert resp.status_code == 422
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Tests for proactive auto-correct: the service-side worker + the lyrics-worker trigger.
|
||||
|
||||
The work runs on the API service (process_proactive_auto_correct); the lyrics
|
||||
worker only fires an HTTP trigger. Both must be best-effort: gated by a flag,
|
||||
never raise, never block, and use the multi-model default settings that line up
|
||||
with the review UI's request.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.workers.auto_correct_worker import process_proactive_auto_correct
|
||||
from backend.workers.lyrics_worker import _trigger_proactive_auto_correct
|
||||
|
||||
|
||||
CORRECTIONS = {
|
||||
"corrected_segments": [
|
||||
{"id": "seg-1", "words": [{"id": "w0", "text": "glory"}]},
|
||||
],
|
||||
"reference_lyrics": {"genius": {"segments": [{"text": "chlorine"}]}},
|
||||
}
|
||||
|
||||
|
||||
def _settings(enabled: bool):
|
||||
return SimpleNamespace(auto_correct_proactive_enabled=enabled)
|
||||
|
||||
|
||||
def _patch(enabled=True, corrections=CORRECTIONS, exists=True, service=None, job=None):
|
||||
"""Patch the dependencies process_proactive_auto_correct imports lazily."""
|
||||
storage = MagicMock()
|
||||
storage.file_exists.return_value = exists
|
||||
storage.download_json.return_value = corrections
|
||||
jm = MagicMock()
|
||||
jm.return_value.get_job.return_value = job or SimpleNamespace(artist="A", title="T")
|
||||
return (
|
||||
patch("backend.config.get_settings", return_value=_settings(enabled)),
|
||||
patch("backend.services.storage_service.StorageService", return_value=storage),
|
||||
patch("backend.services.job_manager.JobManager", jm),
|
||||
patch("backend.services.auto_correct.get_auto_correct_service",
|
||||
return_value=service or MagicMock()),
|
||||
storage,
|
||||
)
|
||||
|
||||
|
||||
# ---- service-side worker ----
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_disabled_flag_short_circuits() -> None:
|
||||
p_set, p_st, p_jm, p_svc, storage = _patch(enabled=False)
|
||||
with p_set, p_st, p_jm, p_svc:
|
||||
result = await process_proactive_auto_correct("job-1")
|
||||
assert result == {"status": "disabled"}
|
||||
storage.file_exists.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_skips_when_no_references() -> None:
|
||||
corr = {"corrected_segments": [{"id": "s", "words": []}], "reference_lyrics": {}}
|
||||
p_set, p_st, p_jm, p_svc, storage = _patch(corrections=corr)
|
||||
svc = MagicMock()
|
||||
with p_set, p_st, p_jm, patch("backend.services.auto_correct.get_auto_correct_service", return_value=svc):
|
||||
result = await process_proactive_auto_correct("job-1")
|
||||
assert result["status"] == "skipped"
|
||||
svc.suggest.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_skips_when_no_corrections_file() -> None:
|
||||
p_set, p_st, p_jm, p_svc, storage = _patch(exists=False)
|
||||
with p_set, p_st, p_jm, p_svc:
|
||||
result = await process_proactive_auto_correct("job-1")
|
||||
assert result["status"] == "skipped"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_happy_path_runs_multi_model_and_caches() -> None:
|
||||
svc = MagicMock()
|
||||
svc.suggest.return_value = SimpleNamespace(
|
||||
suggestions=[1, 2], model="claude-fable-5, gemini-3.1-pro-preview",
|
||||
elapsed_seconds=12.3,
|
||||
)
|
||||
p_set, p_st, p_jm, _p_svc, storage = _patch(service=svc)
|
||||
with p_set, p_st, p_jm, patch("backend.services.auto_correct.get_auto_correct_service", return_value=svc):
|
||||
result = await process_proactive_auto_correct("job-1")
|
||||
assert result == {"status": "generated", "suggestions": 2}
|
||||
kwargs = svc.suggest.call_args.kwargs
|
||||
assert kwargs["job_id"] == "job-1"
|
||||
assert kwargs["settings"].compare_models is True
|
||||
assert kwargs["artist"] == "A"
|
||||
assert kwargs["segments"] == CORRECTIONS["corrected_segments"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_swallows_service_errors() -> None:
|
||||
svc = MagicMock()
|
||||
svc.suggest.side_effect = RuntimeError("anthropic down / out of credits")
|
||||
p_set, p_st, p_jm, _p_svc, storage = _patch(service=svc)
|
||||
with p_set, p_st, p_jm, patch("backend.services.auto_correct.get_auto_correct_service", return_value=svc):
|
||||
result = await process_proactive_auto_correct("job-1") # must not raise
|
||||
assert result["status"] == "error"
|
||||
|
||||
|
||||
# ---- lyrics-worker trigger ----
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lyrics_worker_fires_trigger() -> None:
|
||||
ws = MagicMock()
|
||||
ws.trigger_auto_correct = AsyncMock(return_value=True)
|
||||
with patch("backend.services.worker_service.WorkerService", return_value=ws):
|
||||
await _trigger_proactive_auto_correct("job-1", MagicMock())
|
||||
ws.trigger_auto_correct.assert_awaited_once_with("job-1")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lyrics_worker_trigger_swallows_errors() -> None:
|
||||
ws = MagicMock()
|
||||
ws.trigger_auto_correct = AsyncMock(side_effect=RuntimeError("network down"))
|
||||
job_log = MagicMock()
|
||||
with patch("backend.services.worker_service.WorkerService", return_value=ws):
|
||||
await _trigger_proactive_auto_correct("job-1", job_log) # must not raise
|
||||
job_log.warning.assert_called()
|
||||
@@ -365,6 +365,44 @@ class TestCompleteReviewZeroSegmentValidation:
|
||||
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_existing_instrumental_defaults_selection_to_custom(self, _patched_client):
|
||||
"""Jobs that supplied their own instrumental (tenant/existing_instrumental flow)
|
||||
have no instrumental-selection UI step, so complete-review must default the
|
||||
selection to 'custom' — otherwise the render defaults to 'clean' (a separated
|
||||
stem that was never produced) and fails the prerequisite check."""
|
||||
client, mock_jm = _patched_client
|
||||
job = self._make_job(state_data={'lyrics_metadata': {'segment_count': 5}})
|
||||
job.existing_instrumental_gcs_path = "uploads/job-zero-seg/audio/existing_instrumental.mp3"
|
||||
mock_jm.get_job.return_value = job
|
||||
|
||||
response = client.post(
|
||||
"/api/jobs/job-zero-seg/complete-review",
|
||||
headers={"Authorization": "Bearer test-admin-token"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_jm.update_state_data.assert_any_call(
|
||||
"job-zero-seg", "instrumental_selection", "custom"
|
||||
)
|
||||
|
||||
def test_existing_instrumental_does_not_override_explicit_selection(self, _patched_client):
|
||||
"""An explicit instrumental_selection in the request still wins over the default."""
|
||||
client, mock_jm = _patched_client
|
||||
job = self._make_job(state_data={'lyrics_metadata': {'segment_count': 5}})
|
||||
job.existing_instrumental_gcs_path = "uploads/job-zero-seg/audio/existing_instrumental.mp3"
|
||||
mock_jm.get_job.return_value = job
|
||||
|
||||
response = client.post(
|
||||
"/api/jobs/job-zero-seg/complete-review",
|
||||
headers={"Authorization": "Bearer test-admin-token"},
|
||||
json={"instrumental_selection": "clean"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_jm.update_state_data.assert_any_call(
|
||||
"job-zero-seg", "instrumental_selection", "clean"
|
||||
)
|
||||
|
||||
|
||||
class TestPreviewStyleLoading:
|
||||
"""Tests for the unified style loader used in preview video generation.
|
||||
|
||||
@@ -545,6 +545,57 @@ class TestCreateJobFromSearch:
|
||||
assert job_create.artist == "Abba (Display)"
|
||||
assert job_create.title == "Waterloo (Karaoke)"
|
||||
|
||||
def test_corrected_artist_title_wins_over_session_query(self, create_from_search_client, auth_headers):
|
||||
"""Regression: when the user clicks "Use official formatting", the corrected
|
||||
artist/title sent in the request body must win over the original (raw) search
|
||||
query stored in the session. Previously the job was named with the raw query,
|
||||
so the official formatting selection was silently ignored."""
|
||||
# Session was created from the raw lowercase query the user typed...
|
||||
raw_session = _make_search_session(user_email="test@example.com")
|
||||
raw_session["artist"] = "hard-fi"
|
||||
raw_session["title"] = "hard to beat"
|
||||
create_from_search_client._mock_firestore.get_search_session.return_value = raw_session
|
||||
create_from_search_client._mock_firestore.consume_search_session.return_value = raw_session
|
||||
|
||||
# ...then the user picked the official formatting, so the frontend sends the
|
||||
# corrected artist/title (no separate display override).
|
||||
create_from_search_client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "Hard-Fi",
|
||||
"title": "Hard to Beat",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
call_args = create_from_search_client._mock_jm.create_job.call_args
|
||||
job_create = call_args[0][0]
|
||||
assert job_create.artist == "Hard-Fi"
|
||||
assert job_create.title == "Hard to Beat"
|
||||
# The original query is still preserved for audio-search matching metadata.
|
||||
assert job_create.audio_search_artist == "hard-fi"
|
||||
assert job_create.audio_search_title == "hard to beat"
|
||||
|
||||
def test_blank_body_artist_title_falls_back_to_session_query(self, create_from_search_client, auth_headers):
|
||||
"""Whitespace-only artist/title in the body must not become the job name —
|
||||
fall back to the stored search query instead."""
|
||||
create_from_search_client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": " ",
|
||||
"title": "\t",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
call_args = create_from_search_client._mock_jm.create_job.call_args
|
||||
job_create = call_args[0][0]
|
||||
# Session stores "ABBA" / "Waterloo" (see _make_search_session).
|
||||
assert job_create.artist == "ABBA"
|
||||
assert job_create.title == "Waterloo"
|
||||
|
||||
def test_session_consumed_atomically(self, create_from_search_client, auth_headers):
|
||||
"""Session is consumed (atomically read+deleted) via consume_search_session."""
|
||||
create_from_search_client.post(
|
||||
|
||||
@@ -38,9 +38,36 @@ class TestStorageServiceInit:
|
||||
assert service.bucket == mock_bucket
|
||||
|
||||
|
||||
class TestStorageServiceCopy:
|
||||
"""Test server-side copy (used to stage the tenant instrumental for the GCE encoder)."""
|
||||
|
||||
@patch("backend.services.storage_service.storage.Client")
|
||||
@patch("backend.services.storage_service.settings")
|
||||
def test_copy_blob(self, mock_settings, mock_client_class):
|
||||
mock_settings.gcs_bucket_name = "test-bucket"
|
||||
mock_src_blob = Mock()
|
||||
mock_bucket = Mock()
|
||||
mock_bucket.blob.return_value = mock_src_blob
|
||||
mock_client = Mock()
|
||||
mock_client.bucket.return_value = mock_bucket
|
||||
mock_client_class.return_value = mock_client
|
||||
|
||||
service = StorageService()
|
||||
result = service.copy_blob(
|
||||
"uploads/job123/audio/existing_instrumental.mp3",
|
||||
"jobs/job123/existing_instrumental.mp3",
|
||||
)
|
||||
|
||||
mock_bucket.blob.assert_called_once_with("uploads/job123/audio/existing_instrumental.mp3")
|
||||
mock_bucket.copy_blob.assert_called_once_with(
|
||||
mock_src_blob, mock_bucket, "jobs/job123/existing_instrumental.mp3"
|
||||
)
|
||||
assert result == "jobs/job123/existing_instrumental.mp3"
|
||||
|
||||
|
||||
class TestStorageServiceUpload:
|
||||
"""Test upload operations."""
|
||||
|
||||
|
||||
@patch("backend.services.storage_service.storage.Client")
|
||||
@patch("backend.services.storage_service.settings")
|
||||
def test_upload_file(self, mock_settings, mock_client_class):
|
||||
|
||||
@@ -56,6 +56,43 @@ def _make_job_mock(**kwargs):
|
||||
return job
|
||||
|
||||
|
||||
class TestSelectMixedAudioFiles:
|
||||
"""Regression tests for _select_mixed_audio_files() in file_upload.py.
|
||||
|
||||
The existing-instrumental file shares the uploads/{job}/audio/ directory with the
|
||||
mixed audio, so the 'audio/' prefix matches both. Before the fix, files[0] resolved to
|
||||
'existing_instrumental.mp3' (it sorts first) and transcription ran on the instrumental.
|
||||
"""
|
||||
|
||||
def _fn(self):
|
||||
from backend.api.routes.file_upload import _select_mixed_audio_files
|
||||
return _select_mixed_audio_files
|
||||
|
||||
def test_excludes_existing_instrumental(self):
|
||||
fn = self._fn()
|
||||
# Listing is sorted alphabetically by GCS, so the instrumental comes first.
|
||||
files = [
|
||||
"uploads/job123/audio/existing_instrumental.mp3",
|
||||
"uploads/job123/audio/mixed.mp3",
|
||||
]
|
||||
result = fn(files)
|
||||
assert result == ["uploads/job123/audio/mixed.mp3"]
|
||||
assert result[0] == "uploads/job123/audio/mixed.mp3"
|
||||
|
||||
def test_plain_audio_only_unchanged(self):
|
||||
fn = self._fn()
|
||||
files = ["uploads/job123/audio/My Song.flac"]
|
||||
assert fn(files) == files
|
||||
|
||||
def test_real_filenames_with_instrumental(self):
|
||||
fn = self._fn()
|
||||
files = [
|
||||
"uploads/job123/audio/existing_instrumental.mp3",
|
||||
"uploads/job123/audio/Eddy Grant - I Don't Wanna Dance Guide.mp3",
|
||||
]
|
||||
assert fn(files) == ["uploads/job123/audio/Eddy Grant - I Don't Wanna Dance Guide.mp3"]
|
||||
|
||||
|
||||
class TestApplyTenantOverrides:
|
||||
"""Tests for _apply_tenant_overrides() in file_upload.py."""
|
||||
|
||||
@@ -125,24 +162,70 @@ class TestApplyTenantOverrides:
|
||||
_, _, _, yt_upload = apply_fn(dist, tenant_config, "default", False, True)
|
||||
assert yt_upload is False
|
||||
|
||||
def test_request_values_take_precedence(self):
|
||||
"""Explicit request-level values are not overridden by tenant defaults."""
|
||||
def test_tenant_config_overrides_global_defaults(self):
|
||||
"""Tenant config is authoritative: it overrides any global/consumer default
|
||||
distribution settings already seeded into `dist`.
|
||||
|
||||
Regression guard: prod sets DEFAULT_DROPBOX_PATH / DEFAULT_GDRIVE_FOLDER_ID /
|
||||
DEFAULT_BRAND_PREFIX globally, which get_effective_distribution_settings seeds
|
||||
into `dist`. If tenant overrides only filled in *unset* fields, every tenant job
|
||||
would leak into the shared consumer Dropbox folder and global Google Drive.
|
||||
"""
|
||||
apply_fn = self._get_apply_fn()
|
||||
tenant_config = _make_tenant_config()
|
||||
|
||||
# `dist` arrives pre-seeded with the GLOBAL consumer defaults.
|
||||
dist = EffectiveDistributionSettings(
|
||||
dropbox_path="/Custom/Path",
|
||||
gdrive_folder_id="custom-folder",
|
||||
dropbox_path="/MediaUnsynced/Karaoke/Tracks-Organized", # global default
|
||||
gdrive_folder_id="global-consumer-folder", # global default
|
||||
discord_webhook_url=None,
|
||||
brand_prefix="CUSTOM",
|
||||
brand_prefix="NOMAD", # global default
|
||||
enable_youtube_upload=True,
|
||||
youtube_description=None,
|
||||
)
|
||||
|
||||
new_dist, _, _, _ = apply_fn(dist, tenant_config, "default", False, True)
|
||||
assert new_dist.brand_prefix == "CUSTOM"
|
||||
assert new_dist.dropbox_path == "/Custom/Path"
|
||||
assert new_dist.gdrive_folder_id == "custom-folder"
|
||||
# Tenant config wins on every distribution field.
|
||||
assert new_dist.brand_prefix == "VSTAR"
|
||||
assert new_dist.dropbox_path == "/Karaoke/Vocal-Star"
|
||||
assert new_dist.gdrive_folder_id == "gdrive-folder-123"
|
||||
|
||||
def test_gdrive_disabled_clears_global_default(self):
|
||||
"""When the tenant disables gdrive_upload, the global default GDrive folder is
|
||||
cleared so the tenant job never publishes to Google Drive (the B2B requirement)."""
|
||||
apply_fn = self._get_apply_fn()
|
||||
# Tenant has a gdrive folder configured but the feature is OFF — the disabled
|
||||
# flag must win, clearing both the configured folder and any global default.
|
||||
tenant_config = _make_tenant_config()
|
||||
tenant_config.features.gdrive_upload = False
|
||||
|
||||
dist = EffectiveDistributionSettings(
|
||||
dropbox_path=None,
|
||||
gdrive_folder_id="global-consumer-folder", # would otherwise leak
|
||||
discord_webhook_url=None,
|
||||
brand_prefix=None,
|
||||
enable_youtube_upload=True,
|
||||
youtube_description=None,
|
||||
)
|
||||
|
||||
new_dist, _, _, yt_upload = apply_fn(dist, tenant_config, "default", False, True)
|
||||
assert new_dist.gdrive_folder_id is None
|
||||
assert yt_upload is False
|
||||
|
||||
def test_dropbox_disabled_clears_path(self):
|
||||
"""When the tenant disables dropbox_upload, the Dropbox path is cleared."""
|
||||
apply_fn = self._get_apply_fn()
|
||||
tenant_config = _make_tenant_config()
|
||||
tenant_config.features.dropbox_upload = False
|
||||
|
||||
dist = EffectiveDistributionSettings(
|
||||
dropbox_path="/MediaUnsynced/Karaoke/Tracks-Organized",
|
||||
gdrive_folder_id=None, discord_webhook_url=None,
|
||||
brand_prefix=None, enable_youtube_upload=True, youtube_description=None,
|
||||
)
|
||||
|
||||
new_dist, _, _, _ = apply_fn(dist, tenant_config, "default", False, True)
|
||||
assert new_dist.dropbox_path is None
|
||||
|
||||
def test_no_tenant_config_passthrough(self):
|
||||
"""When no tenant config, all values pass through unchanged."""
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Proactive auto-correct generation, run on the API service.
|
||||
|
||||
The lyrics worker (a Cloud Run Job) triggers this via the internal endpoint
|
||||
once transcription + references are ready. It runs HERE — on the API service —
|
||||
rather than in the lyrics job, because the service already has a working
|
||||
ANTHROPIC_API_KEY + AUTO_CORRECT_COMPARE_MODELS configuration (the lyrics job's
|
||||
secrets use Cloud Run secret aliases that `gcloud run jobs update
|
||||
--update-secrets` can't extend; see docs/archive/2026-06-11-proactive-autocorrect-plan.md).
|
||||
|
||||
Pre-generates + caches the multi-model suggestion run so the review UI's
|
||||
on-load request is an instant cache hit. Best-effort: it must never raise — a
|
||||
failure just means the UI does the call on demand instead.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def process_proactive_auto_correct(job_id: str) -> dict:
|
||||
"""Generate + cache auto-correct suggestions for a job. Never raises.
|
||||
|
||||
Returns a small status dict for the endpoint to echo. Gated by
|
||||
settings.auto_correct_proactive_enabled; reads the corrections.json the
|
||||
lyrics worker just wrote (the same data the review UI loads on first open)
|
||||
and runs the multi-model path with default settings so the cache key lines
|
||||
up with the UI request.
|
||||
"""
|
||||
from backend.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.auto_correct_proactive_enabled:
|
||||
return {"status": "disabled"}
|
||||
|
||||
try:
|
||||
from backend.services.auto_correct import get_auto_correct_service
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
storage = StorageService()
|
||||
corrections_path = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
if not storage.file_exists(corrections_path):
|
||||
logger.info("[job:%s] proactive auto-correct skipped: no corrections.json", job_id)
|
||||
return {"status": "skipped", "reason": "no_corrections"}
|
||||
data = storage.download_json(corrections_path)
|
||||
segments = data.get("corrected_segments") or data.get("segments") or []
|
||||
reference_lyrics = data.get("reference_lyrics") or {}
|
||||
if not segments or not reference_lyrics:
|
||||
# No references → nothing to compare against. The reviewer can paste
|
||||
# references in the UI and trigger auto-correct manually later.
|
||||
logger.info(
|
||||
"[job:%s] proactive auto-correct skipped: %d segments, %d ref sources",
|
||||
job_id, len(segments), len(reference_lyrics),
|
||||
)
|
||||
return {"status": "skipped", "reason": "no_references"}
|
||||
|
||||
job = JobManager().get_job(job_id)
|
||||
service = get_auto_correct_service()
|
||||
result = await asyncio.wait_for(
|
||||
asyncio.to_thread(
|
||||
service.suggest,
|
||||
job_id=job_id,
|
||||
segments=segments,
|
||||
reference_lyrics=reference_lyrics,
|
||||
artist=getattr(job, "artist", None) if job else None,
|
||||
title=getattr(job, "title", None) if job else None,
|
||||
# Must match what the review UI sends (default settings,
|
||||
# multi-model) or the cache key won't line up.
|
||||
settings=AutoCorrectSettings(compare_models=True),
|
||||
),
|
||||
timeout=180,
|
||||
)
|
||||
logger.info(
|
||||
"[job:%s] proactive auto-correct done: %d suggestions cached (models=%s, %.1fs)",
|
||||
job_id, len(result.suggestions), result.model, result.elapsed_seconds,
|
||||
)
|
||||
return {"status": "generated", "suggestions": len(result.suggestions)}
|
||||
except Exception as e: # noqa: BLE001 — proactive is best-effort, never fatal
|
||||
logger.warning("[job:%s] proactive auto-correct failed (non-fatal): %s", job_id, e, exc_info=True)
|
||||
return {"status": "error", "message": str(e)}
|
||||
@@ -170,6 +170,26 @@ def create_lyrics_processor(
|
||||
)
|
||||
|
||||
|
||||
async def _trigger_proactive_auto_correct(job_id, job_log) -> None:
|
||||
"""Trigger proactive auto-correct generation on the API service.
|
||||
|
||||
The actual multi-model LLM call + caching runs on the API service (which
|
||||
has the working Anthropic key / compare-models config) — see
|
||||
backend/workers/auto_correct_worker.py. Here we just fire the HTTP trigger
|
||||
and await it. Best-effort and fully isolated: it must NEVER raise, fail the
|
||||
job, or block the pipeline — downstream stages are already triggered before
|
||||
this runs, and the service gates the work behind AUTO_CORRECT_PROACTIVE_ENABLED.
|
||||
"""
|
||||
try:
|
||||
from backend.services.worker_service import WorkerService
|
||||
|
||||
ok = await WorkerService().trigger_auto_correct(job_id)
|
||||
job_log.info("Proactive auto-correct trigger %s", "ok" if ok else "skipped/failed")
|
||||
except Exception as e: # noqa: BLE001 — never let auto-correct affect the job
|
||||
job_log.warning(f"Proactive auto-correct trigger failed (non-fatal): {e}")
|
||||
logger.warning(f"[job:{job_id}] Proactive auto-correct trigger failed (non-fatal): {e}")
|
||||
|
||||
|
||||
async def process_lyrics_transcription(job_id: str) -> bool:
|
||||
"""
|
||||
Process lyrics transcription and correction for a job using karaoke_gen.LyricsProcessor.
|
||||
@@ -516,7 +536,15 @@ async def process_lyrics_transcription(job_id: str) -> bool:
|
||||
# This will check if audio is also complete and transition to next stage if so
|
||||
job_log.info("Lyrics worker complete, checking if audio is also done...")
|
||||
job_manager.mark_lyrics_complete(job_id)
|
||||
|
||||
|
||||
# Proactively pre-generate + cache AI auto-correct suggestions so
|
||||
# they're ready when the reviewer opens the lyrics UI. The work
|
||||
# runs on the API service (it has the Anthropic key); we just fire
|
||||
# the trigger here. Done AFTER mark_lyrics_complete (downstream is
|
||||
# already triggered, so this never blocks it) and fully isolated —
|
||||
# it can never fail or delay the job beyond its own timeout.
|
||||
await _trigger_proactive_auto_correct(job_id, job_log)
|
||||
|
||||
duration = time.time() - start_time
|
||||
# Store worker-level timing
|
||||
job_manager.update_processing_metadata(job_id, "timing.lyrics_worker_seconds", round(duration, 1))
|
||||
|
||||
@@ -107,6 +107,21 @@ async def _encode_via_gce(
|
||||
instrumental_selection = job.state_data.get('instrumental_selection', 'clean')
|
||||
existing_instrumental = getattr(job, 'existing_instrumental_gcs_path', None)
|
||||
|
||||
# Stage the user-provided instrumental into the encoder's input prefix (jobs/{job_id}/).
|
||||
# It is uploaded under uploads/, which the GCE encoder does NOT pull via input_gcs_path;
|
||||
# copying it here makes the encoder's recursive find_file("*existing_instrumental*")
|
||||
# locate it regardless of the worker image version (older encoder images predate the
|
||||
# encoding_config "existing_instrumental" download path). Without this, tenant /
|
||||
# existing-instrumental jobs fail with "No instrumental audio found".
|
||||
if existing_instrumental:
|
||||
try:
|
||||
ext = os.path.splitext(existing_instrumental)[1].lower() or ".mp3"
|
||||
staged_path = f"jobs/{job_id}/existing_instrumental{ext}"
|
||||
storage.copy_blob(existing_instrumental, staged_path)
|
||||
job_log.info(f"Staged existing instrumental for encoder: {staged_path}")
|
||||
except Exception as e:
|
||||
job_log.warning(f"Failed to stage existing instrumental into jobs/ prefix: {e}")
|
||||
|
||||
encoding_config = {
|
||||
"formats": ["mp4_4k_lossless", "mp4_4k_lossy", "mp4_720p"],
|
||||
"base_name": base_name,
|
||||
|
||||
@@ -452,6 +452,27 @@ class VideoWorkerOrchestrator:
|
||||
if self.config.countdown_padding_seconds:
|
||||
self.job_log.info(f"Countdown padding: {self.config.countdown_padding_seconds}s - instrumental will be padded")
|
||||
|
||||
# The GCE encoder downloads its inputs from input_gcs_path (jobs/{job_id}/) and resolves
|
||||
# the instrumental via find_file. For jobs that supply their own instrumental
|
||||
# (existing_instrumental flow, e.g. tenant submissions), the file lives under
|
||||
# uploads/{job_id}/audio/existing_instrumental.* — which is NOT under jobs/{job_id}/ and
|
||||
# is NOT a name the encoder's 'custom' branch looks for. The encoder's 'custom' branch
|
||||
# globs for "*custom_instrumental*.{flac,mp3}" / "*Instrumental Custom*", so copy the
|
||||
# supplied instrumental into jobs/{job_id}/custom_instrumental.<ext> (server-side, from
|
||||
# the authoritative GCS source — no dependency on local temp files). Without this,
|
||||
# existing-instrumental jobs fail at the encoder with "No instrumental audio found".
|
||||
if encoding_backend.name == "gce" and self.storage:
|
||||
try:
|
||||
srcs = self.storage.list_files(f"uploads/{self.config.job_id}/audio/existing_instrumental")
|
||||
if srcs:
|
||||
src = srcs[0]
|
||||
ext = os.path.splitext(src)[1].lower() or ".mp3"
|
||||
dest = f"jobs/{self.config.job_id}/custom_instrumental{ext}"
|
||||
self.storage.copy_blob(src, dest)
|
||||
self.job_log.info(f"Staged custom instrumental for GCE encoder: {dest}")
|
||||
except Exception as e:
|
||||
self.job_log.warning(f"Failed to stage custom instrumental for GCE encoder: {e}")
|
||||
|
||||
# Run encoding
|
||||
with job_span("encoding", self.config.job_id) as span:
|
||||
add_span_event("encoding_started", {"backend": encoding_backend.name})
|
||||
|
||||
+148
@@ -545,6 +545,95 @@ Adds user-pasted lyrics as a new reference source, re-runs the correction pipeli
|
||||
|
||||
Returns `{ "status": "success", "data": <CorrectionData> }`.
|
||||
|
||||
#### AI Auto-Correct Suggestions
|
||||
|
||||
```http
|
||||
POST /api/review/{job_id}/auto-correct
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"segments": [ "...client's current corrected_segments..." ],
|
||||
"reference_lyrics": { "genius": { "segments": [...] } },
|
||||
"artist": "Twenty One Pilots",
|
||||
"title": "Chlorine",
|
||||
"settings": {
|
||||
"suggest_adlib_removal": true,
|
||||
"allow_insertions": true,
|
||||
"min_confidence": 0.0,
|
||||
"compare_models": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
AI correction suggestions for the lyrics review UI. Stateless: one whole-song
|
||||
LLM call per model (Claude models use the Anthropic API via the
|
||||
`anthropic-api-key` secret, Gemini models use Vertex AI) compares the
|
||||
client's current transcription against the reference sources and returns
|
||||
word-id-keyed suggestions. Nothing is applied server-side — the reviewer
|
||||
accepts/rejects each suggestion in the UI and persistence flows through the
|
||||
existing corrections/complete paths.
|
||||
|
||||
The review UI always requests the multi-model path (`compare_models: true`)
|
||||
and auto-runs once on load, so suggestions appear without a click. To make
|
||||
that load instant, suggestions are **proactively pre-generated and cached**
|
||||
once transcription + references are ready: the lyrics worker fires an internal
|
||||
trigger (`POST /api/internal/workers/auto-correct`) that runs the same
|
||||
multi-model generation on the API service (gated by
|
||||
`AUTO_CORRECT_PROACTIVE_ENABLED`; best-effort — it never blocks or fails the
|
||||
karaoke job). Because the proactive run uses the same default settings the UI
|
||||
sends, the on-load request is normally a cache hit with no extra cost.
|
||||
|
||||
With `"compare_models": true`, every model in `AUTO_CORRECT_COMPARE_MODELS`
|
||||
(semicolon-separated) is queried in parallel; identical suggestions are
|
||||
deduplicated with a per-suggestion `consensus` count, and suggestions that
|
||||
target overlapping words with different outcomes share a `conflict_group`
|
||||
(the UI accepts at most one per group). A model failure in compare mode is
|
||||
reported in `warnings` while remaining model results are returned; only if
|
||||
all models fail does the endpoint return 502.
|
||||
|
||||
Returns:
|
||||
|
||||
```json
|
||||
{
|
||||
"suggestions": [
|
||||
{
|
||||
"id": "uuid",
|
||||
"op": "replace",
|
||||
"word_ids": ["w3"],
|
||||
"segment_ids": ["seg-1"],
|
||||
"original_text": "glory",
|
||||
"new_text": "chlorine",
|
||||
"reason": "All references read 'chlorine' here",
|
||||
"category": "mishearing",
|
||||
"confidence": 0.95,
|
||||
"models": ["claude-opus-4-8", "gemini-3.1-pro-preview"],
|
||||
"consensus": 2,
|
||||
"total_models": 2,
|
||||
"conflict_group": null
|
||||
}
|
||||
],
|
||||
"model": "claude-opus-4-8, gemini-3.1-pro-preview",
|
||||
"elapsed_seconds": 27.4,
|
||||
"settings_applied": { "suggest_adlib_removal": true, "allow_insertions": true, "min_confidence": 0.0 },
|
||||
"warnings": [],
|
||||
"cached": false
|
||||
}
|
||||
```
|
||||
|
||||
Results are cached per job in GCS
|
||||
(`jobs/{job_id}/lyrics/auto_correct_cache/{hash}.json`), keyed on the exact
|
||||
input: word ids + texts, reference lyrics texts, settings, and the resolved
|
||||
model list. Re-running on unmodified lyrics returns the previous result with
|
||||
`"cached": true` and incurs no LLM cost; any edit to the lyrics, references,
|
||||
or settings produces a new key and a fresh run. Cache reads/writes are
|
||||
best-effort — storage failures degrade to a normal uncached run.
|
||||
|
||||
`op` is `replace` | `delete` | `insert_after` (for `insert_after`, `word_ids`
|
||||
holds the anchor word). Errors: `422` when no reference lyrics are available,
|
||||
`400` for invalid settings, `502` when the model call fails or returns
|
||||
malformed output. Design/eval background:
|
||||
`docs/archive/2026-06-10-lyrics-auto-correction-reeval-plan.md`.
|
||||
|
||||
#### Search Reference Lyrics
|
||||
|
||||
```http
|
||||
@@ -742,6 +831,65 @@ Response:
|
||||
|
||||
When `has_community` is true, the frontend shows a dismissible green banner suggesting the user check existing versions before creating a new one.
|
||||
|
||||
#### Match Judge (artist/title formatting + match acceptance)
|
||||
|
||||
```http
|
||||
POST /api/catalog/match-judge
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"artist": "paramore",
|
||||
"title": "big man, little dignity",
|
||||
"audio_confidence_tier": 1,
|
||||
"stage": "full"
|
||||
}
|
||||
```
|
||||
|
||||
Decides the official formatting for a typed artist/title and whether it matches a
|
||||
real song. A deterministic normalizer + the catalog run first; a light Vertex
|
||||
Gemini model (`MATCH_JUDGE_MODEL`, default `gemini-3.5-flash`) is consulted
|
||||
**only** when those aren't confident. `audio_confidence_tier` (1=strong..3=weak,
|
||||
optional) lets the judge tell whether weak audio results hint at a typo. The call
|
||||
never blocks job creation — on timeout/error it returns a `none` verdict. Disable
|
||||
the AI layer with `MATCH_JUDGE_ENABLED=false` (deterministic+catalog still run).
|
||||
|
||||
`stage` (optional, `"fast"` | `"full"`, default `"full"`) supports a two-call
|
||||
pattern the frontend uses to keep the tidy off the critical path:
|
||||
|
||||
- `"fast"` — catalog-only pass (no AI, `audio_confidence_tier` ignored). The
|
||||
client fires this on mount, in parallel with the audio search. Returns a
|
||||
confident catalog verdict when it can, otherwise `needs_ai: true` (a marker
|
||||
telling the client to follow up with a `"full"` call once the tier is known).
|
||||
- `"full"` — the complete pipeline. Runs the AI judge when the catalog isn't
|
||||
confident, **and** when a confident catalog match coincides with a weak audio
|
||||
tier (`>= 3`) — a weak tier means the match may be a junk/typo'd entry, so the
|
||||
AI verifies it and can override.
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"kind": "cosmetic",
|
||||
"confident": true,
|
||||
"canonical_artist": "Paramore",
|
||||
"canonical_title": "Big Man, Little Dignity",
|
||||
"alternatives": [],
|
||||
"engine": "catalog",
|
||||
"reason": "formatting differs from catalog",
|
||||
"needs_ai": false
|
||||
}
|
||||
```
|
||||
|
||||
`kind` drives the Step 2 UI: `cosmetic` → silent tidy with a two-way toggle
|
||||
("keep what I typed" ⇄ "use tidied version"); `content` (confident) → applied
|
||||
with a "Corrected … · Undo" toggle, re-searching audio only when the original
|
||||
results were weak; `ambiguous` (or unconfident `content`) → an ask-first "Did you
|
||||
mean?" prompt; `none` → no change. `needs_ai` is only ever `true` on a `"fast"`
|
||||
verdict that couldn't decide; it is always `false` on a `"full"` verdict.
|
||||
|
||||
Until the judge settles, the Step 2 audio-selection buttons are disabled with a
|
||||
subtle "Checking song details…" indicator, so a user can never advance with
|
||||
un-tidied metadata; a 12s timeout guarantees the gate releases.
|
||||
|
||||
### Audio Search
|
||||
|
||||
#### Search for Audio
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -66,6 +72,13 @@ When a metadata key is missing, don't set it to "now" and skip the action — th
|
||||
### Pending Jobs Guard Must Not Reset Idle Timestamps (Mar 2026)
|
||||
When pending CI jobs are detected, keep runners alive but don't refresh their `last-activity` timestamps. Refreshing timestamps resets the idle timer, so runners can never accumulate enough idle time to be stopped — even after all jobs complete.
|
||||
|
||||
### "Is It Busy?" Guards Must Fail SAFE, Not Fail Open (Jun 2026)
|
||||
Both stop paths for the GCE encoder VMs guarded against killing a busy worker by checking `/health`'s `active_jobs` — but both defaulted to **0 (= idle)** when `/health` was unreachable or slow (CI drain: `... || echo "0"`; idle Cloud Function: `except: return 0`). A busy encoder runs a 4K ffmpeg on all 32 cores and shares uvicorn with the encode subprocess, so `/health` can miss its timeout *while the VM is hard at work*. Combined with blue/green deploy churn (every merge cycles the VMs) and the 5-min idle check, this stopped VMs **mid-render**, orphaning the in-memory job so backend polls got 404 → "lost contact with worker ... not found" (incident 2026-06-15; the burst was self-inflicted by rapid PR merges during the tenant E2E, 0 in the prior 48h). **Rule:** a guard that decides whether to destroy work must treat "couldn't confirm" as "assume busy / don't act," never as the permissive default. Retry the probe, and only act on a *confirmed* safe signal (here: a real `active_jobs == 0` from a 200 response), with a bounded timeout so a wedged worker can't block forever.
|
||||
|
||||
### In-Flight Status Polls Must Be Pinned to the Worker, Not the Floating Primary (Jun 2026)
|
||||
|
||||
The day after the drain fix above, the **same** "lost contact ... not found" error recurred (incident 2026-06-16, job d3af33ae) — but this time the VM was *never* stopped mid-render. `EncodingService.get_job_status()` re-resolved the worker URL on **every poll** via `_get_worker_url()` → `config.active_url`. A blue-green deploy swapped the Firestore `primary_vm` pointer at 04:33:46 (worker-a → worker-b); 7s later the in-flight render's polls started hitting worker-b, which had never received the job → 404 → 5 failures → render failed. Worker-a was alive and finished the encode the whole time; nobody was listening. The drain (which keeps the old VM *alive*) can't help — the job is orphaned at the **poll layer** the instant the pointer swaps, 47s before any VM stop. **Rule:** once a job is accepted by a specific worker, every subsequent poll for that job must target *that* worker until terminal — the poll follows the job, not the floating primary pointer. URL re-resolution is correct for *capacity fallback* (dead primary → start fallback → re-route a fresh submission) but wrong for an *in-flight poll* (a different/fresh VM can't have the job; re-routing only yields 404). Fix: capture the worker URL **after** submit (reflects a fallback re-route, precedes any later swap) and pass it as `worker_url=` through `wait_for_completion` → `get_job_status`, which then pins the request and sets `allow_failover=False`. v0.184.2.
|
||||
|
||||
### Cloud Run GPU: Let the Platform Scale, Not Your Code (Mar 2026)
|
||||
|
||||
**Don't use fire-and-forget + semaphore on Cloud Run.** We tried making the `/separate` endpoint return immediately (fire-and-forget background thread) with a `threading.Semaphore(1)` to serialize GPU work. Cloud Run couldn't see background threads as "busy", so it routed ALL requests to one instance where they queued behind the semaphore — causing 30-minute timeouts in production.
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -58,6 +58,8 @@ curl -X POST "https://api.nomadkaraoke.com/api/internal/workers/video" \
|
||||
|
||||
**Prevention:** The video worker now runs as a **Cloud Run Job** (`USE_CLOUD_RUN_JOBS_FOR_VIDEO=true`), which runs to completion and is immune to Cloud Run Service deployment rollouts. This replaces the `BackgroundTask` pattern that was vulnerable to instance termination during deployments. Additionally, CI performs a graceful drain before restarting the GCE encoding worker, the encoding client retries for ~90s, and status polling tolerates up to 5 consecutive failures.
|
||||
|
||||
Since v0.184.2, in-flight status polls are also **pinned to the worker that accepted the job** (`get_job_status(..., worker_url=)`), so a blue-green deploy that swaps the `active_url` primary pointer mid-render no longer migrates the poll to a worker that never received the job. If you still see `lost contact with worker after 5 consecutive poll failures: Encoding job <ID> not found`, confirm via step 2 above that the worker the job was submitted to (not necessarily the current primary) still has the job — a `not found` from the *current* primary while the job is alive on the old primary was the pre-v0.184.2 failure mode (incident 2026-06-16, job d3af33ae).
|
||||
|
||||
---
|
||||
|
||||
## CDG/TXT packages missing from completed job
|
||||
|
||||
@@ -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,53 @@
|
||||
# Audio Editor: Fade In / Fade Out Buttons
|
||||
|
||||
**Date:** 2026-06-11
|
||||
**Branch:** `feat/sess-20260611-1250-audio-fade`
|
||||
|
||||
## Goal
|
||||
|
||||
Add **Fade In** and **Fade Out** action buttons to the audio editor toolbar so users
|
||||
can ramp the volume of a selected region gracefully instead of a hard cut.
|
||||
|
||||
**Primary use case (user quote):** "when cutting off a long intro from a song, we'll
|
||||
likely want it to fade in gracefully over a few seconds rather than come in really loud
|
||||
at the point it was trimmed to."
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **Edge-gated display**, mirroring the existing `Trim Start` / `Trim End` buttons:
|
||||
- **Fade In** appears when the selection starts near the beginning (`startSeconds < 1`).
|
||||
- **Fade Out** appears when the selection ends near the end (`endSeconds > duration - 1`).
|
||||
- This matches the real use case (fade the new start after trimming an intro; fade the
|
||||
new end after trimming an outro) and avoids `afade`'s surprising behaviour of
|
||||
silencing audio outside the fade window for mid-track selections.
|
||||
- **Duration-preserving** (like `mute`) — fades only adjust volume, they don't change length.
|
||||
- Implemented with FFmpeg's `afade` filter: `afade=t=in|out:st={start}:d={end-start}`.
|
||||
- No new keyboard shortcut (a single key can't disambiguate in vs out cleanly).
|
||||
|
||||
## Changes
|
||||
|
||||
### Backend
|
||||
1. `backend/services/audio_edit_service.py`
|
||||
- Add `fade_region(input_path, start, end, direction, output_path)` — validates
|
||||
`direction in {"in","out"}`, runs `afade`, returns metadata (duration preserved).
|
||||
- Dispatch `fade_in` / `fade_out` in `apply_edit`.
|
||||
2. `backend/api/routes/review.py`
|
||||
- Add `"fade_in"`, `"fade_out"` to `valid_operations`.
|
||||
|
||||
### Frontend
|
||||
3. `frontend/components/audio-editor/AudioEditor.tsx`
|
||||
- `handleFadeIn()` / `handleFadeOut()` → `handleApply("fade_in"|"fade_out", {start_seconds, end_seconds})`.
|
||||
- Edge-gated toolbar buttons with `TrendingUp` / `TrendingDown` icons.
|
||||
4. i18n: add `fadeIn`, `fadeOut`, `fadeInSelection`, `fadeOutSelection` to
|
||||
`frontend/messages/en.json`, then `translate.py --target all` (33 locales).
|
||||
|
||||
## Tests
|
||||
- **Backend unit** (`test_audio_edit_service.py`): `fade_region` in/out ffmpeg args,
|
||||
duration preserved, invalid direction rejected, `apply_edit` dispatch for fade_in/out.
|
||||
- **Backend route** (`test_audio_edit_routes.py`): fade_in/fade_out accepted (not "Invalid operation").
|
||||
- **Frontend** (`AudioEditor.test.tsx`): Fade In button renders for a start-anchored
|
||||
selection and calls `applyAudioEdit` with `fade_in`.
|
||||
|
||||
## Out of Scope (possible future work)
|
||||
- Mid-track fades (would need a `volume` envelope filter, not `afade`).
|
||||
- Configurable fade curve / duration input box.
|
||||
@@ -0,0 +1,82 @@
|
||||
# Proactive AI Auto-Correction + UI De-AI-ification
|
||||
|
||||
**Date:** 2026-06-11
|
||||
**Branch:** `feat/sess-20260611-1514-autocorrect-cost-logging`
|
||||
**Context:** Measured cost ~$0.13/track (multi-model). Cheap enough to run on every job.
|
||||
|
||||
## Goal (user's words)
|
||||
|
||||
Run multi-model auto-correction automatically on every karaoke job so suggestions
|
||||
are ready to review/approve/reject by the time anyone reaches the lyrics review UI.
|
||||
Must fail gracefully — never block the karaoke job if AI APIs are flaky / out of
|
||||
credits. Remove all "AI"/"model" mentions from the review UI; button becomes just
|
||||
"Auto-correct"; drop the user-configurable model selection and always use multi-model.
|
||||
Keep the button for the case where references arrive later (user pastes reference
|
||||
lyrics during review, then clicks it).
|
||||
|
||||
## Architecture decisions (validated against the codebase)
|
||||
|
||||
1. **Where proactive runs: the `lyrics-transcription-job` Cloud Run Job**, after
|
||||
`mark_lyrics_complete()` (so downstream screens/render are already triggered and
|
||||
are NOT blocked), awaited (a fire-and-forget task would die when the job
|
||||
entrypoint returns). The job is long-lived, so an extra ~15-30s is fine and the
|
||||
process stays alive to finish the cache write.
|
||||
2. **Cache alignment = the whole point.** `AutoCorrectService` already writes a
|
||||
per-job GCS cache keyed on (models, settings, word-id+text list, ref texts,
|
||||
artist, title). If the proactive run uses the SAME inputs + settings + models the
|
||||
UI will send, the UI's on-load call is a **cache hit** (instant, no second spend).
|
||||
- Proactive settings = `AutoCorrectSettings(compare_models=True)` (all other
|
||||
fields default). Backend defaults == frontend `DEFAULT_AUTO_CORRECT_SETTINGS`
|
||||
once we flip `compare_models` to `true`. Both paths build settings server-side
|
||||
and hash the same dict.
|
||||
- `models` is derived server-side identically in both paths via `_models_for()`.
|
||||
- Proactive reads `corrections.json` (corrected_segments + reference_lyrics) — the
|
||||
exact data the review-data endpoint serves on first load (before any edits).
|
||||
3. **Env/secret wiring (REQUIRED for it to actually work).** The lyrics job currently
|
||||
has neither `ANTHROPIC_API_KEY` nor `AUTO_CORRECT_*`. It uses the SAME SA as the
|
||||
API service (`karaoke-backend@…`), which already reads `anthropic-api-key`
|
||||
(project-level secret access) — so adding the secret to the job is low-risk.
|
||||
Add via `--update-env-vars`/`--update-secrets` in the ci.yml job-update step
|
||||
(merges, doesn't wipe the existing 12 vars).
|
||||
4. **Feature flag:** `auto_correct_proactive_enabled` (config), default **false** in
|
||||
code, set `AUTO_CORRECT_PROACTIVE_ENABLED=true` on the lyrics job via ci.yml.
|
||||
5. **UI auto-run on load:** on review load, if references exist, auto-invoke
|
||||
auto-correct (cache hit → instant). Keep the button for manual re-run after the
|
||||
user pastes references. Always send `compare_models: true`.
|
||||
|
||||
## Changes
|
||||
|
||||
### Backend
|
||||
- `backend/config.py`: add `auto_correct_proactive_enabled`.
|
||||
- `backend/workers/lyrics_worker.py`: after `mark_lyrics_complete`, await a guarded
|
||||
helper `_run_proactive_auto_correct(job_id, ...)` — loads corrections.json, calls
|
||||
`suggest(..., settings=AutoCorrectSettings(compare_models=True))`, `asyncio.wait_for`
|
||||
timeout, swallow ALL exceptions (log only). Never affects job status.
|
||||
- Tests: worker test that it's gated by the flag, swallows errors, and skips when no
|
||||
references.
|
||||
|
||||
### Infra
|
||||
- `.github/workflows/ci.yml`: lyrics-transcription-job update step gains
|
||||
`--update-env-vars "AUTO_CORRECT_MODEL=claude-fable-5,AUTO_CORRECT_COMPARE_MODELS=claude-fable-5;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true"`
|
||||
and `--update-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest"`.
|
||||
|
||||
### Frontend (`frontend/`, next-intl, 33 locales)
|
||||
- Always multi-model: `DEFAULT_AUTO_CORRECT_SETTINGS.compare_models = true`; remove
|
||||
the compare/model toggle from `AutoCorrectModal.tsx`.
|
||||
- Strip model attribution: remove model-name badge + consensus "X/Y models" badge in
|
||||
`AutoCorrectPanel.tsx`; reword the conflict badge to not mention models (keep the
|
||||
conflict-resolution behavior).
|
||||
- Rename button to "Auto-correct"; remove "AI"/"model" from all related strings.
|
||||
- Auto-run on review load when references exist (cache hit → instant); keep button.
|
||||
- i18n: edit `messages/en.json`, then `python frontend/scripts/translate.py
|
||||
--messages-dir frontend/messages --target all` for all 33 locales.
|
||||
- Update `e2e/production/auto-correct-suggestions.spec.ts` button selector.
|
||||
|
||||
## Failure modes (all non-blocking by design)
|
||||
- Anthropic down / no credits → claude call raises, caught; Gemini result still cached
|
||||
(multi-model degrades to whatever answered). UI on-load call same behaviour.
|
||||
- Both providers fail → proactive logs warning, job proceeds normally; UI on-load call
|
||||
returns 502 and the panel shows nothing (or the manual button can retry later).
|
||||
- Proactive task times out → `wait_for` cancels it, job proceeds.
|
||||
- No references at lyrics-complete time → proactive skipped; user pastes refs in UI →
|
||||
clicks button → on-demand call.
|
||||
@@ -0,0 +1,105 @@
|
||||
# Artist/Title Matching, Suggestions & Auto-Correction Rework (Phase 1)
|
||||
|
||||
**Date:** 2026-06-15
|
||||
**Worktree:** `karaoke-gen-submission-form-simplify`
|
||||
**Branch:** `feat/sess-20260615-0101-submission-form-simplify`
|
||||
**Status:** Design + plan — pending implementation
|
||||
|
||||
## Problem
|
||||
|
||||
On Step 2 ("Choose Audio") the wizard stacks two green "success" cards: the **"Song found in our database"** catalog panel and the **"Perfect match found"** audio card. User feedback: the first reads like "we already have this karaoke video," when its only real job is to nudge the user toward **official artist/title formatting** (a quality-bar concern for *published* tracks). It's confusing, and the underlying case-insensitive match is imperfect.
|
||||
|
||||
This phase reworks **only** the artist/title matching → suggestion → auto-correction behavior. The broader flow structure is deliberately left intact (see "Constraints from history"). The title-screen preview perf fix is tracked separately.
|
||||
|
||||
## Decisions (from 2026-06-15 brainstorm with Andrew)
|
||||
|
||||
1. **Invisible cosmetic tidy.** When formatting differs only cosmetically (casing, spacing, punctuation, diacritics, `&`/`feat.` conventions) and we're confident it's the same song, **silently apply** the official formatting. No green "database" card. Show only a faint, dismissible line: *"Tidied to **Paramore — Big Man, Little Dignity** · keep what I typed"*.
|
||||
2. **Confident content correction → auto-apply + surface + smart re-search.** When the correction changes actual characters (e.g. `Yesteray → Yesterday`) and we're confident, apply it **and** surface it with one-tap Undo: *"Corrected to **Yesterday** — you typed 'Yesteray' · Undo"*. Because characters changed, the original audio search may be poor, so **re-run the audio search** — automatically **only when the original results were weak** (tier 3 / empty); otherwise offer a quiet "Search again" link.
|
||||
3. **Ambiguous → ask first.** When the judge isn't confident which song is meant (multiple plausible candidates), show an ask-first prompt: *"Did you mean **X**? [Use this] [Keep mine]"* before changing anything.
|
||||
4. **Three-layer engine, all in v1.** Deterministic rules → catalog canonical → light AI judge. **The AI judge fires only when the deterministic + catalog layers are not confident** (cheap; happy path never invokes it).
|
||||
|
||||
## Constraints from history (do NOT regress)
|
||||
|
||||
From `docs/archive/2026-02-28-ux-*`, `2026-03-02-decouple-search-from-job-creation.md`, `2026-03-08-step2-song-suggestions.plan.md`, `2026-03-08-fuzzy-did-you-mean.plan.md`, `docs/LESSONS-LEARNED.md`, PRs #444/#451/#480/#495/#512:
|
||||
|
||||
- **No Step-1 autocomplete.** It was added (PR #451) then removed (PR #512) because users didn't understand it. Suggestions belong on Step 2, in parallel with the audio search.
|
||||
- **Cosmetic correction must NOT restart the audio search.** Already a documented decision — the existing catalog `onArtistTitleCorrection` updates artist/title without re-searching. Preserve this. (Content corrections that change characters MAY re-search — see decision 2.)
|
||||
- **Deferred job creation (search-session pattern).** No job is created until the final confirm step. Don't move creation earlier. The tidied artist/title is passed at `create-from-search` time; the audio `search_session_id` is unaffected by a metadata tidy.
|
||||
- **Preserve the fuzzy artist-tiebreaker lesson:** when title-matching returns multiple artists with the same song name, use the user's (possibly garbled) artist input as a tiebreaker. And the gating: fuzzy/"did you mean" only triggers when audio results are poor.
|
||||
- **`display_artist`/`display_title`** stay distinct from matching `artist`/`title`; they're set at creation time. The tidy applies to the **matching** artist/title (what drives search, lyrics, and published metadata).
|
||||
- **Public vs private brand rule, audio-before-customize ordering, combined review flow** — untouched by this phase.
|
||||
|
||||
## Architecture
|
||||
|
||||
Consolidate today's scattered client-side matching (case-insensitive exact match in `SongSuggestionPanel` + LCS fuzzy in `audio-search-utils.ts`) into **one backend "match judge" service**, called from Step 2 in parallel with the audio search (replacing the current `searchCatalogTracks` + client fuzzy effect). Rationale: testable, consistent canonical formatting, and the AI layer needs the backend's LLM clients/keys.
|
||||
|
||||
### Backend: `POST /api/catalog/match-judge`
|
||||
|
||||
Request: `{ artist, title, audio_confidence_tier?: 1|2|3 }`
|
||||
(The frontend passes the audio search's computed confidence tier so the judge knows whether weak results suggest a typo.)
|
||||
|
||||
Pipeline (server-side):
|
||||
1. **Deterministic normalize** (reuse/extend `karaoke_gen.utils.normalize_text`): trim, collapse whitespace, fix obvious casing (title-case with small-word handling), straighten quotes, standardize `feat.`/`ft.` → `(feat. …)` and `and`↔`&` per house style.
|
||||
2. **Catalog lookup** (existing `search_tracks` via `catalog_proxy_service`). If a candidate matches the normalized input under a strict normalized-equality test → **confident cosmetic**: return the catalog's canonical `artist_name`/`track_name`.
|
||||
3. **AI judge — only if (1)+(2) not confident.** Invoke a light model (see "Model") with the typed input, the top catalog candidates, and the audio tier. It returns a structured verdict.
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"kind": "cosmetic | content | ambiguous | none",
|
||||
"confident": true,
|
||||
"canonical_artist": "Paramore",
|
||||
"canonical_title": "Big Man, Little Dignity",
|
||||
"alternatives": [{"artist": "...", "title": "..."}],
|
||||
"engine": "deterministic | catalog | ai",
|
||||
"reason": "casing only"
|
||||
}
|
||||
```
|
||||
- `kind=cosmetic` → frontend applies invisibly + faint line (no re-search).
|
||||
- `kind=content` + `confident` → frontend auto-applies + Undo line; re-search if audio tier was weak.
|
||||
- `kind=ambiguous` (or `content` not confident) → frontend shows ask-first "Did you mean?" with `alternatives`.
|
||||
- `kind=none` → no suggestion (leave user input as typed).
|
||||
|
||||
**Resilience:** AI judge runs under a short timeout (~2–3s) and is fully optional — on timeout/error/unparseable output, fall back to deterministic+catalog result (or `kind=none`). Never block the audio search; never error the request. Mirror `auto_correct`'s greppable usage/cost logging (`match-judge usage/cost job/session=…`).
|
||||
|
||||
### Model (decided)
|
||||
|
||||
Reuse `auto_correct` dispatch (`claude*` → Anthropic, else Gemini via `genai.Client(vertexai=True, project=…, location="global").models.generate_content(model=…)`).
|
||||
**Decision (Andrew, 2026-06-15):** default `MATCH_JUDGE_MODEL=gemini-3.5-flash` — the latest Vertex Gemini Flash (https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/gemini/3-5-flash). Passed bare to the genai Vertex client exactly like `auto_correct` passes `gemini-3.1-pro-preview`. No `ANTHROPIC_API_KEY` needed. Env-configurable, so if Vertex requires a version suffix it's a one-line env change (an invalid id surfaces as a loud error on first call). Add `gemini-3.5-flash` pricing to `pricing.py` for cost logging.
|
||||
|
||||
### Frontend (`AudioSourceStep.tsx`)
|
||||
|
||||
- Replace the parallel `searchCatalogTracks` + client fuzzy `useEffect` with a single `api.matchJudge(artist, title, tier)` call fired in parallel on mount (after the audio tier is known, or fired and reconciled when the tier resolves).
|
||||
- **Remove** the green `SongSuggestionPanel`. Add a quiet `TidyNotice` (cosmetic) and reuse/restyle `DidYouMeanBanner` for the surfaced-content (Undo) and ambiguous (ask) cases.
|
||||
- Wire cosmetic/confident-content application through the existing `onArtistTitleCorrection` (no restart). Add a `reSearch()` path (reuse `handleFuzzyAccept`'s restart logic) gated on weak prior results for content corrections.
|
||||
- Keep the `confidence.tier` gating and artist-tiebreaker semantics (now enforced server-side, but the frontend still passes the tier).
|
||||
|
||||
## Out of scope (this phase)
|
||||
|
||||
- Title-screen preview perf (separate task: smaller canvas + low-res bg + preload at step 2 + spinner).
|
||||
- Any change to step count / visibility / customize / job-creation timing.
|
||||
- Auto-selecting audio on a Tier-1 match (possible later, separately).
|
||||
|
||||
## Testing strategy
|
||||
|
||||
Per `docs/TESTING.md`:
|
||||
- **Backend unit:** deterministic normalizer rule table (casing, spacing, punctuation, feat./&, quotes); judge response parsing; confidence/kind classification; AI-failure fallback; "only call AI when not confident" gating.
|
||||
- **Backend integration:** `/api/catalog/match-judge` happy/edge paths with catalog mocked and AI mocked.
|
||||
- **Frontend unit (Jest):** TidyNotice rendering + Undo; content-correction auto-apply + smart re-search gating (weak vs ok results); ambiguous ask-first; preserve "no restart on cosmetic".
|
||||
- **E2E (Playwright) + prod E2E:** end-to-end on a real song (cosmetic case), a typo case (content + re-search), and an ambiguous case.
|
||||
|
||||
## Telemetry
|
||||
|
||||
- Log judge decisions + engine used + latency + token cost (greppable, like `auto-correct usage/cost`).
|
||||
- Count cosmetic / content / ambiguous / none and Undo clicks to measure real-world correction quality (informs whether thresholds need tuning).
|
||||
|
||||
## Open decisions
|
||||
|
||||
1. ~~Judge model default~~ — DECIDED: `gemini-3.5-flash` (Vertex), configurable via `MATCH_JUDGE_MODEL`.
|
||||
2. Confidence thresholds for cosmetic vs content vs ambiguous (start conservative; tune from telemetry).
|
||||
3. Whether to keep a tiny instant frontend normalizer for immediate display, or rely solely on the judge response (~sub-second). Lean: rely on judge for v1; add instant normalize later if the delay is noticeable.
|
||||
|
||||
## Rollout
|
||||
|
||||
- `MATCH_JUDGE_ENABLED` env flag (default on) so the AI layer can be disabled without a deploy; deterministic+catalog still function if AI is off.
|
||||
- Bump `pyproject.toml` version. Ship behind normal CI; Andrew reviews locally (localhost:3000 → prod backend) before merge/deploy.
|
||||
@@ -0,0 +1,98 @@
|
||||
# White-Label Tenant Portals: Made Working End-to-End (Jun 2026)
|
||||
|
||||
## Context
|
||||
|
||||
The two B2B white-label tenant portals (`vocalstar.nomadkaraoke.com`, `singa.nomadkaraoke.com`)
|
||||
had full data models, middleware, GCS config, themes, a simplified job form, a separate
|
||||
Cloudflare deployment, and 280+ unit tests — and were documented as "production ready."
|
||||
**But no tenant job had ever actually completed:** 0 of the 484 most recent prod jobs
|
||||
carried a `tenant_id`. The feature looked done but was broken at every stage that had
|
||||
never been exercised by a real end-to-end tenant job.
|
||||
|
||||
This session drove a real Vocal Star track (`Eddy Grant - I Don't Wanna Dance`, from their
|
||||
bulk batch) through the full pipeline in production, fixing each blocker in turn, until a
|
||||
tenant job completed: correct attribution → transcription → screens → review → render →
|
||||
Dropbox delivery, with the locked theme and **no** YouTube / Google Drive.
|
||||
|
||||
## The seven blockers (each was the next never-exercised stage)
|
||||
|
||||
1. **Tenant attribution never happened (root cause).** The frontend API client never sent
|
||||
the `X-Tenant-ID` header (`getTenantHeaders()` existed but was unwired). Tenant portals
|
||||
call the shared `api.nomadkaraoke.com`, whose Host isn't the tenant subdomain, and the
|
||||
`?tenant=` param is prod-disabled — so the backend never detected the tenant and every
|
||||
sign-in/job silently became a consumer job. Fix: attach `X-Tenant-ID` from
|
||||
`window.__TENANT_CONFIG__` in `lib/api.ts` (`getBaseHeaders`), incl. the magic-link
|
||||
request. PR #824.
|
||||
|
||||
2. **Tenant config not authoritative.** Prod sets global `DEFAULT_DROPBOX_PATH` /
|
||||
`DEFAULT_GDRIVE_FOLDER_ID` / `DEFAULT_BRAND_PREFIX`; `_apply_tenant_overrides` only
|
||||
filled unset fields, so tenant jobs leaked into the shared consumer Dropbox folder and
|
||||
uploaded to the global Google Drive. Fix: tenant config is authoritative, gated by
|
||||
feature flags (gdrive/dropbox cleared when disabled). PR #824.
|
||||
|
||||
3. **Wrong file transcribed.** existing-instrumental jobs upload mixed + instrumental into
|
||||
the same `uploads/{job}/audio/` dir; `uploads-complete` resolved the `audio` slot via
|
||||
`files[0]`, which sorts to `existing_instrumental.mp3`. Transcription ran on the
|
||||
instrumental. Fix: `_select_mixed_audio_files` excludes the instrumental. PR #825.
|
||||
|
||||
4. **AudioShake rejected the audio.** Vocal Star's MP3s begin with ~731 leading null bytes
|
||||
before the first frame; ffmpeg tolerates it, AudioShake 400s ("Error fetching or
|
||||
processing asset"). Consumer jobs never hit this (they transcribe re-encoded stems).
|
||||
Fix: detect leading null padding on `.mp3/.aac` and losslessly remux (`ffmpeg -c copy`)
|
||||
before upload. Verified against the live AudioShake API. PR #826.
|
||||
|
||||
5. **Theme incomplete.** The strict theme validator requires every field; the tenant
|
||||
themes (created Jan 2026) were missing `extra_text_text_transform` (intro + end),
|
||||
added to the schema later → "Title screen generation failed." Fix: added the field to
|
||||
the live GCS themes and the setup scripts. PR #827.
|
||||
|
||||
6. **Theme assets not downloaded.** The setup scripts wrote full `gs://bucket/themes/.../assets/X`
|
||||
URLs, but `theme_service._build_style_assets_mapping` only resolves bare basenames (the
|
||||
consumer convention) → `style_assets` empty → assets never localized → encoder failed
|
||||
with "Video background image not found". Fix: rewrote the live themes + setup scripts to
|
||||
bare basenames. PR #827.
|
||||
|
||||
7. **Render prerequisites — "No instrumental selected".** existing-instrumental jobs have
|
||||
no instrumental-selection UI step; the orchestrator defaults to `'clean'` (a stem never
|
||||
produced) and `_validate_prerequisites` rejected the job. Fix: `complete-review`
|
||||
defaults `instrumental_selection` to `'custom'` when `existing_instrumental_gcs_path`
|
||||
is set. PR #827.
|
||||
|
||||
## Tenant config (final, both tenants)
|
||||
|
||||
- Locked theme (`vocalstar` / `singa`), no theme selection.
|
||||
- `youtube_upload=false`, `gdrive_upload=false` (folder cleared), `dropbox_upload=true`.
|
||||
- Dropbox: `/MediaUnsynced/Karaoke/Tracks-VocalStar`, `/MediaUnsynced/Karaoke/Tracks-Singa`.
|
||||
- Jobs forced `is_private=true`; CDG + 4K enabled.
|
||||
|
||||
## Daily E2E
|
||||
|
||||
`scripts/e2e/tenant_e2e.py` + `.github/workflows/e2e-tenant-daily.yml` run a full job per
|
||||
tenant daily (07:37 UTC, matrix vocalstar/singa): submit → approve review → render →
|
||||
assert (completes, Dropbox link present, no YouTube, downloads available) → clean up the
|
||||
job + uploads. Auth via WIF + `E2E_ADMIN_TOKEN`; test audio in `gs://.../e2e-tests/shared/`.
|
||||
|
||||
## Outcome
|
||||
|
||||
Both tenants pass the full prod E2E (PRs #824–#830): log in → submit (artist, title, mixed,
|
||||
instrumental) → transcribe → review → render with the locked theme → encode → package →
|
||||
Dropbox delivery, with **no YouTube, no Google Drive**, and all outputs (4K / 720p /
|
||||
with-vocals MP4 + CDG + TXT) downloadable from the portal via `job.file_urls`.
|
||||
|
||||
The encoder blocker (bug #8) took three iterations: the staging had to land in the
|
||||
**orchestrator** path (`video_worker_orchestrator._run_encoding`, not the legacy
|
||||
`_encode_via_gce`) and use the filename the running encoder VM's `custom` branch globs for
|
||||
(`custom_instrumental.<ext>`, since the live VM boots the 2026-01-23 image whose `custom`
|
||||
branch predates `*existing_instrumental*` / `*Instrumental User*`). The instrumental is
|
||||
server-side-copied from `uploads/{job}/audio/existing_instrumental.*` →
|
||||
`jobs/{job}/custom_instrumental.<ext>`.
|
||||
|
||||
## Gotchas / lessons
|
||||
|
||||
- The tenant pipeline had never run end-to-end, so every stage hid a latent bug. "Has a
|
||||
real job of this shape ever completed in prod?" is a better readiness question than test
|
||||
count.
|
||||
- Theme asset paths must be **bare basenames** (consumer convention), not `gs://` URLs.
|
||||
- AudioShake needs clean audio at offset 0; user-provided files vary — remux defensively.
|
||||
- Public tenant config API redacts `dropbox_path`/`gdrive_folder_id`/`brand_prefix`; read
|
||||
the stored GCS config for the real values.
|
||||
@@ -0,0 +1,106 @@
|
||||
# Match-Judge Improvements — Implementation Plan
|
||||
|
||||
**Date:** 2026-06-16
|
||||
**Worktree:** `karaoke-gen-match-judge-improvements`
|
||||
**Branch:** `feat/sess-20260616-0053-match-judge-improvements`
|
||||
**Builds on:** match-judge v0.184.1 (PRs #836 + #838)
|
||||
**Spec:** `docs/archive/2026-06-16-match-judge-improvements-prompt.md` (decisions by Andrew — settled)
|
||||
|
||||
Four items. Decisions are already made in the prompt; this doc records the concrete
|
||||
shapes I'm committing to and the test plan. TDD throughout.
|
||||
|
||||
---
|
||||
|
||||
## Item 1 — Race fix: parallel tidy + hard gate
|
||||
|
||||
**Backend shape (decided: two-call `stage` contract).** Add `stage: "fast" | "full"`
|
||||
to the endpoint + `judge_match`. Default `"full"` (backwards-compatible).
|
||||
|
||||
- `stage="fast"` (no tier needed): run catalog search + `classify_catalog_match` ONLY.
|
||||
Never calls AI.
|
||||
- confident catalog verdict (cosmetic/none) → return it (`needs_ai=False`).
|
||||
- catalog undecided → return `MatchVerdict(none, confident=False, engine="catalog",
|
||||
reason="needs ai", needs_ai=True)`.
|
||||
- `stage="full"` (tier known): current pipeline + Item 4 (see below).
|
||||
|
||||
New field `needs_ai: bool = False` on `MatchVerdict` (+ `to_dict`, response model, TS type).
|
||||
|
||||
**Frontend two-phase coordination (AudioSourceStep):**
|
||||
1. On mount (parallel with audio search): `matchJudge(artist, title, { stage: 'fast' })`.
|
||||
Store the promise in a ref. If it resolves to a confident cosmetic verdict, apply the
|
||||
silent tidy immediately (no re-search).
|
||||
2. When the audio search resolves (tier known), one coordinating effect:
|
||||
- `await` the fast promise.
|
||||
- `needFull = fast == null || fast.needs_ai || (fastIsCatalogConfident && tier >= 3)`.
|
||||
- if `needFull` → `matchJudge(artist, title, { stage: 'full', audioConfidenceTier: tier })`,
|
||||
apply its verdict.
|
||||
- settle the gate in a `finally` (always).
|
||||
|
||||
**Hard gate.** `gateReleased` state (starts false) → true when the judge settles.
|
||||
Pick/select buttons (PickCard, ResultRow) and the fallback submit buttons are disabled
|
||||
while `!gateReleased`. A subtle "Checking song details…" line shows when
|
||||
`!gateReleased && !isSearching`. Safety timeout `JUDGE_GATE_TIMEOUT_MS = 12000` from when
|
||||
the full call fires guarantees release even on a network hang (backend AI already caps at
|
||||
12s). Gate never deadlocks: every path (disabled flag, fast/full failure, timeout) settles.
|
||||
|
||||
On a content re-search, keep the gate open (don't re-judge) — mirrors the existing
|
||||
`judgeTriggered` semantics.
|
||||
|
||||
**Acceptance:** impossible to reach Step 3 with un-tidied metadata in normal flow; a slow
|
||||
AI verdict never clobbers the selection; gate is imperceptible in cosmetic cases and bounded
|
||||
(≤12s) otherwise.
|
||||
|
||||
## Item 2 — Two-way toggle for tidy/correction (frontend only)
|
||||
|
||||
`MatchNotice` becomes a clean two-way toggle. Add `correctionActive` state (default true).
|
||||
- cosmetic applied: "Tidied to **X** · keep what I typed" → revert.
|
||||
- cosmetic reverted: "Using what you typed: **Y** · use tidied version" → reapply.
|
||||
- content applied: "Corrected to **X** — you typed “Y” · Undo" → revert.
|
||||
- content reverted: "Using what you typed: **Y** · use the correction" → reapply.
|
||||
|
||||
Toggle is metadata-only (no re-search on toggle — matches old Undo + the "no restart on
|
||||
cosmetic" rule). `appliedFrom` already holds the typed text; `verdict` holds canonical.
|
||||
|
||||
New i18n keys (translate all locales): `matchUsingTyped`, `matchUseTidied`,
|
||||
`matchUseCorrection`.
|
||||
|
||||
## Item 3 — Title-screen preview perf (frontend only)
|
||||
|
||||
`TitleCardPreview.tsx` + `KaraokeBackgroundPreview.tsx`:
|
||||
- Render canvas at **preview resolution** (960×540, dpr-aware, clamp dpr≤2) instead of
|
||||
3840×2160. Keep coordinate constants in 4K space; apply `ctx.setTransform(scale,…)` so
|
||||
drawing code is unchanged.
|
||||
- Add **low-res** bg assets: `public/title-card-bg-preview.png`,
|
||||
`public/karaoke-bg-preview.png` (downscaled from the 2.7 MB 4K originals). Previews use
|
||||
these; the 4K originals stay for any real render path.
|
||||
- **Preload** the preview bg(s) at Step 2 (export `preloadTitleCardBg()` /
|
||||
`preloadKaraokeBg()`, call from AudioSourceStep mount) so they're warm by Step 4.
|
||||
- **Spinner** "Loading title screen preview" overlay until the first draw completes
|
||||
(`ready` state).
|
||||
- Update `TitleCardPreview.test.tsx` mock (add `setTransform`/`scale`), add coverage for
|
||||
the spinner + low-res bg src.
|
||||
|
||||
## Item 4 — Catalog-match trust: verify weak matches with AI (backend)
|
||||
|
||||
In `judge_match` (stage=full): when `classify_catalog_match` returns a confident verdict
|
||||
BUT the audio tier is weak (`>= 3`), still call AI and let it override — catches a junk/
|
||||
misspelled Spotify entry matching the user's exact typo (prod: `Queen / Bohemian Rapsody`
|
||||
→ wrongly "already canonical"). AI overrides only when confident and `kind != none`;
|
||||
otherwise keep the catalog verdict. Extra ~$0.0003/call cost only on weak-result cases.
|
||||
|
||||
## Testing
|
||||
|
||||
- **Backend unit** (`test_service.py`): fast-stage returns catalog verdict / needs_ai;
|
||||
fast never calls AI; full-stage weak-tier catalog match → AI consulted → override;
|
||||
full-stage strong-tier catalog match → no AI; AI-unconfident on weak tier → keep catalog.
|
||||
- **Backend unit** (`test_classifier.py`): unchanged (still escalates on no match).
|
||||
- **Backend route** (`test_match_judge_routes.py`): `stage` forwarded; `needs_ai` in response.
|
||||
- **Frontend** (`AudioSourceStep.test.tsx`): fast call on mount; cosmetic applies from fast;
|
||||
gate disables pick button until settled then enables; full call fired only when needed;
|
||||
two-way toggle revert↔reapply.
|
||||
- **Frontend** (`TitleCardPreview.test.tsx`): preview-res canvas, low-res bg, spinner.
|
||||
- `make test` full suite green before `/shipit`.
|
||||
|
||||
## Out of scope / preserved
|
||||
No Step-1 autocomplete; cosmetic must not restart search; deferred job creation; public
|
||||
brand rule; audio-before-customize ordering. (Constraints from the 2026-06-15 doc.)
|
||||
@@ -0,0 +1,67 @@
|
||||
# Match-Judge Improvements — New-Session Prompt Doc
|
||||
|
||||
**Created:** 2026-06-16
|
||||
**For:** a fresh session, started via `/startnomad gen match-judge improvements`
|
||||
**Builds on:** the artist/title match-judge feature shipped in gen **v0.184.1** (PRs #836 + #838).
|
||||
|
||||
## Read first (context)
|
||||
|
||||
- Feature overview + gotchas: agent memory `project_match_judge.md` (and `[[project_match_judge]]`).
|
||||
- Original design + history constraints: `docs/archive/2026-06-15-artist-title-matching-rework-plan.md`.
|
||||
- **Honor the "Constraints from history" section of that plan** — no Step-1 autocomplete; cosmetic correction must not restart the audio search; deferred job-creation/search-session pattern; public-style brand rule; audio-before-customize ordering. Don't undo these.
|
||||
|
||||
### Where the code lives
|
||||
- Backend: `backend/services/match_judge/` — `classifier.py` (deterministic + catalog), `ai.py` (Vertex `gemini-3.5-flash`), `service.py` (orchestration), `verdict.py` (`MatchVerdict`). Endpoint: `POST /api/catalog/match-judge` in `backend/api/routes/catalog.py`. Config in `backend/config.py` (`MATCH_JUDGE_ENABLED` / `MATCH_JUDGE_MODEL` / `MATCH_JUDGE_TIMEOUT_MS=12000`).
|
||||
- Frontend: `frontend/components/job/steps/AudioSourceStep.tsx` — the judge effect, `applyCorrection`/`handleSuggestionAccept`/`handleUndoCorrection`, and the `MatchNotice` component. Client: `api.matchJudge` in `frontend/lib/api.ts`. i18n keys live in `frontend/messages/en.json` under `jobFlow` (`matchTidiedTo`, `matchKeepMine`, `matchCorrectedTo`, `matchUndo`, `matchDidYouMean`) — any new/changed strings must be translated to all 33 locales (`python scripts/translate.py --messages-dir ./messages --target all`).
|
||||
|
||||
### How it currently works (the starting point)
|
||||
On Step 2, the judge effect fires **after** the audio search resolves (`isSearching === false`), passing `confidence.tier`. The verdict drives `MatchNotice`: cosmetic → silent apply + quiet "Tidied to X · keep what I typed" (no re-search); confident content → apply + "Corrected to X · Undo", re-search only if tier 3; ambiguous → ask-first "Did you mean?". `applyCorrection(newArtist, newTitle, reSearch)` writes to the parent via `onArtistTitleCorrection` (no-restart path) and, when `reSearch`, resets `searchTriggered`/results so the mount effect re-runs.
|
||||
|
||||
---
|
||||
|
||||
## Work items (with decisions already made)
|
||||
|
||||
### 1. Race: audio results can arrive before the tidy finishes
|
||||
**Problem:** the judge runs *after* the audio search, so there's a window where results are shown but the tidy hasn't applied. If the user selects audio / advances fast, the un-tidied artist/title can be what's saved (job creation is deferred to Step 4, so it's usually caught, but not guaranteed). Worse: a `content`+reSearch verdict landing while the user is mid-selection can blow away results / a pick.
|
||||
|
||||
**Decision (Andrew):** **Tidy earlier (parallel) + a hard gate.**
|
||||
- Run the **deterministic + catalog** tidy **in parallel with the audio search** (kick it off on mount; it doesn't need the tier). The **AI** layer still needs the tier, so it runs once the audio search resolves — but only when deterministic+catalog aren't confident.
|
||||
- This likely means splitting the single `match-judge` call, OR adding a query param so the backend can do a fast catalog-only pass immediately and a full pass (with tier) after. Decide the cleanest shape — could be two calls (`/match-judge` cheap-first without tier, then a second with tier only if needed) or one call kicked off as soon as possible. Keep the backend contract clean.
|
||||
- **Hard-gate selection:** disable "Use This Audio" (all audio pick buttons) with a subtle indicator (e.g. "Checking song details…") until **both** the audio search **and** the judge verdict have resolved + applied. The judge's 12s timeout must still unlock the gate (never strand the user). Because the tidy runs in parallel, the common cosmetic case adds ~no perceptible wait; only the rarer AI path holds the gate briefly.
|
||||
- Gate releases when the verdict reaches a terminal state (cosmetic applied / content applied / ambiguous prompt shown / none / timeout). For **ambiguous**, release the gate (don't block indefinitely on an unsure result) but keep the "Did you mean?" prompt visible.
|
||||
|
||||
**Acceptance:** it is impossible to reach Step 3 with un-tidied metadata in the normal flow; a slow AI verdict never clobbers a selection; the gate is imperceptible for cosmetic cases and bounded (≤12s) otherwise.
|
||||
|
||||
### 2. Make "keep what I typed" reversible (two-way toggle)
|
||||
**Decision (Andrew):** the tidy notice should let the user **see what it would revert to**, and **switch back** to the tidied version if they change their mind.
|
||||
- Show both values. e.g. tidied state: *"Tidied to **Hard-Fi — I Shall Overcome** · keep what I typed"*. After clicking, reverted state: *"Using what you typed: **hard-fi - i shall overcome** · use tidied version"*, and "use tidied version" switches back. A clean two-way toggle; current value always clear.
|
||||
- Same for the **content** correction ("Corrected to X · Undo") — Undo should be reversible back to the correction too.
|
||||
- This is just frontend `MatchNotice` + state (`appliedFrom` already tracks the pre-correction text; add the inverse). New i18n keys as needed (translate all 33 locales).
|
||||
|
||||
### 3. Title-screen preview performance (the original "point D")
|
||||
`frontend/components/job/TitleCardPreview.tsx` renders a **3840×2160 (4K) canvas** and loads a **4K** background PNG (`/title-card-bg.png`) — for what's shown as a small thumbnail. Slow, especially on mobile.
|
||||
- Render the canvas at **display resolution** (e.g. ~960×540, or `devicePixelRatio`-aware), not 4K.
|
||||
- Add a **low-res** background asset (downscale `public/title-card-bg.png`) and use it for the preview; keep the 4K for any real render path.
|
||||
- **Preload** the background once the artist/title are locked at Step 2 (the preview currently lives on Step 4), so it's warm by the time the user arrives.
|
||||
- Add a **"Loading title screen preview"** spinner while it renders.
|
||||
- Note: private mode has a second canvas (`KaraokeBackgroundPreview.tsx`) — apply the same treatment. There's a `TitleCardPreview.test.tsx`; update it.
|
||||
|
||||
### 4. Catalog-match trust (the "second point" — yes, it's a real bug)
|
||||
**Problem:** the classifier's exact catalog match can match a junk / misspelled Spotify entry (e.g. a karaoke/lyric upload titled with the user's exact typo), so it returns `none`/"already canonical" and **the AI judge never runs**. Observed in prod: `Queen / Bohemian Rapsody` → "already canonical" (wrong).
|
||||
**Decision (Andrew):** **Verify weak matches with AI.** When the audio results were weak (**tier 3**), run the AI judge **even if the catalog "matched"**, and let the AI override the catalog verdict. The extra cost (~$0.0003/call) is only incurred on weak-result cases. Implement in `service.py` (don't let `classify_catalog_match` short-circuit when tier is weak) and/or `classifier.py`. Add unit tests covering: weak tier + junk exact-match → AI consulted → corrected; strong tier + exact-match → still short-circuits (no AI).
|
||||
|
||||
---
|
||||
|
||||
## Process
|
||||
|
||||
1. `/startnomad gen match-judge improvements`, read the context docs above.
|
||||
2. Brainstorm/confirm the parallel-tidy backend shape (item 1) before coding — it's the trickiest. Consider visual mockups only if helpful; the decisions above are settled, so keep it light.
|
||||
3. TDD: backend changes get unit/integration tests; frontend changes get Jest tests (mirror the existing `AudioSourceStep.test.tsx` / `TitleCardPreview.test.tsx` patterns). Update i18n for all 33 locales when strings change.
|
||||
4. Run `make test` (full suite), then `/shipit` (CodeRabbit → version bump → PR with `@coderabbitai ignore` → merge → wait for deploy → verify prod). **Verify item 1 and item 4 live in prod** with real `/api/catalog/match-judge` calls and by clicking through Step 2 on localhost:3000 (dev server proxies to prod backend by default).
|
||||
5. After shipping, trigger the daily prod E2E workflow: `gh workflow run e2e-daily.yml --ref main`.
|
||||
|
||||
## Notes / gotchas
|
||||
- The shell/rtk wrapper mangles `&&`, `2>&1`, and reformats `gh --json -q` output — use `;`-separated commands and `rtk proxy gh …` for raw JSON.
|
||||
- `gh pr merge --delete-branch` errors locally because `main` is checked out in the main clone worktree; the remote merge still succeeds — verify with `gh pr view <n> --json state`.
|
||||
- CI dedupes test jobs on merge and goes straight to "Deploy - Backend (Cloud Run)"; the definitive deploy signal is the prod root version (`https://api.nomadkaraoke.com/`) flipping to the new value.
|
||||
- Admin token for prod API tests: `gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke | cut -d',' -f1`, send as `Authorization: Bearer <token>`.
|
||||
@@ -0,0 +1,83 @@
|
||||
# Render status-poll pinning — fix for deploy-swap orphaning (job d3af33ae)
|
||||
|
||||
**Date:** 2026-06-16
|
||||
**Worktree:** `karaoke-gen-encoding-job-not-found`
|
||||
**Incident error:** `Encoding job <ID> lost contact with worker after 5 consecutive poll failures: Encoding job <ID> not found`
|
||||
|
||||
## What happened (job d3af33ae, 2026-06-16 UTC)
|
||||
|
||||
| Time | Event |
|
||||
|------|-------|
|
||||
| 04:29:09 | `karaoke-backend@` starts **worker-a** (`34.57.78.246`) — render warmup |
|
||||
| ~04:31:39 | Render submitted to **worker-a**; encoding begins |
|
||||
| 04:33:01 | `github-actions-deployer@` starts **worker-b** (`34.10.189.118`) — deploy begins |
|
||||
| **04:33:46.985** | Firestore `last_swap_at`: primary swapped worker-a → **worker-b** |
|
||||
| 04:33:53 → 04:34:33 | Backend status polls fail 1/5 → 5/5: "Encoding job d3af33ae not found" |
|
||||
| 04:34:33 | Render failed; deploy stops worker-a |
|
||||
| 04:46:35 | User retried → re-rendered on worker-b → **success** |
|
||||
|
||||
The 4 polls that failed at 04:33:53–04:34:23 happened **while worker-a was still running and encoding**. The 404s came from worker-b (the just-swapped primary), which never received the job.
|
||||
|
||||
## Root cause
|
||||
|
||||
`EncodingService.get_job_status()` resolves the worker URL **fresh on every poll** via
|
||||
`_get_worker_url()` → `config.active_url`. When a blue-green deploy flips `primary_vm` in
|
||||
Firestore mid-render, in-flight status polls migrate from the worker that owns the job
|
||||
(old primary) to the new primary, which 404s. A clean 404 is counted as a transient poll
|
||||
failure; 5 in a row fails the render — even though the original worker finished the encode.
|
||||
|
||||
URL re-resolution is **correct for capacity fallback** (primary VM dead → start fallback →
|
||||
re-route), but **wrong for a deploy swap** (old primary alive, still owns the job).
|
||||
|
||||
The drain logic added 2026-06-15 (`ci.yml` "Drain and stop old primary") prevents *stopping*
|
||||
a busy VM, but the job is orphaned at the **poll layer** the instant the pointer swaps —
|
||||
47s before the VM is stopped. The drain can't fix this.
|
||||
|
||||
## Fix: pin in-flight polls to the worker that accepted the job
|
||||
|
||||
Invariant: **once a job is accepted by a worker VM, all status polls for that job target
|
||||
that same VM until terminal** — the poll follows the job, not the floating primary pointer.
|
||||
|
||||
### Changes (`backend/services/encoding_service.py`)
|
||||
|
||||
1. **`_request_with_retry(..., allow_failover: bool = True)`** — gate the warmup-on-failure
|
||||
block and the post-warmup URL re-resolution on `allow_failover`. Default `True` keeps all
|
||||
existing submit callers (and capacity fallback) unchanged.
|
||||
|
||||
2. **`get_job_status(job_id, worker_url: Optional[str] = None)`** — when `worker_url` is given,
|
||||
poll `f"{worker_url}/status/{job_id}"` with `allow_failover=False` (a pinned poll must never
|
||||
re-resolve to active_url nor spin up a fallback VM — a fresh VM can't have the job). When
|
||||
omitted, behave exactly as today.
|
||||
|
||||
3. **`wait_for_completion(..., worker_url: Optional[str] = None)`** — thread `worker_url` into
|
||||
`get_job_status`. Consecutive-failure tolerance unchanged (still rides out a brief restart of
|
||||
the *pinned* worker). A pinned 404 is now the *true* "owning worker lost the job" signal.
|
||||
|
||||
4. **`encode_videos` / `render_video_on_gce` / `encode_preview_video`** — capture
|
||||
`pinned_url = self._get_worker_url()` **after** submit returns, and pass it as `worker_url=`
|
||||
to `wait_for_completion`. Capturing post-submit reflects a capacity-fallback re-route during
|
||||
submit (warmup invalidates the cache, so `_get_worker_url()` returns the fallback URL) while
|
||||
being *before* any later deploy swap.
|
||||
|
||||
### Why post-submit capture (not the submit return value)
|
||||
|
||||
A capacity-fallback during submit updates `active_override` + invalidates the URL cache, so the
|
||||
*next* `_get_worker_url()` already returns the worker the job actually landed on. This avoids
|
||||
threading the URL back through three `submit_*` return contracts.
|
||||
|
||||
## Tests (TDD — `backend/tests/test_encoding_service.py`)
|
||||
|
||||
- `get_job_status` targets the pinned URL over active_url, with `allow_failover=False`.
|
||||
- `get_job_status` without a pin still uses active_url (regression).
|
||||
- `wait_for_completion` threads `worker_url` into each poll.
|
||||
- `_request_with_retry` does **not** warm up / re-resolve when `allow_failover=False`.
|
||||
- **End-to-end:** `render_video_on_gce` keeps polling the submission worker even when
|
||||
`active_url` has swapped to a worker that 404s — would fail before the fix, passes after.
|
||||
- Update the 3 existing `wait_for_completion` tolerance mocks to accept `worker_url=None`.
|
||||
|
||||
## Scope notes / non-goals
|
||||
|
||||
- The single `get_job_status` call inside the `submit_*` 409-conflict handler stays unpinned
|
||||
(rare two-request-same-job-during-swap edge); the main poll loop is pinned via the convenience
|
||||
methods, which covers the join case.
|
||||
- No change to the CI drain logic — it remains the correct guard for *stopping* a busy VM.
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* @jest-environment jsdom
|
||||
*
|
||||
* Tests that the API client attaches the X-Tenant-ID header on white-label tenant
|
||||
* portals (sourced from window.__TENANT_CONFIG__) and omits it on the consumer build.
|
||||
*
|
||||
* Regression guard for the root-cause bug: the frontend never sent X-Tenant-ID, so the
|
||||
* shared api.nomadkaraoke.com backend could not detect the tenant and every tenant-portal
|
||||
* job/sign-in silently fell back to consumer behavior (0 tenant jobs ever ran in prod).
|
||||
*/
|
||||
|
||||
import { api, getTenantId } from '@/lib/api'
|
||||
|
||||
function setEdgeTenant(id: string | null) {
|
||||
if (id) {
|
||||
;(window as any).__TENANT_CONFIG__ = {
|
||||
tenant: { id, name: id, subdomain: `${id}.nomadkaraoke.com` },
|
||||
is_default: false,
|
||||
}
|
||||
} else {
|
||||
delete (window as any).__TENANT_CONFIG__
|
||||
}
|
||||
}
|
||||
|
||||
describe('getTenantId', () => {
|
||||
afterEach(() => setEdgeTenant(null))
|
||||
|
||||
it('returns null when no tenant config is present (consumer build)', () => {
|
||||
setEdgeTenant(null)
|
||||
expect(getTenantId()).toBeNull()
|
||||
})
|
||||
|
||||
it('returns the tenant id from window.__TENANT_CONFIG__', () => {
|
||||
setEdgeTenant('vocalstar')
|
||||
expect(getTenantId()).toBe('vocalstar')
|
||||
})
|
||||
|
||||
it('returns null when the injected config has no tenant (default/consumer domain)', () => {
|
||||
;(window as any).__TENANT_CONFIG__ = { tenant: null, is_default: true }
|
||||
expect(getTenantId()).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('X-Tenant-ID header attachment', () => {
|
||||
const fetchMock = jest.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
fetchMock.mockReset()
|
||||
;(global as any).fetch = fetchMock
|
||||
fetchMock.mockResolvedValue({ ok: true, json: async () => ({}) })
|
||||
})
|
||||
|
||||
afterEach(() => setEdgeTenant(null))
|
||||
|
||||
it('attaches X-Tenant-ID to authenticated requests (createJobWithUploadUrls) on a tenant portal', async () => {
|
||||
setEdgeTenant('vocalstar')
|
||||
window.localStorage.setItem('karaoke_access_token', 'tok-123')
|
||||
|
||||
fetchMock.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ job_id: 'j1', upload_urls: [] }),
|
||||
})
|
||||
|
||||
await api.createJobWithUploadUrls('Adele', 'Hello', [], {
|
||||
is_private: true,
|
||||
existing_instrumental: true,
|
||||
})
|
||||
|
||||
const [, init] = fetchMock.mock.calls[0]
|
||||
expect(init.headers['X-Tenant-ID']).toBe('vocalstar')
|
||||
expect(init.headers['Authorization']).toBe('Bearer tok-123')
|
||||
|
||||
window.localStorage.removeItem('karaoke_access_token')
|
||||
})
|
||||
|
||||
it('attaches X-Tenant-ID to the magic-link request on a tenant portal', async () => {
|
||||
setEdgeTenant('singa')
|
||||
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ success: true }) })
|
||||
|
||||
await api.sendMagicLink('user@singa.com')
|
||||
|
||||
const [url, init] = fetchMock.mock.calls[0]
|
||||
expect(url).toMatch(/\/api\/users\/auth\/magic-link$/)
|
||||
expect(init.headers['X-Tenant-ID']).toBe('singa')
|
||||
})
|
||||
|
||||
it('does NOT attach X-Tenant-ID on the consumer build', async () => {
|
||||
setEdgeTenant(null)
|
||||
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ success: true }) })
|
||||
|
||||
await api.sendMagicLink('user@example.com')
|
||||
|
||||
const [, init] = fetchMock.mock.calls[0]
|
||||
expect(init.headers['X-Tenant-ID']).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -20,6 +20,8 @@ import {
|
||||
SkipForward,
|
||||
Volume2,
|
||||
VolumeX,
|
||||
TrendingUp,
|
||||
TrendingDown,
|
||||
Upload,
|
||||
Check,
|
||||
ChevronDown,
|
||||
@@ -382,6 +384,12 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
? (audioInfo?.original_duration_seconds ?? 0)
|
||||
: (audioInfo?.current_duration_seconds ?? 0)
|
||||
|
||||
// Trim/Fade are edge actions — only valid when the selection touches the
|
||||
// very start or very end of the track (1s tolerance, matching the
|
||||
// server-side anchoring in audio_edit_service.fade_region).
|
||||
const atStartEdge = !!selection && selection.startSeconds < 1
|
||||
const atEndEdge = !!selection && selection.endSeconds > currentDuration - 1
|
||||
|
||||
// ─── Auto-save ─────────────────────────────────────────────────
|
||||
|
||||
const { saveSession } = useAudioEditAutoSave({
|
||||
@@ -614,6 +622,22 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
})
|
||||
}
|
||||
|
||||
function handleFadeIn() {
|
||||
if (!selection) return
|
||||
handleApply("fade_in", {
|
||||
start_seconds: selection.startSeconds,
|
||||
end_seconds: selection.endSeconds,
|
||||
})
|
||||
}
|
||||
|
||||
function handleFadeOut() {
|
||||
if (!selection) return
|
||||
handleApply("fade_out", {
|
||||
start_seconds: selection.startSeconds,
|
||||
end_seconds: selection.endSeconds,
|
||||
})
|
||||
}
|
||||
|
||||
// ─── Join (upload) ─────────────────────────────────────────────
|
||||
|
||||
const [showJoinDialog, setShowJoinDialog] = useState(false)
|
||||
@@ -866,28 +890,52 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
{formatTimePrecise(selection.startSeconds)} - {formatTimePrecise(selection.endSeconds)}
|
||||
({formatTimePrecise(selection.endSeconds - selection.startSeconds)})
|
||||
</span>
|
||||
{selection.startSeconds < 1 && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={isOperating}
|
||||
onClick={handleTrimStart}
|
||||
className="text-xs h-7"
|
||||
>
|
||||
{t('trimStart')}
|
||||
</Button>
|
||||
)}
|
||||
{selection.endSeconds > currentDuration - 1 && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={isOperating}
|
||||
onClick={handleTrimEnd}
|
||||
className="text-xs h-7"
|
||||
>
|
||||
{t('trimEnd')}
|
||||
</Button>
|
||||
)}
|
||||
{/* Trim/Fade are edge actions: enabled only when the selection
|
||||
touches the very start (start) or very end (end) of the track.
|
||||
Always rendered (disabled off-edge) so the actions stay
|
||||
discoverable, with a tooltip explaining how to enable them. */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={isOperating || !atStartEdge}
|
||||
onClick={handleTrimStart}
|
||||
className="text-xs h-7"
|
||||
title={atStartEdge ? t('trimStartSelection') : t('trimStartDisabledHint')}
|
||||
>
|
||||
{t('trimStart')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={isOperating || !atStartEdge}
|
||||
onClick={handleFadeIn}
|
||||
className="text-xs h-7"
|
||||
title={atStartEdge ? t('fadeInSelection') : t('fadeInDisabledHint')}
|
||||
>
|
||||
<TrendingUp className="w-3 h-3 mr-1" />
|
||||
{t('fadeIn')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={isOperating || !atEndEdge}
|
||||
onClick={handleTrimEnd}
|
||||
className="text-xs h-7"
|
||||
title={atEndEdge ? t('trimEndSelection') : t('trimEndDisabledHint')}
|
||||
>
|
||||
{t('trimEnd')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={isOperating || !atEndEdge}
|
||||
onClick={handleFadeOut}
|
||||
className="text-xs h-7"
|
||||
title={atEndEdge ? t('fadeOutSelection') : t('fadeOutDisabledHint')}
|
||||
>
|
||||
<TrendingDown className="w-3 h-3 mr-1" />
|
||||
{t('fadeOut')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
|
||||
@@ -327,6 +327,100 @@ describe("AudioEditor", () => {
|
||||
})
|
||||
})
|
||||
|
||||
it("shows Fade In button and applies fade_in for a start-anchored selection", async () => {
|
||||
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
|
||||
mockApi.applyAudioEdit.mockResolvedValue({ ...mockEditResponse, operation: "fade_in" })
|
||||
|
||||
render(<AudioEditor job={mockJob} />)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Audio Editor")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
const canvas = document.querySelector("canvas") as HTMLCanvasElement
|
||||
jest.spyOn(canvas, "getBoundingClientRect").mockReturnValue({
|
||||
left: 0, top: 0, right: 1000, bottom: 140, width: 1000, height: 140, x: 0, y: 0,
|
||||
toJSON: () => ({}),
|
||||
} as DOMRect)
|
||||
|
||||
// Drag from the very start to ~6s (duration 200, width 1000 → 6s ≈ 30px)
|
||||
fireEvent.mouseDown(canvas, { clientX: 0 })
|
||||
fireEvent.mouseMove(canvas, { clientX: 30 })
|
||||
fireEvent.mouseUp(canvas, { clientX: 30 })
|
||||
|
||||
const fadeInButton = await screen.findByText("Fade In")
|
||||
fireEvent.click(fadeInButton)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockApi.applyAudioEdit).toHaveBeenCalledWith(
|
||||
"test-job-123",
|
||||
"fade_in",
|
||||
expect.objectContaining({ start_seconds: 0 }),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it("shows Fade Out button and applies fade_out for an end-anchored selection", async () => {
|
||||
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
|
||||
mockApi.applyAudioEdit.mockResolvedValue({ ...mockEditResponse, operation: "fade_out" })
|
||||
|
||||
render(<AudioEditor job={mockJob} />)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Audio Editor")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
const canvas = document.querySelector("canvas") as HTMLCanvasElement
|
||||
jest.spyOn(canvas, "getBoundingClientRect").mockReturnValue({
|
||||
left: 0, top: 0, right: 1000, bottom: 140, width: 1000, height: 140, x: 0, y: 0,
|
||||
toJSON: () => ({}),
|
||||
} as DOMRect)
|
||||
|
||||
// Drag from ~194s to the end (duration 200, width 1000 → 194s ≈ 970px, end ≈ 1000px)
|
||||
fireEvent.mouseDown(canvas, { clientX: 970 })
|
||||
fireEvent.mouseMove(canvas, { clientX: 1000 })
|
||||
fireEvent.mouseUp(canvas, { clientX: 1000 })
|
||||
|
||||
const fadeOutButton = await screen.findByText("Fade Out")
|
||||
fireEvent.click(fadeOutButton)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockApi.applyAudioEdit).toHaveBeenCalledWith(
|
||||
"test-job-123",
|
||||
"fade_out",
|
||||
expect.objectContaining({ end_seconds: 200 }),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it("renders Trim/Fade buttons disabled for a mid-track selection", async () => {
|
||||
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
|
||||
|
||||
render(<AudioEditor job={mockJob} />)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Audio Editor")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
const canvas = document.querySelector("canvas") as HTMLCanvasElement
|
||||
jest.spyOn(canvas, "getBoundingClientRect").mockReturnValue({
|
||||
left: 0, top: 0, right: 1000, bottom: 140, width: 1000, height: 140, x: 0, y: 0,
|
||||
toJSON: () => ({}),
|
||||
} as DOMRect)
|
||||
|
||||
// Drag a mid-track region (duration 200, width 1000 → 100px≈20s, 300px≈60s)
|
||||
fireEvent.mouseDown(canvas, { clientX: 100 })
|
||||
fireEvent.mouseMove(canvas, { clientX: 300 })
|
||||
fireEvent.mouseUp(canvas, { clientX: 300 })
|
||||
|
||||
// Buttons stay visible (discoverable) but disabled off-edge
|
||||
const fadeIn = (await screen.findByText("Fade In")).closest("button")
|
||||
const fadeOut = screen.getByText("Fade Out").closest("button")
|
||||
const trimStart = screen.getByText("Trim Start").closest("button")
|
||||
const trimEnd = screen.getByText("Trim End").closest("button")
|
||||
expect(fadeIn).toBeDisabled()
|
||||
expect(fadeOut).toBeDisabled()
|
||||
expect(trimStart).toBeDisabled()
|
||||
expect(trimEnd).toBeDisabled()
|
||||
})
|
||||
|
||||
it("shows playback controls", async () => {
|
||||
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
|
||||
render(<AudioEditor job={mockJob} />)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
"use client"
|
||||
|
||||
import { useRef, useEffect, useCallback } from "react"
|
||||
import { useRef, useEffect, useState, useCallback } from "react"
|
||||
import { useTranslations } from "next-intl"
|
||||
import { Loader2 } from "lucide-react"
|
||||
|
||||
interface KaraokeBackgroundPreviewProps {
|
||||
backgroundUrl?: string // Object URL from File, or undefined for solid color
|
||||
@@ -9,9 +11,25 @@ interface KaraokeBackgroundPreviewProps {
|
||||
unsungColor?: string // Color for unsung lyrics
|
||||
}
|
||||
|
||||
// 4K coordinate space (the sample lyrics are laid out in it); the canvas renders at
|
||||
// the much smaller preview resolution below via a scale transform.
|
||||
const CANVAS_W = 3840
|
||||
const CANVAS_H = 2160
|
||||
|
||||
const PREVIEW_W = 960
|
||||
const PREVIEW_H = 540
|
||||
const MAX_DPR = 2
|
||||
|
||||
// Low-res background for the preview (the 4K asset stays for the real render path).
|
||||
const KARAOKE_BG_SRC = "/karaoke-bg-preview.png"
|
||||
|
||||
/** Warm the karaoke background cache ahead of time (e.g. on Step 2). */
|
||||
export function preloadKaraokeBg(): void {
|
||||
if (typeof window === "undefined") return
|
||||
const img = new Image()
|
||||
img.src = KARAOKE_BG_SRC
|
||||
}
|
||||
|
||||
// 4 sample lines to match real karaoke video rendering
|
||||
const SAMPLE_LINES = [
|
||||
"Don't say that you don't understand",
|
||||
@@ -30,7 +48,9 @@ export function KaraokeBackgroundPreview({
|
||||
sungColor,
|
||||
unsungColor,
|
||||
}: KaraokeBackgroundPreviewProps) {
|
||||
const t = useTranslations("karaokeBackgroundPreview")
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
const [ready, setReady] = useState(false)
|
||||
|
||||
const effectiveSungColor = sungColor || DEFAULT_SUNG_COLOR
|
||||
const effectiveUnsungColor = unsungColor || DEFAULT_UNSUNG_COLOR
|
||||
@@ -38,11 +58,21 @@ export function KaraokeBackgroundPreview({
|
||||
const draw = useCallback(async () => {
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas) return
|
||||
|
||||
// Size the backing store to the preview resolution (dpr-aware, capped) and
|
||||
// scale the 4K coordinate space down to it.
|
||||
const dpr = Math.min((typeof window !== "undefined" && window.devicePixelRatio) || 1, MAX_DPR)
|
||||
const cw = Math.round(PREVIEW_W * dpr)
|
||||
const ch = Math.round(PREVIEW_H * dpr)
|
||||
if (canvas.width !== cw) canvas.width = cw
|
||||
if (canvas.height !== ch) canvas.height = ch
|
||||
|
||||
const ctx = canvas.getContext("2d")
|
||||
if (!ctx) return
|
||||
ctx.setTransform(cw / CANVAS_W, 0, 0, ch / CANVAS_H, 0, 0)
|
||||
|
||||
// Draw background: custom image > solid color > default Nomad theme image
|
||||
const bgSrc = backgroundUrl || (backgroundColor ? null : "/karaoke-bg.png")
|
||||
const bgSrc = backgroundUrl || (backgroundColor ? null : KARAOKE_BG_SRC)
|
||||
if (bgSrc) {
|
||||
try {
|
||||
const img = await new Promise<HTMLImageElement>((resolve, reject) => {
|
||||
@@ -116,6 +146,8 @@ export function KaraokeBackgroundPreview({
|
||||
ctx.fillText(line, centerX, y)
|
||||
}
|
||||
})
|
||||
|
||||
setReady(true)
|
||||
}, [backgroundUrl, backgroundColor, effectiveSungColor, effectiveUnsungColor])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -123,15 +155,26 @@ export function KaraokeBackgroundPreview({
|
||||
}, [draw])
|
||||
|
||||
return (
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
width={CANVAS_W}
|
||||
height={CANVAS_H}
|
||||
className="w-full rounded-lg"
|
||||
style={{
|
||||
aspectRatio: "16/9",
|
||||
border: "1px solid var(--card-border)",
|
||||
}}
|
||||
/>
|
||||
<div className="relative w-full" style={{ aspectRatio: "16/9" }}>
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
width={PREVIEW_W}
|
||||
height={PREVIEW_H}
|
||||
className="w-full h-full rounded-lg"
|
||||
style={{
|
||||
border: "1px solid var(--card-border)",
|
||||
}}
|
||||
/>
|
||||
{!ready && (
|
||||
<div
|
||||
className="absolute inset-0 flex flex-col items-center justify-center gap-2 rounded-lg"
|
||||
style={{ backgroundColor: "var(--secondary)", color: "var(--text-muted)" }}
|
||||
data-testid="karaoke-background-preview-loading"
|
||||
>
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
<span className="text-xs">{t('loading')}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
"use client"
|
||||
|
||||
import { useRef, useEffect, useCallback } from "react"
|
||||
import { useRef, useEffect, useState, useCallback } from "react"
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Loader2 } from "lucide-react"
|
||||
|
||||
interface TitleCardPreviewProps {
|
||||
artist: string
|
||||
@@ -19,9 +20,19 @@ interface TitleCardPreviewProps {
|
||||
// - Title: white (#ffffff), uppercase, region 370,980,3100,350
|
||||
// - Artist: golden yellow (#ffdf6b), uppercase, region 370,1400,3100,450
|
||||
|
||||
// Coordinate space the title-card layout is authored in (style_params.json is in
|
||||
// 4K). All region/font constants below are in this space; the canvas renders at a
|
||||
// much smaller preview resolution (see PREVIEW_*) via a scale transform, so a small
|
||||
// thumbnail no longer allocates a 4K (3840×2160) backing store + 4K PNG.
|
||||
const CANVAS_W = 3840
|
||||
const CANVAS_H = 2160
|
||||
|
||||
// Actual canvas backing-store resolution for the preview (multiplied by the
|
||||
// device pixel ratio, capped, at draw time). Plenty sharp for the thumbnail.
|
||||
const PREVIEW_W = 960
|
||||
const PREVIEW_H = 540
|
||||
const MAX_DPR = 2
|
||||
|
||||
// Title region: x=370, y=980, w=3100, h=350
|
||||
const TITLE_X = 370
|
||||
const TITLE_Y = 980
|
||||
@@ -37,6 +48,9 @@ const ARTIST_H = 450
|
||||
const TITLE_COLOR = "#ffffff"
|
||||
const ARTIST_COLOR = "#ffdf6b"
|
||||
|
||||
// Low-res background sized for the preview (the full 4K asset stays for the real
|
||||
// render path). Cached at module scope so it loads once per session.
|
||||
const TITLE_CARD_BG_SRC = "/title-card-bg-preview.png"
|
||||
let bgImageCache: HTMLImageElement | null = null
|
||||
|
||||
function loadBgImage(): Promise<HTMLImageElement> {
|
||||
@@ -48,10 +62,21 @@ function loadBgImage(): Promise<HTMLImageElement> {
|
||||
resolve(img)
|
||||
}
|
||||
img.onerror = reject
|
||||
img.src = "/title-card-bg.png"
|
||||
img.src = TITLE_CARD_BG_SRC
|
||||
})
|
||||
}
|
||||
|
||||
/** Warm the title-card background cache ahead of time (e.g. on Step 2) so the
|
||||
* Step 4 preview paints instantly. Safe to call repeatedly; failures are ignored. */
|
||||
export function preloadTitleCardBg(): void {
|
||||
void loadBgImage().catch(() => {})
|
||||
}
|
||||
|
||||
/** Test-only: clear the module-level bg cache so each test starts from a cold load. */
|
||||
export function __resetTitleCardBgCacheForTest(): void {
|
||||
bgImageCache = null
|
||||
}
|
||||
|
||||
function fitText(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
text: string,
|
||||
@@ -126,6 +151,7 @@ function drawTextBlock(
|
||||
export function TitleCardPreview({ artist, title, customBackgroundUrl, backgroundColor, titleColor, artistColor }: TitleCardPreviewProps) {
|
||||
const t = useTranslations('titleCardPreview')
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
const [ready, setReady] = useState(false)
|
||||
|
||||
const effectiveTitleColor = titleColor || TITLE_COLOR
|
||||
const effectiveArtistColor = artistColor || ARTIST_COLOR
|
||||
@@ -133,8 +159,18 @@ export function TitleCardPreview({ artist, title, customBackgroundUrl, backgroun
|
||||
const draw = useCallback(async () => {
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas) return
|
||||
|
||||
// Size the backing store to the preview resolution (dpr-aware, capped) and
|
||||
// scale the 4K coordinate space down to it, so we never allocate a 4K canvas.
|
||||
const dpr = Math.min((typeof window !== "undefined" && window.devicePixelRatio) || 1, MAX_DPR)
|
||||
const cw = Math.round(PREVIEW_W * dpr)
|
||||
const ch = Math.round(PREVIEW_H * dpr)
|
||||
if (canvas.width !== cw) canvas.width = cw
|
||||
if (canvas.height !== ch) canvas.height = ch
|
||||
|
||||
const ctx = canvas.getContext("2d")
|
||||
if (!ctx) return
|
||||
ctx.setTransform(cw / CANVAS_W, 0, 0, ch / CANVAS_H, 0, 0)
|
||||
|
||||
// Draw background: custom image > solid color > default image
|
||||
try {
|
||||
@@ -194,6 +230,8 @@ export function TitleCardPreview({ artist, title, customBackgroundUrl, backgroun
|
||||
artist ? effectiveArtistColor : "rgba(255,223,107,0.25)",
|
||||
fontFamily,
|
||||
)
|
||||
|
||||
setReady(true)
|
||||
}, [artist, title, customBackgroundUrl, backgroundColor, effectiveTitleColor, effectiveArtistColor, t])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -201,15 +239,26 @@ export function TitleCardPreview({ artist, title, customBackgroundUrl, backgroun
|
||||
}, [draw])
|
||||
|
||||
return (
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
width={CANVAS_W}
|
||||
height={CANVAS_H}
|
||||
className="w-full rounded-lg"
|
||||
style={{
|
||||
aspectRatio: "16/9",
|
||||
border: "1px solid var(--card-border)",
|
||||
}}
|
||||
/>
|
||||
<div className="relative w-full" style={{ aspectRatio: "16/9" }}>
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
width={PREVIEW_W}
|
||||
height={PREVIEW_H}
|
||||
className="w-full h-full rounded-lg"
|
||||
style={{
|
||||
border: "1px solid var(--card-border)",
|
||||
}}
|
||||
/>
|
||||
{!ready && (
|
||||
<div
|
||||
className="absolute inset-0 flex flex-col items-center justify-center gap-2 rounded-lg"
|
||||
style={{ backgroundColor: "var(--secondary)", color: "var(--text-muted)" }}
|
||||
data-testid="title-card-preview-loading"
|
||||
>
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
<span className="text-xs">{t('loading')}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -23,6 +23,7 @@ jest.mock("@/lib/api", () => ({
|
||||
searchStandalone: jest.fn(),
|
||||
searchCatalogTracks: jest.fn(),
|
||||
checkCommunityVersions: jest.fn(),
|
||||
matchJudge: jest.fn(),
|
||||
createJobFromSearch: jest.fn(),
|
||||
},
|
||||
ApiError: class ApiError extends Error {
|
||||
@@ -75,10 +76,46 @@ const defaultProps = {
|
||||
onUrlReady: jest.fn(),
|
||||
onFileReady: jest.fn(),
|
||||
onBack: jest.fn(),
|
||||
onAudioEditChange: jest.fn(),
|
||||
noCredits: false,
|
||||
}
|
||||
|
||||
function verdict(overrides: Partial<import("@/lib/api").MatchJudgeVerdict> = {}) {
|
||||
return {
|
||||
kind: "none" as const,
|
||||
confident: true,
|
||||
canonical_artist: "ABBA",
|
||||
canonical_title: "Waterloo",
|
||||
alternatives: [],
|
||||
engine: "catalog" as const,
|
||||
reason: "",
|
||||
needs_ai: false,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
/** Stage-aware matchJudge mock: the component fires a "fast" pass on mount and a
|
||||
* "full" pass (with the tier) only when the fast pass is inconclusive / weak. */
|
||||
function setJudgeVerdicts(opts: {
|
||||
fast?: Partial<import("@/lib/api").MatchJudgeVerdict>
|
||||
full?: Partial<import("@/lib/api").MatchJudgeVerdict>
|
||||
}) {
|
||||
mockApi.matchJudge.mockImplementation((_a, _t, callOpts) => {
|
||||
const isFast = callOpts?.stage === "fast"
|
||||
return Promise.resolve(verdict(isFast ? opts.fast : opts.full))
|
||||
})
|
||||
}
|
||||
|
||||
function setupMocks() {
|
||||
// Reset confidence to the tier-1 default each test (mockReturnValue otherwise
|
||||
// persists across tests because clearAllMocks only clears call history).
|
||||
mockGetSearchConfidence.mockReturnValue({
|
||||
tier: 1,
|
||||
bestResult: { index: 0, title: "Waterloo", artist: "ABBA", provider: "YouTube", url: "https://yt.com/1" },
|
||||
bestCategory: "LOSSLESS",
|
||||
reason: "Perfect match",
|
||||
warnings: [],
|
||||
})
|
||||
mockApi.searchStandalone.mockResolvedValue({
|
||||
search_session_id: "sess-123",
|
||||
results: [
|
||||
@@ -92,6 +129,8 @@ function setupMocks() {
|
||||
songs: [],
|
||||
best_youtube_url: null,
|
||||
})
|
||||
// Default: catalog says "already canonical" on both passes (no change).
|
||||
setJudgeVerdicts({ fast: {}, full: {} })
|
||||
}
|
||||
|
||||
describe("AudioSourceStep", () => {
|
||||
@@ -108,11 +147,63 @@ describe("AudioSourceStep", () => {
|
||||
})
|
||||
})
|
||||
|
||||
it("calls searchCatalogTracks on mount in parallel", async () => {
|
||||
it("fires a fast catalog-only pass on mount (parallel with search)", async () => {
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockApi.searchCatalogTracks).toHaveBeenCalledWith("Waterloo", "ABBA", 5)
|
||||
expect(mockApi.matchJudge).toHaveBeenCalledWith("ABBA", "Waterloo", { stage: "fast" })
|
||||
})
|
||||
})
|
||||
|
||||
it("fires a full pass with the tier when the fast pass is inconclusive", async () => {
|
||||
setJudgeVerdicts({
|
||||
fast: { kind: "none", confident: false, needs_ai: true, engine: "catalog" },
|
||||
full: { kind: "none", confident: true },
|
||||
})
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockApi.matchJudge).toHaveBeenCalledWith(
|
||||
"ABBA", "Waterloo", { stage: "full", audioConfidenceTier: 1 }
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it("does NOT fire a full pass when the fast pass is confident and audio is strong", async () => {
|
||||
// Default mocks: fast returns a confident catalog verdict, tier 1.
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockApi.matchJudge).toHaveBeenCalledWith("ABBA", "Waterloo", { stage: "fast" })
|
||||
})
|
||||
// Give the coordinating effect a chance to (not) fire the full call.
|
||||
await waitFor(() => {
|
||||
expect(mockApi.matchJudge).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
expect(mockApi.matchJudge).not.toHaveBeenCalledWith(
|
||||
"ABBA", "Waterloo", expect.objectContaining({ stage: "full" })
|
||||
)
|
||||
})
|
||||
|
||||
it("fires a full pass to verify a catalog match when audio results are weak (tier 3)", async () => {
|
||||
mockApi.searchStandalone.mockResolvedValue({
|
||||
search_session_id: "sess-empty", results: [], results_count: 0,
|
||||
})
|
||||
mockGetSearchConfidence.mockReturnValue({
|
||||
tier: 3, bestResult: null, bestCategory: null, reason: "", warnings: [],
|
||||
})
|
||||
setJudgeVerdicts({
|
||||
fast: { kind: "none", confident: true, engine: "catalog" }, // catalog "matched"
|
||||
full: { kind: "content", confident: true, canonical_title: "Waterloo (Fixed)", engine: "ai" },
|
||||
})
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockApi.matchJudge).toHaveBeenCalledWith(
|
||||
"ABBA", "Waterloo", { stage: "full", audioConfidenceTier: 3 }
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -147,16 +238,119 @@ describe("AudioSourceStep", () => {
|
||||
expect(screen.getByText("ABBA - Waterloo")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("renders SongSuggestionPanel when catalog returns results", async () => {
|
||||
mockApi.searchCatalogTracks.mockResolvedValue([
|
||||
{ artist_name: "ABBA", track_name: "Waterloo (Remastered)" },
|
||||
])
|
||||
it("auto-applies a cosmetic tidy from the fast pass and shows the tidy notice", async () => {
|
||||
setJudgeVerdicts({
|
||||
fast: {
|
||||
kind: "cosmetic",
|
||||
confident: true,
|
||||
canonical_title: "Waterloo (Remastered)",
|
||||
engine: "catalog",
|
||||
},
|
||||
})
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("song-suggestion-panel")).toBeInTheDocument()
|
||||
expect(defaultProps.onArtistTitleCorrection).toHaveBeenCalledWith("ABBA", "Waterloo (Remastered)")
|
||||
})
|
||||
expect(screen.getByTestId("match-tidy-notice")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("does not auto-apply an ambiguous match — shows an ask instead", async () => {
|
||||
setJudgeVerdicts({
|
||||
fast: { kind: "none", confident: false, needs_ai: true, engine: "catalog" },
|
||||
full: {
|
||||
kind: "ambiguous",
|
||||
confident: false,
|
||||
canonical_artist: "Lewis Capaldi",
|
||||
canonical_title: "Bruises",
|
||||
alternatives: [{ artist: "Fox Stevenson", title: "Bruises" }],
|
||||
engine: "ai",
|
||||
},
|
||||
})
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("match-didyoumean")).toBeInTheDocument()
|
||||
})
|
||||
expect(defaultProps.onArtistTitleCorrection).not.toHaveBeenCalled()
|
||||
|
||||
const user = userEvent.setup()
|
||||
await user.click(screen.getByText("Lewis Capaldi — Bruises"))
|
||||
expect(defaultProps.onArtistTitleCorrection).toHaveBeenCalledWith("Lewis Capaldi", "Bruises")
|
||||
})
|
||||
|
||||
it("gates the pick button until the judge settles, then enables it", async () => {
|
||||
// Fast pass is inconclusive; full pass resolves after a tick → gate releases.
|
||||
let resolveFull: (v: import("@/lib/api").MatchJudgeVerdict) => void = () => {}
|
||||
mockApi.matchJudge.mockImplementation((_a, _t, callOpts) => {
|
||||
if (callOpts?.stage === "fast") {
|
||||
return Promise.resolve(verdict({ kind: "none", confident: false, needs_ai: true }))
|
||||
}
|
||||
return new Promise<import("@/lib/api").MatchJudgeVerdict>((res) => { resolveFull = res })
|
||||
})
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
// Pick button rendered but disabled while the full pass is in flight.
|
||||
const pickButton = await screen.findByRole("button", { name: /Use This Audio/i })
|
||||
expect(pickButton).toBeDisabled()
|
||||
expect(screen.getByTestId("match-gate-checking")).toBeInTheDocument()
|
||||
|
||||
// Resolve the full pass → gate releases, button enables.
|
||||
await act(async () => {
|
||||
resolveFull(verdict({ kind: "none", confident: true }))
|
||||
})
|
||||
await waitFor(() => expect(pickButton).toBeEnabled())
|
||||
expect(screen.queryByTestId("match-gate-checking")).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("releases the gate via the safety timeout if the judge hangs", async () => {
|
||||
jest.useFakeTimers()
|
||||
try {
|
||||
mockApi.matchJudge.mockImplementation((_a, _t, callOpts) => {
|
||||
if (callOpts?.stage === "fast") {
|
||||
return Promise.resolve(verdict({ kind: "none", confident: false, needs_ai: true }))
|
||||
}
|
||||
return new Promise(() => {}) // full pass never resolves
|
||||
})
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
// Let the fast pass + coordinating effect run.
|
||||
await act(async () => { await Promise.resolve() })
|
||||
const pickButton = await screen.findByRole("button", { name: /Use This Audio/i })
|
||||
expect(pickButton).toBeDisabled()
|
||||
|
||||
// Advance past the 12s safety timeout → gate releases.
|
||||
await act(async () => { jest.advanceTimersByTime(12000) })
|
||||
await waitFor(() => expect(pickButton).toBeEnabled())
|
||||
} finally {
|
||||
jest.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it("toggles a cosmetic tidy back and forth (two-way)", async () => {
|
||||
setJudgeVerdicts({
|
||||
fast: { kind: "cosmetic", confident: true, canonical_title: "Waterloo (Remastered)", engine: "catalog" },
|
||||
})
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(defaultProps.onArtistTitleCorrection).toHaveBeenCalledWith("ABBA", "Waterloo (Remastered)")
|
||||
})
|
||||
|
||||
const user = userEvent.setup()
|
||||
// Revert to what the user typed.
|
||||
await user.click(screen.getByText("keep what I typed"))
|
||||
expect(defaultProps.onArtistTitleCorrection).toHaveBeenLastCalledWith("ABBA", "Waterloo")
|
||||
expect(screen.getByText(/Using what you typed/)).toBeInTheDocument()
|
||||
|
||||
// Switch back to the tidied version.
|
||||
await user.click(screen.getByText("use tidied version"))
|
||||
expect(defaultProps.onArtistTitleCorrection).toHaveBeenLastCalledWith("ABBA", "Waterloo (Remastered)")
|
||||
})
|
||||
|
||||
it("renders CommunityVersionBanner when community data has results", async () => {
|
||||
@@ -239,8 +433,8 @@ describe("AudioSourceStep", () => {
|
||||
expect(defaultProps.onBack).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it("silently handles catalog search failure (does not show error)", async () => {
|
||||
mockApi.searchCatalogTracks.mockRejectedValue(new Error("catalog down"))
|
||||
it("silently handles matchJudge failure (does not show error)", async () => {
|
||||
mockApi.matchJudge.mockRejectedValue(new Error("judge down"))
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
@@ -248,8 +442,8 @@ describe("AudioSourceStep", () => {
|
||||
expect(mockApi.searchStandalone).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
// No error shown for catalog failure — it's a nice-to-have
|
||||
expect(screen.queryByText("catalog down")).not.toBeInTheDocument()
|
||||
// No error shown for judge failure — it's a nice-to-have
|
||||
expect(screen.queryByText("judge down")).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("silently handles community check failure", async () => {
|
||||
@@ -264,16 +458,15 @@ describe("AudioSourceStep", () => {
|
||||
expect(screen.queryByText("community down")).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("does not show SongSuggestionPanel when catalog returns empty array", async () => {
|
||||
mockApi.searchCatalogTracks.mockResolvedValue([])
|
||||
|
||||
it("shows no match notice for a 'none' verdict", async () => {
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockApi.searchStandalone).toHaveBeenCalled()
|
||||
expect(mockApi.matchJudge).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
expect(screen.queryByTestId("song-suggestion-panel")).not.toBeInTheDocument()
|
||||
expect(screen.queryByTestId("match-tidy-notice")).not.toBeInTheDocument()
|
||||
expect(screen.queryByTestId("match-didyoumean")).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("does not show CommunityVersionBanner when has_community is false", async () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { render, act } from "@testing-library/react"
|
||||
import { TitleCardPreview } from "../TitleCardPreview"
|
||||
import { render, act, screen } from "@testing-library/react"
|
||||
import { TitleCardPreview, preloadTitleCardBg, __resetTitleCardBgCacheForTest } from "../TitleCardPreview"
|
||||
|
||||
// Module-level state shared with mock closures via reference
|
||||
const state = {
|
||||
@@ -32,6 +32,7 @@ function setupMocks() {
|
||||
state.fontLoadResolve = null
|
||||
|
||||
HTMLCanvasElement.prototype.getContext = jest.fn(() => ({
|
||||
setTransform: jest.fn(),
|
||||
drawImage: jest.fn(),
|
||||
fillRect: jest.fn(),
|
||||
fillText: jest.fn((text: string) => {
|
||||
@@ -74,6 +75,7 @@ function setupMocks() {
|
||||
|
||||
beforeEach(() => {
|
||||
setupMocks()
|
||||
__resetTitleCardBgCacheForTest()
|
||||
})
|
||||
|
||||
describe("TitleCardPreview", () => {
|
||||
@@ -154,6 +156,7 @@ describe("TitleCardPreview", () => {
|
||||
let _fillStyle = ""
|
||||
let _font = ""
|
||||
return {
|
||||
setTransform: jest.fn(),
|
||||
drawImage: jest.fn(),
|
||||
fillRect: jest.fn(),
|
||||
fillText: jest.fn((text: string) => {
|
||||
@@ -187,6 +190,66 @@ describe("TitleCardPreview", () => {
|
||||
expect(fillStyles).toContain("#00ff00")
|
||||
})
|
||||
|
||||
it("renders the canvas at preview resolution, not 4K", async () => {
|
||||
let result: ReturnType<typeof render>
|
||||
await act(async () => {
|
||||
result = render(<TitleCardPreview title="Test" artist="Artist" />)
|
||||
await new Promise((r) => setTimeout(r, 100))
|
||||
})
|
||||
|
||||
const canvasEl = result!.container.querySelector("canvas")
|
||||
expect(canvasEl).not.toBeNull()
|
||||
// dpr defaults to 1 in jsdom → 960×540 backing store (was 3840×2160).
|
||||
expect(canvasEl!.width).toBe(960)
|
||||
expect(canvasEl!.height).toBe(540)
|
||||
})
|
||||
|
||||
it("loads the low-res preview background by default", async () => {
|
||||
const loadedSrcs: string[] = []
|
||||
global.Image = class MockImageDefault {
|
||||
onload: (() => void) | null = null
|
||||
onerror: (() => void) | null = null
|
||||
_src = ""
|
||||
complete = true
|
||||
get src() { return this._src }
|
||||
set src(v: string) {
|
||||
this._src = v
|
||||
loadedSrcs.push(v)
|
||||
Promise.resolve().then(() => this.onload?.())
|
||||
}
|
||||
} as unknown as typeof Image
|
||||
|
||||
await act(async () => {
|
||||
render(<TitleCardPreview title="Test" artist="Artist" />)
|
||||
await new Promise((r) => setTimeout(r, 100))
|
||||
})
|
||||
|
||||
expect(loadedSrcs).toContain("/title-card-bg-preview.png")
|
||||
expect(loadedSrcs).not.toContain("/title-card-bg.png")
|
||||
})
|
||||
|
||||
it("shows a loading spinner before the first draw completes", () => {
|
||||
// Hold the font load open so draw() never reaches setReady(true).
|
||||
state.fontCheckReturn = false
|
||||
render(<TitleCardPreview title="Song" artist="Artist" />)
|
||||
expect(screen.getByTestId("title-card-preview-loading")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("preloadTitleCardBg loads the low-res asset without throwing", () => {
|
||||
const loadedSrcs: string[] = []
|
||||
global.Image = class MockImagePreload {
|
||||
onload: (() => void) | null = null
|
||||
onerror: (() => void) | null = null
|
||||
_src = ""
|
||||
complete = false
|
||||
get src() { return this._src }
|
||||
set src(v: string) { this._src = v; loadedSrcs.push(v) }
|
||||
} as unknown as typeof Image
|
||||
|
||||
expect(() => preloadTitleCardBg()).not.toThrow()
|
||||
expect(loadedSrcs).toContain("/title-card-bg-preview.png")
|
||||
})
|
||||
|
||||
it("loads custom background image when customBackgroundUrl is provided", async () => {
|
||||
const loadedSrcs: string[] = []
|
||||
global.Image = class MockImageCustom {
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
|
||||
import { useTranslations } from "next-intl"
|
||||
import { useState, useEffect, useMemo, useCallback, useRef } from "react"
|
||||
import { api, ApiError, CatalogTrackResult, CommunityCheckResponse } from "@/lib/api"
|
||||
import { api, ApiError, CatalogTrackResult, CommunityCheckResponse, MatchJudgeVerdict } from "@/lib/api"
|
||||
import { CommunityVersionBanner } from "@/components/job/CommunityVersionBanner"
|
||||
import { preloadTitleCardBg } from "@/components/job/TitleCardPreview"
|
||||
import { preloadKaraokeBg } from "@/components/job/KaraokeBackgroundPreview"
|
||||
import {
|
||||
ExtendedAudioSearchResult,
|
||||
groupResults,
|
||||
@@ -18,7 +20,7 @@ import {
|
||||
} from "@/lib/audio-search-utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Loader2, ChevronDown, ChevronUp, Upload, Youtube, ArrowLeft, Check, AlertTriangle, CheckCircle2, Lightbulb, Info, Search, X, Scissors, Zap } from "lucide-react"
|
||||
import { Loader2, ChevronDown, ChevronUp, Upload, Youtube, ArrowLeft, Check, AlertTriangle, CheckCircle2, Lightbulb, Info, X, Scissors, Zap } from "lucide-react"
|
||||
import { BuyCreditsDialog } from "@/components/credits/BuyCreditsDialog"
|
||||
|
||||
interface AudioSourceStepProps {
|
||||
@@ -47,6 +49,21 @@ type SearchStatus =
|
||||
const MAX_SEARCH_ATTEMPTS = 3
|
||||
const RETRY_DELAYS = [0, 2000, 4000] // ms delay before each attempt
|
||||
|
||||
// Audio tier at/above this is "weak" (poor / no results) — a hint the title may
|
||||
// be a typo, which makes the AI judge worth consulting even on a catalog match.
|
||||
const WEAK_TIER = 3
|
||||
|
||||
// Hard ceiling on how long the audio-selection gate stays closed waiting for the
|
||||
// judge. The backend AI call already caps at ~12s; this is a belt-and-suspenders
|
||||
// release so a network hang never strands the user. Bounds the gate to ≤12s.
|
||||
const JUDGE_GATE_TIMEOUT_MS = 12000
|
||||
|
||||
/** True when a fast (catalog-only) pass produced a confident catalog verdict
|
||||
* (a cosmetic tidy or an exact "already canonical" match) — i.e. no AI needed. */
|
||||
function isCatalogConfident(v: MatchJudgeVerdict | null): boolean {
|
||||
return !!v && !v.needs_ai && v.confident && (v.kind === 'cosmetic' || v.kind === 'none')
|
||||
}
|
||||
|
||||
/** Returns true for transient errors that should be auto-retried */
|
||||
function isRetryableError(err: unknown): boolean {
|
||||
// Network errors (TypeError: Failed to fetch, connection refused, CORS)
|
||||
@@ -126,6 +143,7 @@ export function AudioSourceStep({
|
||||
noCredits,
|
||||
onAudioEditChange,
|
||||
}: AudioSourceStepProps) {
|
||||
const tJobFlow = useTranslations('jobFlow')
|
||||
const [results, setResults] = useState<ExtendedAudioSearchResult[]>([])
|
||||
const [searchStatus, setSearchStatus] = useState<SearchStatus>({ phase: 'searching', attempt: 1 })
|
||||
const [pendingChoice, setPendingChoice] = useState<PendingChoice | null>(null)
|
||||
@@ -138,19 +156,30 @@ export function AudioSourceStep({
|
||||
const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set())
|
||||
const searchTriggered = useRef(false)
|
||||
|
||||
// Catalog song suggestions (parallel to audio search)
|
||||
const [catalogResults, setCatalogResults] = useState<CatalogTrackResult[]>([])
|
||||
const [catalogDismissed, setCatalogDismissed] = useState(false)
|
||||
|
||||
// Community version check (parallel to audio search)
|
||||
const [communityData, setCommunityData] = useState<CommunityCheckResponse | null>(null)
|
||||
const [communityDismissed, setCommunityDismissed] = useState(false)
|
||||
|
||||
// Fuzzy "Did you mean?" state
|
||||
const [fuzzySuggestion, setFuzzySuggestion] = useState<CatalogTrackResult | null>(null)
|
||||
const [fuzzyAlternatives, setFuzzyAlternatives] = useState<CatalogTrackResult[]>([])
|
||||
const [fuzzyDismissed, setFuzzyDismissed] = useState(false)
|
||||
const fuzzyTriggered = useRef(false)
|
||||
// Artist/title match judge: formatting tidy + match-acceptance + did-you-mean.
|
||||
// Two-phase: a fast catalog-only pass fires on mount (in parallel with the audio
|
||||
// search) so the common cosmetic tidy is ready before results render; a full pass
|
||||
// (with the confidence tier, may use AI) runs after the search resolves, only when
|
||||
// the fast pass was inconclusive or a catalog match coincides with weak audio.
|
||||
const [verdict, setVerdict] = useState<MatchJudgeVerdict | null>(null)
|
||||
const [verdictDismissed, setVerdictDismissed] = useState(false)
|
||||
// What we auto-applied, so the user can toggle back to exactly what they typed.
|
||||
const [appliedFrom, setAppliedFrom] = useState<{ artist: string; title: string } | null>(null)
|
||||
// Two-way toggle state: true = the canonical correction is applied, false = the
|
||||
// user reverted to what they typed (they can switch back).
|
||||
const [correctionActive, setCorrectionActive] = useState(true)
|
||||
// The fast pass's promise, awaited by the full-pass effect once the tier is known.
|
||||
const fastJudgeRef = useRef<Promise<MatchJudgeVerdict | null> | null>(null)
|
||||
const fullJudgeTriggered = useRef(false)
|
||||
|
||||
// Hard gate: audio-selection buttons stay disabled until the judge settles, so a
|
||||
// user can never advance with un-tidied metadata (and a slow verdict can't clobber
|
||||
// a selection). Released on any terminal judge state or the safety timeout.
|
||||
const [gateReleased, setGateReleased] = useState(false)
|
||||
|
||||
const [showBuyCreditsDialog, setShowBuyCreditsDialog] = useState(false)
|
||||
|
||||
@@ -204,17 +233,12 @@ export function AudioSourceStep({
|
||||
}
|
||||
}, [artist, title, onSearchCompleted])
|
||||
|
||||
// Auto-trigger audio search + catalog search in parallel on mount
|
||||
// Auto-trigger audio search + community check in parallel on mount.
|
||||
// The match judge runs in a separate effect once the search resolves (below).
|
||||
useEffect(() => {
|
||||
if (searchTriggered.current) return
|
||||
searchTriggered.current = true
|
||||
doSearch()
|
||||
// Fire catalog search in parallel (non-blocking)
|
||||
api.searchCatalogTracks(title, artist, 5)
|
||||
.then((tracks) => setCatalogResults(tracks))
|
||||
.catch(() => {
|
||||
// Silently fail — catalog search is a nice-to-have
|
||||
})
|
||||
// Fire community version check in parallel (non-blocking)
|
||||
api.checkCommunityVersions(artist, title)
|
||||
.then((data) => setCommunityData(data))
|
||||
@@ -223,66 +247,128 @@ export function AudioSourceStep({
|
||||
})
|
||||
}, [doSearch, artist, title])
|
||||
|
||||
// Warm the Step 4 preview backgrounds now (artist/title are locked here), so the
|
||||
// title-card / karaoke previews paint instantly by the time the user arrives.
|
||||
useEffect(() => {
|
||||
preloadTitleCardBg()
|
||||
preloadKaraokeBg()
|
||||
}, [])
|
||||
|
||||
const confidence = useMemo(() => getSearchConfidence(results, title), [results, title])
|
||||
const groupedResults = useMemo(() => groupResults(results), [results])
|
||||
const otherResultsCount = results.length > 0 && confidence.bestResult ? results.length - 1 : 0
|
||||
|
||||
// Fuzzy "Did you mean?" — triggers when audio search is poor AND catalog didn't find a close title match
|
||||
const catalogHasExactTitleMatch = useMemo(() =>
|
||||
catalogResults.some((t) => t.track_name.toLowerCase() === title.toLowerCase()),
|
||||
[catalogResults, title]
|
||||
)
|
||||
// Phase 1 — fast catalog-only pass, fired on mount in parallel with the audio
|
||||
// search (no tier needed). A confident cosmetic tidy applies immediately so it's
|
||||
// done before results render. The promise is awaited by phase 2.
|
||||
useEffect(() => {
|
||||
if (fuzzyTriggered.current) return
|
||||
if (isSearching) return // Wait for audio search to complete
|
||||
if (catalogHasExactTitleMatch) return // Catalog found the exact song — no typo
|
||||
if (confidence.tier <= 2) return // Audio search found good results — no typo likely
|
||||
|
||||
fuzzyTriggered.current = true
|
||||
// Try artist name as query first, fall back to title if that returns nothing
|
||||
api.searchCatalogTracks(artist, undefined, 20)
|
||||
.then((tracks) => {
|
||||
const matches = findFuzzyMatches(title, tracks)
|
||||
if (matches.length > 0) {
|
||||
setFuzzySuggestion(matches[0])
|
||||
setFuzzyAlternatives(matches.slice(1))
|
||||
return
|
||||
if (fastJudgeRef.current) return
|
||||
fastJudgeRef.current = api.matchJudge(artist, title, { stage: 'fast' })
|
||||
.then((v) => {
|
||||
if (v.kind === 'cosmetic' && v.confident && !v.needs_ai) {
|
||||
setVerdict(v)
|
||||
applyCorrection(v.canonical_artist, v.canonical_title, false)
|
||||
}
|
||||
// Fallback: search by title (handles case where artist field has garbage like "fox stevenson bruises")
|
||||
return api.searchCatalogTracks(title, undefined, 20).then((titleTracks) => {
|
||||
const titleMatches = findFuzzyMatches(title, titleTracks, 0.6, true, artist)
|
||||
if (titleMatches.length > 0) {
|
||||
setFuzzySuggestion(titleMatches[0])
|
||||
setFuzzyAlternatives(titleMatches.slice(1))
|
||||
}
|
||||
})
|
||||
return v
|
||||
})
|
||||
.catch(() => {
|
||||
// Silently fail
|
||||
})
|
||||
}, [isSearching, catalogResults, confidence.tier, artist, title])
|
||||
.catch(() => null)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [artist, title])
|
||||
|
||||
function handleFuzzyAccept(track?: CatalogTrackResult) {
|
||||
const chosen = track || fuzzySuggestion
|
||||
if (!chosen) return
|
||||
// Update parent's artist/title
|
||||
onArtistTitleCorrection(chosen.artist_name, chosen.track_name)
|
||||
// Reset and restart search with corrected name
|
||||
setFuzzySuggestion(null)
|
||||
setFuzzyAlternatives([])
|
||||
setFuzzyDismissed(true)
|
||||
setResults([])
|
||||
setSearchStatus({ phase: 'searching', attempt: 1 })
|
||||
setCatalogResults([])
|
||||
setCatalogDismissed(false)
|
||||
setCommunityData(null)
|
||||
setCommunityDismissed(false)
|
||||
setShowOtherOptions(false)
|
||||
searchTriggered.current = false
|
||||
fuzzyTriggered.current = false
|
||||
// doSearch (and catalog/community searches) will re-fire via the useEffect
|
||||
// when the parent re-renders us with corrected artist/title props, since
|
||||
// searchTriggered.current is reset and doSearch is recreated with new props.
|
||||
// Phase 2 — once the audio search resolves (so the tier is known): await the fast
|
||||
// pass, run a full pass only when needed (fast inconclusive, or a catalog match
|
||||
// landed on weak audio — item 4), then release the selection gate. Always settles.
|
||||
useEffect(() => {
|
||||
if (isSearching) return
|
||||
if (fullJudgeTriggered.current) return
|
||||
fullJudgeTriggered.current = true
|
||||
|
||||
let cancelled = false
|
||||
const timer = setTimeout(() => {
|
||||
if (!cancelled) setGateReleased(true)
|
||||
}, JUDGE_GATE_TIMEOUT_MS)
|
||||
const tier = confidence.tier
|
||||
|
||||
;(async () => {
|
||||
const fast = await (fastJudgeRef.current ?? Promise.resolve(null))
|
||||
const needFull = !fast || fast.needs_ai || (isCatalogConfident(fast) && tier >= WEAK_TIER)
|
||||
if (needFull) {
|
||||
try {
|
||||
const full = await api.matchJudge(artist, title, { stage: 'full', audioConfidenceTier: tier })
|
||||
if (!cancelled) applyFullVerdict(full, tier)
|
||||
} catch {
|
||||
// Silently fail — matching is a nice-to-have.
|
||||
}
|
||||
}
|
||||
if (!cancelled) {
|
||||
clearTimeout(timer)
|
||||
setGateReleased(true)
|
||||
}
|
||||
})()
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
clearTimeout(timer)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isSearching])
|
||||
|
||||
// Apply a full-pass verdict (cosmetic tidy / confident content correction / ask).
|
||||
function applyFullVerdict(v: MatchJudgeVerdict, tier: number) {
|
||||
setVerdict(v)
|
||||
if (v.kind === 'cosmetic' && v.confident) {
|
||||
// Same song, formatting only — apply silently, never re-search.
|
||||
applyCorrection(v.canonical_artist, v.canonical_title, false)
|
||||
} else if (v.kind === 'content' && v.confident) {
|
||||
// Real character change — apply, and re-search only if the typo'd search came
|
||||
// back weak (tier 3) so we fetch better audio for the fix.
|
||||
applyCorrection(v.canonical_artist, v.canonical_title, tier >= WEAK_TIER)
|
||||
}
|
||||
// ambiguous / unconfident content / none → render an ask (no auto-apply)
|
||||
}
|
||||
|
||||
// Apply a corrected artist/title. reSearch=true re-runs the audio search with
|
||||
// the corrected terms; the verdict notice stays visible across the re-search.
|
||||
function applyCorrection(newArtist: string, newTitle: string, reSearch: boolean) {
|
||||
if (newArtist === artist && newTitle === title) return
|
||||
setAppliedFrom({ artist, title })
|
||||
setCorrectionActive(true)
|
||||
onArtistTitleCorrection(newArtist, newTitle)
|
||||
if (reSearch) {
|
||||
setResults([])
|
||||
setSearchStatus({ phase: 'searching', attempt: 1 })
|
||||
setCommunityData(null)
|
||||
setCommunityDismissed(false)
|
||||
setShowOtherOptions(false)
|
||||
// Keep the gate open and don't re-judge the corrected terms. doSearch
|
||||
// re-fires via the mount effect when the parent re-renders with the
|
||||
// corrected artist/title props (searchTriggered is reset below).
|
||||
searchTriggered.current = false
|
||||
}
|
||||
}
|
||||
|
||||
// User accepts an ambiguous "Did you mean?" suggestion (always re-search).
|
||||
function handleSuggestionAccept(newArtist: string, newTitle: string) {
|
||||
setVerdict({
|
||||
kind: 'content', confident: true,
|
||||
canonical_artist: newArtist, canonical_title: newTitle,
|
||||
alternatives: [], engine: 'ai', reason: '', needs_ai: false,
|
||||
})
|
||||
applyCorrection(newArtist, newTitle, true)
|
||||
}
|
||||
|
||||
// Two-way toggle. Revert restores exactly what the user typed; reapply switches
|
||||
// back to the canonical correction. Toggling is metadata-only (no re-search).
|
||||
function handleRevert() {
|
||||
if (!appliedFrom) return
|
||||
setCorrectionActive(false)
|
||||
onArtistTitleCorrection(appliedFrom.artist, appliedFrom.title)
|
||||
}
|
||||
|
||||
function handleReapply() {
|
||||
if (!verdict) return
|
||||
setCorrectionActive(true)
|
||||
onArtistTitleCorrection(verdict.canonical_artist, verdict.canonical_title)
|
||||
}
|
||||
|
||||
function handleSelect(index: number) {
|
||||
@@ -428,20 +514,32 @@ export function AudioSourceStep({
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Song name suggestions from catalog */}
|
||||
{catalogResults.length > 0 && !catalogDismissed && (
|
||||
<SongSuggestionPanel
|
||||
results={catalogResults}
|
||||
artist={artist}
|
||||
title={title}
|
||||
onSelect={(track) => {
|
||||
onArtistTitleCorrection(track.artist_name, track.track_name)
|
||||
setCatalogDismissed(true)
|
||||
}}
|
||||
onDismiss={() => setCatalogDismissed(true)}
|
||||
{/* Artist/title formatting tidy + did-you-mean */}
|
||||
{verdict && !verdictDismissed && (
|
||||
<MatchNotice
|
||||
verdict={verdict}
|
||||
appliedFrom={appliedFrom}
|
||||
correctionActive={correctionActive}
|
||||
onAccept={handleSuggestionAccept}
|
||||
onRevert={handleRevert}
|
||||
onReapply={handleReapply}
|
||||
onDismiss={() => setVerdictDismissed(true)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Selection gate indicator — while the judge confirms the song details, the
|
||||
audio pick buttons stay disabled so we never advance with un-tidied metadata. */}
|
||||
{!isSearching && !gateReleased && (
|
||||
<div
|
||||
className="flex items-center gap-2 text-xs"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
data-testid="match-gate-checking"
|
||||
>
|
||||
<Loader2 className="w-3.5 h-3.5 animate-spin shrink-0" />
|
||||
<span>{tJobFlow('matchChecking')}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Community version banner */}
|
||||
{communityData?.has_community && !communityDismissed && (
|
||||
<CommunityVersionBanner
|
||||
@@ -450,16 +548,6 @@ export function AudioSourceStep({
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* "Did you mean?" fuzzy correction banner */}
|
||||
{fuzzySuggestion && !fuzzyDismissed && (
|
||||
<DidYouMeanBanner
|
||||
suggestion={fuzzySuggestion}
|
||||
alternatives={fuzzyAlternatives}
|
||||
onAccept={handleFuzzyAccept}
|
||||
onDismiss={() => setFuzzyDismissed(true)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Error display */}
|
||||
{error && (
|
||||
<div className="text-sm rounded p-3 text-red-400 bg-red-500/10">
|
||||
@@ -501,6 +589,7 @@ export function AudioSourceStep({
|
||||
searchTitle={title}
|
||||
onSelect={handleSelect}
|
||||
noCredits={noCredits}
|
||||
locked={!gateReleased}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -512,6 +601,7 @@ export function AudioSourceStep({
|
||||
searchTitle={title}
|
||||
onSelect={handleSelect}
|
||||
noCredits={noCredits}
|
||||
locked={!gateReleased}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -529,6 +619,7 @@ export function AudioSourceStep({
|
||||
uploadFile={uploadFile}
|
||||
setUploadFile={setUploadFile}
|
||||
noCredits={noCredits}
|
||||
locked={!gateReleased}
|
||||
onUrlSubmit={handleUrlSubmit}
|
||||
onUploadSubmit={handleUploadSubmit}
|
||||
/>
|
||||
@@ -548,6 +639,7 @@ export function AudioSourceStep({
|
||||
searchTitle={title}
|
||||
onSelect={handleSelect}
|
||||
noCredits={noCredits}
|
||||
locked={!gateReleased}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -568,6 +660,7 @@ export function AudioSourceStep({
|
||||
uploadFile={uploadFile}
|
||||
setUploadFile={setUploadFile}
|
||||
noCredits={noCredits}
|
||||
locked={!gateReleased}
|
||||
onUrlSubmit={handleUrlSubmit}
|
||||
onUploadSubmit={handleUploadSubmit}
|
||||
/>
|
||||
@@ -585,12 +678,14 @@ function PickCard({
|
||||
searchTitle,
|
||||
onSelect,
|
||||
noCredits,
|
||||
locked,
|
||||
}: {
|
||||
confidence: SearchConfidence
|
||||
variant: "perfect" | "recommended"
|
||||
searchTitle: string
|
||||
onSelect: (index: number) => void
|
||||
noCredits: boolean
|
||||
locked?: boolean
|
||||
}) {
|
||||
const bestResult = confidence.bestResult!
|
||||
const isPerfect = variant === "perfect"
|
||||
@@ -688,7 +783,7 @@ function PickCard({
|
||||
|
||||
<Button
|
||||
onClick={() => onSelect(bestResult.index)}
|
||||
disabled={noCredits}
|
||||
disabled={noCredits || locked}
|
||||
className={`w-full text-white ${
|
||||
isPerfect
|
||||
? 'bg-green-600 hover:bg-green-500'
|
||||
@@ -778,6 +873,7 @@ function OtherOptionsSection({
|
||||
searchTitle,
|
||||
onSelect,
|
||||
noCredits,
|
||||
locked,
|
||||
}: {
|
||||
confidence: SearchConfidence
|
||||
groupedResults: ReturnType<typeof groupResults>
|
||||
@@ -789,6 +885,7 @@ function OtherOptionsSection({
|
||||
searchTitle: string
|
||||
onSelect: (index: number) => void
|
||||
noCredits: boolean
|
||||
locked?: boolean
|
||||
}) {
|
||||
const isTier3 = confidence.tier === 3
|
||||
|
||||
@@ -808,6 +905,7 @@ function OtherOptionsSection({
|
||||
searchTitle={searchTitle}
|
||||
onSelect={onSelect}
|
||||
noCredits={noCredits}
|
||||
locked={locked}
|
||||
defaultExpanded
|
||||
alwaysShowMatchBadge
|
||||
/>
|
||||
@@ -844,6 +942,7 @@ function OtherOptionsSection({
|
||||
searchTitle={searchTitle}
|
||||
onSelect={onSelect}
|
||||
noCredits={noCredits}
|
||||
locked={locked}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -860,6 +959,7 @@ function ResultCategories({
|
||||
searchTitle,
|
||||
onSelect,
|
||||
noCredits,
|
||||
locked,
|
||||
defaultExpanded,
|
||||
alwaysShowMatchBadge,
|
||||
}: {
|
||||
@@ -870,6 +970,7 @@ function ResultCategories({
|
||||
searchTitle: string
|
||||
onSelect: (index: number) => void
|
||||
noCredits: boolean
|
||||
locked?: boolean
|
||||
defaultExpanded?: boolean
|
||||
alwaysShowMatchBadge?: boolean
|
||||
}) {
|
||||
@@ -942,6 +1043,7 @@ function ResultCategories({
|
||||
showMatchBadges={showMatchBadges}
|
||||
onSelect={onSelect}
|
||||
noCredits={noCredits}
|
||||
locked={locked}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -959,12 +1061,14 @@ function ResultRow({
|
||||
showMatchBadges,
|
||||
onSelect,
|
||||
noCredits,
|
||||
locked,
|
||||
}: {
|
||||
result: ExtendedAudioSearchResult
|
||||
searchTitle: string
|
||||
showMatchBadges: boolean
|
||||
onSelect: (index: number) => void
|
||||
noCredits: boolean
|
||||
locked?: boolean
|
||||
}) {
|
||||
const mismatch = useMemo(() => checkFilenameMismatch(searchTitle, result), [searchTitle, result])
|
||||
// Only show "Title match" when we actually verified a match (filename is non-empty)
|
||||
@@ -1024,7 +1128,7 @@ function ResultRow({
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => onSelect(result.index)}
|
||||
disabled={noCredits}
|
||||
disabled={noCredits || locked}
|
||||
className="h-7 px-3 text-xs shrink-0 bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white"
|
||||
>
|
||||
<Check className="w-3 h-3 mr-1" />
|
||||
@@ -1034,191 +1138,6 @@ function ResultRow({
|
||||
)
|
||||
}
|
||||
|
||||
/** Song name suggestion panel — two modes: exact match confirmation vs correction suggestions */
|
||||
function SongSuggestionPanel({
|
||||
results,
|
||||
artist,
|
||||
title,
|
||||
onSelect,
|
||||
onDismiss,
|
||||
}: {
|
||||
results: CatalogTrackResult[]
|
||||
artist: string
|
||||
title: string
|
||||
onSelect: (track: CatalogTrackResult) => void
|
||||
onDismiss: () => void
|
||||
}) {
|
||||
const [showOthers, setShowOthers] = useState(false)
|
||||
|
||||
// Check if any result is a case-insensitive match for the user's input
|
||||
const hasExactMatch = results.some(
|
||||
(t) => t.artist_name.toLowerCase() === artist.toLowerCase() && t.track_name.toLowerCase() === title.toLowerCase()
|
||||
)
|
||||
// Results that differ from what the user typed (potential corrections)
|
||||
const corrections = results.filter(
|
||||
(t) => !(t.artist_name === artist && t.track_name === title)
|
||||
)
|
||||
// If the user already typed exactly right (case-sensitive), nothing to show
|
||||
const hasExactCaseSensitiveMatch = results.some(
|
||||
(t) => t.artist_name === artist && t.track_name === title
|
||||
)
|
||||
|
||||
if (hasExactCaseSensitiveMatch && corrections.length === 0) {
|
||||
// Perfect match, no alternatives — don't show the panel at all
|
||||
return null
|
||||
}
|
||||
|
||||
// Find the exact case-insensitive match (for casing correction)
|
||||
const exactCaseInsensitiveMatch = hasExactMatch
|
||||
? results.find(
|
||||
(t) => t.artist_name.toLowerCase() === artist.toLowerCase() && t.track_name.toLowerCase() === title.toLowerCase()
|
||||
)
|
||||
: null
|
||||
const hasCasingDifference = exactCaseInsensitiveMatch && (
|
||||
exactCaseInsensitiveMatch.artist_name !== artist || exactCaseInsensitiveMatch.track_name !== title
|
||||
)
|
||||
// "Other" corrections excludes the exact case-insensitive match
|
||||
const otherCorrections = corrections.filter(
|
||||
(t) => !exactCaseInsensitiveMatch || t.artist_name !== exactCaseInsensitiveMatch.artist_name || t.track_name !== exactCaseInsensitiveMatch.track_name
|
||||
)
|
||||
|
||||
// Mode 1: User's input matches a song (case-insensitive) — show confirmation with optional alternatives
|
||||
if (hasExactMatch) {
|
||||
return (
|
||||
<div
|
||||
className="border rounded-lg overflow-hidden border-green-500/30 bg-green-500/5"
|
||||
data-testid="song-suggestion-panel"
|
||||
>
|
||||
<div className="px-3 py-2 flex items-center justify-between bg-green-500/10">
|
||||
<div className="flex items-center gap-2">
|
||||
<CheckCircle2 className="w-3.5 h-3.5 text-green-400" />
|
||||
<span className="text-xs font-semibold text-green-400">
|
||||
Song found in our database
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
onClick={onDismiss}
|
||||
className="text-[10px] flex items-center gap-1 hover:opacity-80"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
<X className="w-3 h-3" />
|
||||
Dismiss
|
||||
</button>
|
||||
</div>
|
||||
<div className="px-3 py-2">
|
||||
{hasCasingDifference && exactCaseInsensitiveMatch ? (
|
||||
<div>
|
||||
<p className="text-[10px] mb-1.5" style={{ color: 'var(--text-muted)' }}>
|
||||
Use the official formatting?
|
||||
</p>
|
||||
<CatalogTrackList tracks={[exactCaseInsensitiveMatch]} onSelect={onSelect} />
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
|
||||
Your artist and title matched a song in our database — looking good!
|
||||
</p>
|
||||
)}
|
||||
{otherCorrections.length > 0 && (
|
||||
<div className="mt-2">
|
||||
<button
|
||||
onClick={() => setShowOthers(!showOthers)}
|
||||
className="flex items-center gap-1 text-[10px] hover:opacity-80"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
{showOthers ? (
|
||||
<><ChevronUp className="w-3 h-3" /> Hide other matches</>
|
||||
) : (
|
||||
<><ChevronDown className="w-3 h-3" /> Show {otherCorrections.length} other match{otherCorrections.length !== 1 ? 'es' : ''}</>
|
||||
)}
|
||||
</button>
|
||||
{showOthers && (
|
||||
<div className="mt-1.5 space-y-1">
|
||||
<CatalogTrackList tracks={otherCorrections} onSelect={onSelect} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Mode 2: No exact match — show corrections prominently
|
||||
return (
|
||||
<div
|
||||
className="border rounded-lg overflow-hidden border-blue-500/30 bg-blue-500/5"
|
||||
data-testid="song-suggestion-panel"
|
||||
>
|
||||
<div className="px-3 py-2 flex items-center justify-between bg-blue-500/10">
|
||||
<div className="flex items-center gap-2">
|
||||
<Search className="w-3.5 h-3.5 text-blue-400" />
|
||||
<span className="text-xs font-semibold text-blue-400">
|
||||
Use official artist/title formatting?
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
onClick={onDismiss}
|
||||
className="text-[10px] flex items-center gap-1 hover:opacity-80"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
<X className="w-3 h-3" />
|
||||
Dismiss
|
||||
</button>
|
||||
</div>
|
||||
<div className="px-3 py-2">
|
||||
<p className="text-[10px] mb-2" style={{ color: 'var(--text-muted)' }}>
|
||||
We found these in our song database. Click one to use the official artist/title formatting:
|
||||
</p>
|
||||
<CatalogTrackList tracks={corrections.length > 0 ? corrections : results} onSelect={onSelect} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Reusable list of clickable catalog track rows */
|
||||
function CatalogTrackList({
|
||||
tracks,
|
||||
onSelect,
|
||||
}: {
|
||||
tracks: CatalogTrackResult[]
|
||||
onSelect: (track: CatalogTrackResult) => void
|
||||
}) {
|
||||
// Deduplicate by artist + track name (Spotify often returns the same song from different albums)
|
||||
const uniqueTracks = tracks.filter((t, i, arr) =>
|
||||
arr.findIndex((x) => x.artist_name === t.artist_name && x.track_name === t.track_name) === i
|
||||
)
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
{uniqueTracks.map((track, i) => {
|
||||
const duration = track.duration_ms
|
||||
? `${Math.floor(track.duration_ms / 60000)}:${Math.floor((track.duration_ms % 60000) / 1000).toString().padStart(2, "0")}`
|
||||
: null
|
||||
return (
|
||||
<button
|
||||
key={track.track_id || `${track.artist_name}-${track.track_name}-${i}`}
|
||||
onClick={() => onSelect(track)}
|
||||
className="w-full text-left px-2.5 py-2 rounded-md text-xs flex items-center justify-between gap-2 transition-colors hover:bg-blue-500/10"
|
||||
style={{ color: 'var(--text)' }}
|
||||
>
|
||||
<span className="min-w-0">
|
||||
<span className="font-medium">{track.artist_name}</span>
|
||||
<span style={{ color: 'var(--text-muted)' }}> — </span>
|
||||
<span>{track.track_name}</span>
|
||||
</span>
|
||||
<span className="flex items-center gap-2 shrink-0">
|
||||
{duration && (
|
||||
<span className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{duration}</span>
|
||||
)}
|
||||
<span className="text-[10px] px-1.5 py-0.5 rounded bg-blue-500/15 text-blue-400 font-medium">
|
||||
Use
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Compute similarity between two strings using longest common subsequence ratio */
|
||||
export function stringSimilarity(a: string, b: string): number {
|
||||
@@ -1274,93 +1193,6 @@ export function findFuzzyMatches(
|
||||
.filter((t, i, arr) => arr.findIndex((x) => x.artist_name === t.artist_name && x.track_name === t.track_name) === i)
|
||||
}
|
||||
|
||||
/** "Did you mean?" banner for typo correction */
|
||||
function DidYouMeanBanner({
|
||||
suggestion,
|
||||
alternatives,
|
||||
onAccept,
|
||||
onDismiss,
|
||||
}: {
|
||||
suggestion: CatalogTrackResult
|
||||
alternatives: CatalogTrackResult[]
|
||||
onAccept: (track?: CatalogTrackResult) => void
|
||||
onDismiss: () => void
|
||||
}) {
|
||||
const [showAlternatives, setShowAlternatives] = useState(false)
|
||||
return (
|
||||
<div
|
||||
className="border rounded-lg overflow-hidden border-amber-500/40 bg-amber-500/5"
|
||||
data-testid="did-you-mean-banner"
|
||||
>
|
||||
<div className="px-3 py-2 flex items-center justify-between bg-amber-500/10">
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertTriangle className="w-3.5 h-3.5 text-amber-400" />
|
||||
<span className="text-xs font-semibold text-amber-400">
|
||||
Did you mean?
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
onClick={onDismiss}
|
||||
className="text-[10px] flex items-center gap-1 hover:opacity-80"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
<X className="w-3 h-3" />
|
||||
No thanks
|
||||
</button>
|
||||
</div>
|
||||
<div className="px-3 py-3">
|
||||
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
We couldn't find great audio sources. Did you mean:
|
||||
</p>
|
||||
<button
|
||||
onClick={() => onAccept()}
|
||||
className="mt-2 w-full text-left px-3 py-2.5 rounded-md flex items-center justify-between gap-2 transition-colors border border-amber-500/30 hover:bg-amber-500/10"
|
||||
>
|
||||
<span className="text-sm" style={{ color: 'var(--text)' }}>
|
||||
<span className="font-semibold">{suggestion.artist_name}</span>
|
||||
<span style={{ color: 'var(--text-muted)' }}> — </span>
|
||||
<span className="font-semibold">{suggestion.track_name}</span>
|
||||
</span>
|
||||
<span className="text-xs px-2 py-1 rounded bg-amber-500/15 text-amber-400 font-medium shrink-0">
|
||||
Yes, search again
|
||||
</span>
|
||||
</button>
|
||||
{alternatives.length > 0 && (
|
||||
<div className="mt-2">
|
||||
<button
|
||||
onClick={() => setShowAlternatives(!showAlternatives)}
|
||||
className="text-[11px] flex items-center gap-1 hover:opacity-80"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
<ChevronDown className={`w-3 h-3 transition-transform ${showAlternatives ? 'rotate-180' : ''}`} />
|
||||
{showAlternatives ? 'Hide' : 'Show'} {alternatives.length} other match{alternatives.length > 1 ? 'es' : ''}
|
||||
</button>
|
||||
{showAlternatives && (
|
||||
<div className="mt-1.5 space-y-1">
|
||||
{alternatives.slice(0, 5).map((alt, i) => (
|
||||
<button
|
||||
key={i}
|
||||
onClick={() => onAccept(alt)}
|
||||
className="w-full text-left px-3 py-2 rounded-md flex items-center justify-between gap-2 transition-colors border border-[var(--card-border)] hover:bg-amber-500/10 hover:border-amber-500/30"
|
||||
>
|
||||
<span className="text-xs" style={{ color: 'var(--text)' }}>
|
||||
<span className="font-medium">{alt.artist_name}</span>
|
||||
<span style={{ color: 'var(--text-muted)' }}> — </span>
|
||||
<span className="font-medium">{alt.track_name}</span>
|
||||
</span>
|
||||
<span className="text-[10px] px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-400 shrink-0">
|
||||
Search
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Contextual guidance when search returns no results */
|
||||
function NoResultsSection() {
|
||||
@@ -1396,6 +1228,7 @@ function FallbackSection({
|
||||
uploadFile,
|
||||
setUploadFile,
|
||||
noCredits,
|
||||
locked,
|
||||
onUrlSubmit,
|
||||
onUploadSubmit,
|
||||
}: {
|
||||
@@ -1408,6 +1241,7 @@ function FallbackSection({
|
||||
uploadFile: File | null
|
||||
setUploadFile: (file: File | null) => void
|
||||
noCredits: boolean
|
||||
locked?: boolean
|
||||
onUrlSubmit: (e: React.FormEvent) => void
|
||||
onUploadSubmit: (e: React.FormEvent) => void
|
||||
}) {
|
||||
@@ -1481,7 +1315,7 @@ function FallbackSection({
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
disabled={!youtubeUrl.trim() || noCredits}
|
||||
disabled={!youtubeUrl.trim() || noCredits || locked}
|
||||
className="w-full bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white"
|
||||
>
|
||||
{t('useThisUrl')}
|
||||
@@ -1533,7 +1367,7 @@ function FallbackSection({
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
disabled={!uploadFile || noCredits}
|
||||
disabled={!uploadFile || noCredits || locked}
|
||||
className="w-full bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white"
|
||||
>
|
||||
Use This File
|
||||
@@ -1543,3 +1377,113 @@ function FallbackSection({
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Match-judge notice: a quiet two-way toggle for an auto-applied tidy/correction
|
||||
* (switch between the canonical version and what you typed), or an ask-first
|
||||
* "Did you mean?" prompt for ambiguous cases. */
|
||||
function MatchNotice({
|
||||
verdict,
|
||||
appliedFrom,
|
||||
correctionActive,
|
||||
onAccept,
|
||||
onRevert,
|
||||
onReapply,
|
||||
onDismiss,
|
||||
}: {
|
||||
verdict: MatchJudgeVerdict
|
||||
appliedFrom: { artist: string; title: string } | null
|
||||
correctionActive: boolean
|
||||
onAccept: (artist: string, title: string) => void
|
||||
onRevert: () => void
|
||||
onReapply: () => void
|
||||
onDismiss: () => void
|
||||
}) {
|
||||
const t = useTranslations('jobFlow')
|
||||
const canonical = `${verdict.canonical_artist} — ${verdict.canonical_title}`
|
||||
|
||||
// Auto-applied cosmetic tidy or confident content correction → quiet two-way
|
||||
// toggle. Active: shows the canonical value + a revert link. Reverted: shows what
|
||||
// the user typed + a reapply link. The current value is always clear.
|
||||
if (appliedFrom && (verdict.kind === 'cosmetic' || verdict.kind === 'content')) {
|
||||
const typed = `${appliedFrom.artist} — ${appliedFrom.title}`
|
||||
const isContent = verdict.kind === 'content'
|
||||
let label: string
|
||||
let action: string
|
||||
let onToggle: () => void
|
||||
if (correctionActive) {
|
||||
label = isContent
|
||||
? t('matchCorrectedTo', { value: canonical, typed })
|
||||
: t('matchTidiedTo', { value: canonical })
|
||||
action = isContent ? t('matchUndo') : t('matchKeepMine')
|
||||
onToggle = onRevert
|
||||
} else {
|
||||
label = t('matchUsingTyped', { value: typed })
|
||||
action = isContent ? t('matchUseCorrection') : t('matchUseTidied')
|
||||
onToggle = onReapply
|
||||
}
|
||||
return (
|
||||
<div
|
||||
className="flex items-center gap-2 text-xs px-3 py-2 rounded-lg"
|
||||
style={{ backgroundColor: 'var(--secondary)', color: 'var(--text-muted)' }}
|
||||
data-testid="match-tidy-notice"
|
||||
data-correction-active={correctionActive}
|
||||
>
|
||||
<Check className="w-3.5 h-3.5 text-green-400 shrink-0" />
|
||||
<span className="flex-1">{label}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggle}
|
||||
className="underline shrink-0"
|
||||
style={{ color: 'var(--brand-pink)' }}
|
||||
>
|
||||
{action}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Ambiguous (or unconfident content) → ask before changing anything.
|
||||
if (verdict.kind === 'ambiguous' || verdict.kind === 'content') {
|
||||
const options = [
|
||||
{ artist: verdict.canonical_artist, title: verdict.canonical_title },
|
||||
...verdict.alternatives,
|
||||
].filter((o) => o.artist && o.title)
|
||||
if (options.length === 0) return null
|
||||
return (
|
||||
<div
|
||||
className="border rounded-lg p-3 border-amber-500/30 bg-amber-500/5"
|
||||
data-testid="match-didyoumean"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="flex items-center gap-2 text-sm font-medium text-amber-400">
|
||||
<Lightbulb className="w-4 h-4" />
|
||||
{t('matchDidYouMean')}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onDismiss}
|
||||
aria-label="Dismiss"
|
||||
className="opacity-60 hover:opacity-100"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="mt-2 flex flex-col gap-1.5">
|
||||
{options.map((o, i) => (
|
||||
<button
|
||||
key={`${o.artist}-${o.title}-${i}`}
|
||||
type="button"
|
||||
onClick={() => onAccept(o.artist, o.title)}
|
||||
className="text-left text-sm px-2.5 py-1.5 rounded-md hover:bg-amber-500/10 transition-colors"
|
||||
style={{ color: 'var(--text)' }}
|
||||
>
|
||||
{o.artist} — {o.title}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { Sparkles, Loader2, AlertTriangle } from 'lucide-react'
|
||||
import {
|
||||
AutoCorrectSettings,
|
||||
DEFAULT_AUTO_CORRECT_SETTINGS,
|
||||
} from '@/lib/api/autoCorrect'
|
||||
import type { AutoCorrectStatus } from '@/hooks/useAutoCorrect'
|
||||
|
||||
interface AutoCorrectModalProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onRun: (settings: AutoCorrectSettings) => void
|
||||
onCancelRun: () => void
|
||||
status: AutoCorrectStatus
|
||||
error: string | null
|
||||
hasReferences: boolean
|
||||
}
|
||||
|
||||
const CONFIDENCE_PRESETS = ['all', 'balanced', 'high'] as const
|
||||
type ConfidencePreset = (typeof CONFIDENCE_PRESETS)[number]
|
||||
const PRESET_THRESHOLDS: Record<ConfidencePreset, number> = {
|
||||
all: 0,
|
||||
balanced: 0.5,
|
||||
high: 0.8,
|
||||
}
|
||||
|
||||
export default function AutoCorrectModal({
|
||||
open,
|
||||
onClose,
|
||||
onRun,
|
||||
onCancelRun,
|
||||
status,
|
||||
error,
|
||||
hasReferences,
|
||||
}: AutoCorrectModalProps) {
|
||||
const t = useTranslations('lyricsReview.autoCorrect')
|
||||
const [adlibRemoval, setAdlibRemoval] = useState(
|
||||
DEFAULT_AUTO_CORRECT_SETTINGS.suggest_adlib_removal,
|
||||
)
|
||||
const [allowInsertions, setAllowInsertions] = useState(
|
||||
DEFAULT_AUTO_CORRECT_SETTINGS.allow_insertions,
|
||||
)
|
||||
const [confidencePreset, setConfidencePreset] = useState<ConfidencePreset>('all')
|
||||
|
||||
const isRunning = status === 'running'
|
||||
|
||||
const handleRun = () => {
|
||||
onRun({
|
||||
suggest_adlib_removal: adlibRemoval,
|
||||
allow_insertions: allowInsertions,
|
||||
min_confidence: PRESET_THRESHOLDS[confidencePreset],
|
||||
// Always multi-model — kept aligned with the backend proactive run so
|
||||
// the cached result is reused.
|
||||
compare_models: DEFAULT_AUTO_CORRECT_SETTINGS.compare_models,
|
||||
})
|
||||
}
|
||||
|
||||
const handleClose = () => {
|
||||
if (isRunning) onCancelRun()
|
||||
onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && handleClose()}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Sparkles className="h-5 w-5 text-purple-500" />
|
||||
{t('title')}
|
||||
</DialogTitle>
|
||||
<DialogDescription>{t('description')}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{!hasReferences ? (
|
||||
<div className="flex items-start gap-2 rounded-md border border-amber-500/50 bg-amber-500/10 p-3 text-sm">
|
||||
<AlertTriangle className="h-4 w-4 mt-0.5 shrink-0 text-amber-500" />
|
||||
<span>{t('noReferences')}</span>
|
||||
</div>
|
||||
) : isRunning ? (
|
||||
<div className="flex flex-col items-center gap-3 py-6">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-purple-500" />
|
||||
<p className="text-sm text-muted-foreground">{t('running')}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<Label htmlFor="ac-adlib">{t('adlibRemovalLabel')}</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('adlibRemovalHint')}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="ac-adlib"
|
||||
checked={adlibRemoval}
|
||||
onCheckedChange={setAdlibRemoval}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<Label htmlFor="ac-insertions">{t('insertionsLabel')}</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('insertionsHint')}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="ac-insertions"
|
||||
checked={allowInsertions}
|
||||
onCheckedChange={setAllowInsertions}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<Label>{t('confidenceLabel')}</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('confidenceHint')}
|
||||
</p>
|
||||
</div>
|
||||
<Select
|
||||
value={confidencePreset}
|
||||
onValueChange={(v) => setConfidencePreset(v as ConfidencePreset)}
|
||||
>
|
||||
<SelectTrigger className="w-36">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{CONFIDENCE_PRESETS.map((p) => (
|
||||
<SelectItem key={p} value={p}>
|
||||
{t(`confidence_${p}`)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="flex items-start gap-2 rounded-md border border-destructive/50 bg-destructive/10 p-3 text-sm">
|
||||
<AlertTriangle className="h-4 w-4 mt-0.5 shrink-0 text-destructive" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleClose}>
|
||||
{isRunning ? t('cancel') : t('close')}
|
||||
</Button>
|
||||
{!isRunning && hasReferences && (
|
||||
<Button onClick={handleRun}>
|
||||
<Sparkles className="h-4 w-4 mr-2" />
|
||||
{t('runButton')}
|
||||
</Button>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Card } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from '@/components/ui/tooltip'
|
||||
import {
|
||||
Sparkles,
|
||||
Check,
|
||||
X,
|
||||
Undo2,
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
AlertTriangle,
|
||||
} from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { AiSuggestion } from '@/lib/api/autoCorrect'
|
||||
import type { AutoCorrectController } from '@/hooks/useAutoCorrect'
|
||||
|
||||
interface AutoCorrectPanelProps {
|
||||
controller: AutoCorrectController
|
||||
isReadOnly: boolean
|
||||
}
|
||||
|
||||
function scrollToWord(wordId: string | undefined) {
|
||||
if (!wordId) return
|
||||
const el = document.getElementById(`word-${wordId}`)
|
||||
if (el) {
|
||||
el.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||||
el.classList.add('animate-lyrics-flash')
|
||||
setTimeout(() => el.classList.remove('animate-lyrics-flash'), 1300)
|
||||
}
|
||||
}
|
||||
|
||||
const CATEGORY_BADGE: Record<AiSuggestion['category'], string> = {
|
||||
mishearing: 'bg-purple-500/15 text-purple-600 dark:text-purple-400',
|
||||
grammar: 'bg-blue-500/15 text-blue-600 dark:text-blue-400',
|
||||
adlib_removal: 'bg-orange-500/15 text-orange-600 dark:text-orange-400',
|
||||
repeated_chorus_fix: 'bg-teal-500/15 text-teal-600 dark:text-teal-400',
|
||||
formatting: 'bg-slate-500/15 text-slate-600 dark:text-slate-400',
|
||||
other: 'bg-slate-500/15 text-slate-600 dark:text-slate-400',
|
||||
}
|
||||
|
||||
export default function AutoCorrectPanel({
|
||||
controller,
|
||||
isReadOnly,
|
||||
}: AutoCorrectPanelProps) {
|
||||
const t = useTranslations('lyricsReview.autoCorrect')
|
||||
const [collapsed, setCollapsed] = useState(false)
|
||||
const {
|
||||
suggestions,
|
||||
decisions,
|
||||
pendingCount,
|
||||
acceptedCount,
|
||||
accept,
|
||||
reject,
|
||||
undoAccept,
|
||||
acceptAll,
|
||||
rejectAll,
|
||||
dismiss,
|
||||
isPendingAndStale,
|
||||
} = controller
|
||||
|
||||
if (controller.status !== 'reviewing') return null
|
||||
|
||||
return (
|
||||
<Card className="mb-3 border-purple-500/40">
|
||||
<div className="flex items-center justify-between gap-2 px-3 py-2">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Sparkles className="h-4 w-4 shrink-0 text-purple-500" />
|
||||
<span className="text-sm font-medium truncate">
|
||||
{suggestions.length === 0
|
||||
? t('noSuggestions')
|
||||
: t('summary', {
|
||||
total: suggestions.length,
|
||||
pending: pendingCount,
|
||||
accepted: acceptedCount,
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 shrink-0">
|
||||
{!isReadOnly && pendingCount > 0 && (
|
||||
<>
|
||||
<Button size="sm" variant="outline" onClick={acceptAll}>
|
||||
<Check className="h-3.5 w-3.5 mr-1" />
|
||||
{t('acceptAll')}
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" onClick={rejectAll}>
|
||||
<X className="h-3.5 w-3.5 mr-1" />
|
||||
{t('rejectAll')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => setCollapsed((c) => !c)}
|
||||
aria-label={collapsed ? t('expand') : t('collapse')}
|
||||
>
|
||||
{collapsed ? (
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={dismiss} aria-label={t('dismiss')}>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!collapsed && suggestions.length > 0 && (
|
||||
// Plain overflow div, NOT the ScrollArea component: its Radix root
|
||||
// has no overflow-hidden, so a max-height there doesn't clip and
|
||||
// long suggestion lists spill over the panel border.
|
||||
<div className="max-h-64 overflow-y-auto border-t">
|
||||
<ul className="divide-y">
|
||||
{suggestions.map((s) => {
|
||||
const decision = decisions[s.id]
|
||||
const stale = decision === 'stale' || isPendingAndStale(s)
|
||||
return (
|
||||
<li
|
||||
key={s.id}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
className={cn(
|
||||
'flex items-center gap-2 px-3 py-1.5 text-sm cursor-pointer hover:bg-muted/50 focus-visible:bg-muted/50 focus-visible:outline-none',
|
||||
decision === 'rejected' && 'opacity-50',
|
||||
)}
|
||||
onClick={() => scrollToWord(s.word_ids[0])}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault()
|
||||
scrollToWord(s.word_ids[0])
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Badge
|
||||
className={cn('shrink-0 text-[10px]', CATEGORY_BADGE[s.category])}
|
||||
>
|
||||
{t(`category_${s.category}`)}
|
||||
</Badge>
|
||||
{s.conflict_group && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="shrink-0 text-[10px] border-purple-500/50 text-purple-600 dark:text-purple-400"
|
||||
>
|
||||
{t('conflictBadge')}
|
||||
</Badge>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent className="max-w-xs">
|
||||
{t('conflictTooltip')}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate">
|
||||
{s.op === 'insert_after' ? (
|
||||
<>
|
||||
<span className="text-muted-foreground">{t('insertMarker')} </span>
|
||||
<span className="text-green-600 dark:text-green-400">
|
||||
{s.new_text}
|
||||
</span>
|
||||
</>
|
||||
) : s.op === 'delete' ? (
|
||||
<span className="line-through text-red-600 dark:text-red-400">
|
||||
{s.original_text}
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<span className="line-through text-red-600 dark:text-red-400">
|
||||
{s.original_text}
|
||||
</span>{' '}
|
||||
<span className="text-green-600 dark:text-green-400">
|
||||
{s.new_text}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span className="shrink-0 text-xs text-muted-foreground tabular-nums">
|
||||
{Math.round(s.confidence * 100)}%
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent className="max-w-xs">{s.reason}</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
<div
|
||||
className="flex items-center gap-1 shrink-0"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{stale ? (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<AlertTriangle className="h-4 w-4 text-amber-500" />
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t('staleHint')}</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
) : decision === 'pending' && !isReadOnly ? (
|
||||
<>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-7 px-2 text-green-600 hover:text-green-700"
|
||||
onClick={() => accept(s.id)}
|
||||
aria-label={t('accept')}
|
||||
>
|
||||
<Check className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-7 px-2 text-red-600 hover:text-red-700"
|
||||
onClick={() => reject(s.id)}
|
||||
aria-label={t('reject')}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</>
|
||||
) : decision === 'accepted' ? (
|
||||
<>
|
||||
<Badge variant="outline" className="text-[10px] text-green-600">
|
||||
{t('accepted')}
|
||||
</Badge>
|
||||
{!isReadOnly && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-7 px-2"
|
||||
onClick={() => undoAccept(s.id)}
|
||||
aria-label={t('undo')}
|
||||
>
|
||||
<Undo2 className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
) : decision === 'rejected' ? (
|
||||
<Badge variant="outline" className="text-[10px]">
|
||||
{t('rejected')}
|
||||
</Badge>
|
||||
) : null}
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
Eye,
|
||||
CheckCircle2,
|
||||
XCircle,
|
||||
Sparkles,
|
||||
} from 'lucide-react'
|
||||
import { CorrectionData, InteractionMode } from '@/lib/lyrics-review/types'
|
||||
import ModeSelector from './ModeSelector'
|
||||
@@ -67,6 +68,7 @@ interface HeaderProps {
|
||||
onRevertAllCorrections?: () => void
|
||||
isDuet?: boolean
|
||||
onToggleDuet?: () => void
|
||||
onAutoCorrect?: () => void
|
||||
}
|
||||
|
||||
export default function Header({
|
||||
@@ -100,6 +102,7 @@ export default function Header({
|
||||
onRevertAllCorrections,
|
||||
isDuet = false,
|
||||
onToggleDuet,
|
||||
onAutoCorrect,
|
||||
}: HeaderProps) {
|
||||
const t = useTranslations('lyricsReview.header')
|
||||
const tDuet = useTranslations('lyricsReview.duet')
|
||||
@@ -290,6 +293,23 @@ export default function Header({
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
{!isReadOnly && onAutoCorrect && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onAutoCorrect}
|
||||
className="h-8 text-xs text-purple-500 border-purple-500/50 hover:border-purple-500 hover:bg-purple-500/10"
|
||||
>
|
||||
<Sparkles className="h-3.5 w-3.5 mr-1" />
|
||||
{t('autoCorrect')}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent className="max-w-xs">{t('autoCorrectDesc')}</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
{!isReadOnly && onTimingOffset && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
|
||||
@@ -55,6 +55,9 @@ import { hasMultipleSingers } from '@/lib/lyrics-review/duet'
|
||||
import SessionRestoreDialog from './SessionRestoreDialog'
|
||||
import Header from './Header'
|
||||
import GapNavigator from './GapNavigator'
|
||||
import AutoCorrectModal from './AutoCorrectModal'
|
||||
import AutoCorrectPanel from './AutoCorrectPanel'
|
||||
import { useAutoCorrect } from '@/hooks/useAutoCorrect'
|
||||
import { getWordsFromIds } from '@/lib/lyrics-review/utils/wordUtils'
|
||||
import { applyOffsetToCorrectionData, applyOffsetToSegment } from '@/lib/lyrics-review/utils/timingUtils'
|
||||
|
||||
@@ -154,6 +157,9 @@ export default function LyricsAnalyzer({
|
||||
const [countdown, setCountdown] = useState(2)
|
||||
const [showInstrumentalReview, setShowInstrumentalReview] = useState(false)
|
||||
|
||||
// AI auto-correct state
|
||||
const [isAutoCorrectModalOpen, setIsAutoCorrectModalOpen] = useState(false)
|
||||
|
||||
// Edit log state
|
||||
const [editLog] = useState<EditLog>(() => createEditLog(jobId ?? 'unknown', audioHash))
|
||||
const [lastEditEntry, setLastEditEntry] = useState<EditLogEntry | null>(null)
|
||||
@@ -214,6 +220,27 @@ export default function LyricsAnalyzer({
|
||||
[history, historyIndex]
|
||||
)
|
||||
|
||||
// AI auto-correct suggestions (opt-in; nothing runs unless triggered)
|
||||
const autoCorrect = useAutoCorrect({
|
||||
jobId,
|
||||
data,
|
||||
updateDataWithHistory,
|
||||
editLog,
|
||||
getAuthToken: () => getAccessToken() ?? undefined,
|
||||
// Auto-run once on load so suggestions are ready without a click. The
|
||||
// backend pre-generates + caches them during lyrics processing, so this
|
||||
// is normally an instant cache hit. Skipped in read-only / local mode,
|
||||
// and only when a jobId exists (the request needs one).
|
||||
autoRunOnLoad: !isReadOnly && !isLocalMode && Boolean(jobId),
|
||||
})
|
||||
|
||||
// Close the run modal once suggestions arrive (panel takes over)
|
||||
useEffect(() => {
|
||||
if (autoCorrect.status === 'reviewing') {
|
||||
setIsAutoCorrectModalOpen(false)
|
||||
}
|
||||
}, [autoCorrect.status])
|
||||
|
||||
// Compute which word IDs have been edited by the user (compared to initial state)
|
||||
const editedWordIds = useMemo(() => {
|
||||
const initial = history[0]
|
||||
@@ -1299,8 +1326,11 @@ export default function LyricsAnalyzer({
|
||||
onRevertAllCorrections={handleRevertAllCorrections}
|
||||
isDuet={isDuet}
|
||||
onToggleDuet={() => setIsDuet(d => !d)}
|
||||
onAutoCorrect={!isLocalMode && jobId ? () => setIsAutoCorrectModalOpen(true) : undefined}
|
||||
/>
|
||||
|
||||
<AutoCorrectPanel controller={autoCorrect} isReadOnly={isReadOnly} />
|
||||
|
||||
<div className={cn('grid gap-2', isMobile ? 'grid-cols-1' : 'grid-cols-2')}>
|
||||
<TranscriptionView
|
||||
data={displayData}
|
||||
@@ -1509,6 +1539,16 @@ export default function LyricsAnalyzer({
|
||||
authToken={getAccessToken() ?? undefined}
|
||||
/>
|
||||
|
||||
<AutoCorrectModal
|
||||
open={isAutoCorrectModalOpen}
|
||||
onClose={() => setIsAutoCorrectModalOpen(false)}
|
||||
onRun={(settings) => void autoCorrect.run(settings)}
|
||||
onCancelRun={autoCorrect.cancel}
|
||||
status={autoCorrect.status}
|
||||
error={autoCorrect.error}
|
||||
hasReferences={autoCorrect.hasReferences}
|
||||
/>
|
||||
|
||||
<EditFeedbackBar
|
||||
entry={lastEditEntry}
|
||||
visible={showFeedbackBar}
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { test, expect, Page } from '@playwright/test'
|
||||
|
||||
/**
|
||||
* AI Auto-Correct Suggestions (production)
|
||||
*
|
||||
* Verifies the opt-in AI suggestions flow end-to-end against live production:
|
||||
* 1. Lists jobs filtered by status=in_review (admin can see all jobs).
|
||||
* 2. Navigates to the lyrics review page for the first matching job.
|
||||
* 3. Opens the "Auto-correct" modal and runs suggestion generation.
|
||||
* 4. Waits for the suggestions panel (up to 120s for the LLM call).
|
||||
* 5. Asserts the panel renders with accept/reject affordances (or the
|
||||
* explicit "no suggestions" state), then dismisses it WITHOUT
|
||||
* accepting — production review state is never mutated.
|
||||
*
|
||||
* Skipped if KARAOKE_ADMIN_TOKEN is unset or no in_review jobs exist.
|
||||
*
|
||||
* Run with:
|
||||
* KARAOKE_ADMIN_TOKEN=xxx npx playwright test \
|
||||
* e2e/production/auto-correct-suggestions.spec.ts \
|
||||
* --config=playwright.production.config.ts --reporter=list
|
||||
*/
|
||||
|
||||
const PROD_URL = 'https://gen.nomadkaraoke.com'
|
||||
const API_URL = 'https://api.nomadkaraoke.com'
|
||||
|
||||
const ADMIN_TOKEN = process.env.KARAOKE_ADMIN_TOKEN
|
||||
|
||||
async function openReviewPage(page: Page): Promise<string> {
|
||||
const listResponse = await page.request.get(
|
||||
`${API_URL}/api/jobs?status=in_review&limit=1&fields=summary`,
|
||||
{ headers: { Authorization: `Bearer ${ADMIN_TOKEN}` } },
|
||||
)
|
||||
expect(listResponse.ok()).toBe(true)
|
||||
const listBody = (await listResponse.json()) as
|
||||
| { jobs?: Array<{ id?: string; job_id?: string }> }
|
||||
| Array<{ id?: string; job_id?: string }>
|
||||
const jobs = Array.isArray(listBody) ? listBody : listBody.jobs ?? []
|
||||
test.skip(!jobs.length, 'No in_review jobs available for E2E')
|
||||
const jobId = jobs[0].id ?? jobs[0].job_id
|
||||
expect(jobId, 'List response did not include a job id').toBeTruthy()
|
||||
|
||||
await page.addInitScript((token: string) => {
|
||||
window.localStorage.setItem('karaoke_access_token', token)
|
||||
}, ADMIN_TOKEN!)
|
||||
|
||||
await page.goto(`${PROD_URL}/app/jobs/#/${jobId}/review`)
|
||||
return jobId as string
|
||||
}
|
||||
|
||||
test.describe('AI auto-correct suggestions (production)', () => {
|
||||
test.skip(!ADMIN_TOKEN, 'KARAOKE_ADMIN_TOKEN not set')
|
||||
|
||||
// No retries: each retry would be another paid LLM call.
|
||||
test.describe.configure({ retries: 0 })
|
||||
|
||||
test('run suggestions, review panel, dismiss without applying', async ({
|
||||
page,
|
||||
}: {
|
||||
page: Page
|
||||
}) => {
|
||||
test.setTimeout(180_000) // includes one LLM call (~15-60s)
|
||||
|
||||
await openReviewPage(page)
|
||||
|
||||
// Generous timeout: right after a deploy the first review-page load can
|
||||
// exceed 30s (cold Cloud Run instance + uncached correction payload).
|
||||
// A "Saved Review Sessions" dialog may open on load (it aria-hides the
|
||||
// rest of the app); close it without restoring before proceeding.
|
||||
const suggestBtn = page.getByRole('button', { name: /Auto-correct/i })
|
||||
const sessionDialog = page.getByRole('dialog', { name: /Saved Review Sessions/i })
|
||||
await expect(suggestBtn.or(sessionDialog).first()).toBeVisible({ timeout: 90_000 })
|
||||
if (await sessionDialog.isVisible().catch(() => false)) {
|
||||
await sessionDialog.getByRole('button', { name: /^Close$/i }).click()
|
||||
await expect(sessionDialog).not.toBeVisible()
|
||||
}
|
||||
await expect(suggestBtn).toBeVisible({ timeout: 30_000 })
|
||||
await suggestBtn.click()
|
||||
|
||||
// Settings modal appears with the run button (or the no-references
|
||||
// warning, in which case the flow correctly ends here).
|
||||
const runBtn = page.getByRole('button', { name: /Get suggestions/i })
|
||||
const noRefs = page.getByText(/No reference lyrics are available/i)
|
||||
await expect(runBtn.or(noRefs).first()).toBeVisible({ timeout: 10_000 })
|
||||
if (await noRefs.isVisible().catch(() => false)) {
|
||||
test.info().annotations.push({
|
||||
type: 'note',
|
||||
description: 'Job had no reference lyrics; verified disabled state.',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
await runBtn.click()
|
||||
|
||||
// Panel appears after the LLM call: either a suggestions summary with
|
||||
// Accept all / Reject all, or the explicit no-suggestions state.
|
||||
const summary = page.getByText(/suggestions? · .* pending/i)
|
||||
const none = page.getByText(/no issues found/i)
|
||||
await expect(summary.or(none).first()).toBeVisible({ timeout: 120_000 })
|
||||
|
||||
if (await summary.isVisible().catch(() => false)) {
|
||||
await expect(
|
||||
page.getByRole('button', { name: /Accept all/i }),
|
||||
).toBeVisible()
|
||||
await expect(
|
||||
page.getByRole('button', { name: /Reject all/i }),
|
||||
).toBeVisible()
|
||||
}
|
||||
|
||||
// Dismiss without accepting anything — leaves review state untouched.
|
||||
await page.getByRole('button', { name: /Dismiss suggestions/i }).click()
|
||||
await expect(summary.or(none).first()).not.toBeVisible()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,311 @@
|
||||
'use client'
|
||||
|
||||
/**
|
||||
* State machine for the opt-in AI auto-correct suggestions feature.
|
||||
*
|
||||
* Nothing runs unless the reviewer explicitly triggers it; suggestions are a
|
||||
* pending layer that never mutates the working data until individually (or
|
||||
* bulk) accepted. Every accept/reject/undo lands in the edit log so we can
|
||||
* measure real-world accept rates per category over time.
|
||||
*/
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
AiSuggestion,
|
||||
AutoCorrectApiError,
|
||||
AutoCorrectSettings,
|
||||
DEFAULT_AUTO_CORRECT_SETTINGS,
|
||||
fetchAutoCorrectSuggestions,
|
||||
} from '@/lib/api/autoCorrect'
|
||||
import {
|
||||
applySuggestion,
|
||||
revertSuggestion,
|
||||
isSuggestionStale,
|
||||
SuggestionUndoInfo,
|
||||
} from '@/lib/lyrics-review/utils/autoCorrectApply'
|
||||
import {
|
||||
getConflictSiblings,
|
||||
pickAcceptAllWinners,
|
||||
} from '@/lib/lyrics-review/utils/autoCorrectConflicts'
|
||||
import { addEditEntry } from '@/lib/lyrics-review/utils/editLog'
|
||||
import type { CorrectionData, EditLog } from '@/lib/lyrics-review/types'
|
||||
|
||||
export type SuggestionDecision = 'pending' | 'accepted' | 'rejected' | 'stale'
|
||||
export type AutoCorrectStatus = 'idle' | 'running' | 'reviewing' | 'error'
|
||||
|
||||
interface UseAutoCorrectArgs {
|
||||
jobId?: string
|
||||
data: CorrectionData
|
||||
updateDataWithHistory: (newData: CorrectionData, desc?: string) => void
|
||||
editLog: EditLog
|
||||
getAuthToken: () => string | undefined
|
||||
/** Auto-trigger one run on load (when references exist) so suggestions are
|
||||
* ready without a click. Normally a cache hit (backend pre-generates). */
|
||||
autoRunOnLoad?: boolean
|
||||
}
|
||||
|
||||
export function useAutoCorrect({
|
||||
jobId,
|
||||
data,
|
||||
updateDataWithHistory,
|
||||
editLog,
|
||||
getAuthToken,
|
||||
autoRunOnLoad = false,
|
||||
}: UseAutoCorrectArgs) {
|
||||
const [status, setStatus] = useState<AutoCorrectStatus>('idle')
|
||||
const [suggestions, setSuggestions] = useState<AiSuggestion[]>([])
|
||||
const [decisions, setDecisions] = useState<Record<string, SuggestionDecision>>({})
|
||||
const [model, setModel] = useState<string>('')
|
||||
const [cached, setCached] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const undoInfos = useRef<Record<string, SuggestionUndoInfo>>({})
|
||||
const abortRef = useRef<AbortController | null>(null)
|
||||
|
||||
const hasReferences = Object.keys(data.reference_lyrics ?? {}).length > 0
|
||||
|
||||
// Abort any in-flight request on unmount so no state updates land after.
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
abortRef.current?.abort()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const run = useCallback(
|
||||
async (settings: AutoCorrectSettings = DEFAULT_AUTO_CORRECT_SETTINGS) => {
|
||||
if (!jobId) return
|
||||
setStatus('running')
|
||||
setError(null)
|
||||
abortRef.current?.abort()
|
||||
const ac = new AbortController()
|
||||
abortRef.current = ac
|
||||
try {
|
||||
const response = await fetchAutoCorrectSuggestions(
|
||||
jobId,
|
||||
{
|
||||
segments: data.corrected_segments,
|
||||
referenceLyrics: data.reference_lyrics ?? {},
|
||||
artist: data.metadata?.artist,
|
||||
title: data.metadata?.title,
|
||||
settings,
|
||||
},
|
||||
ac.signal,
|
||||
getAuthToken(),
|
||||
)
|
||||
setSuggestions(response.suggestions)
|
||||
setDecisions(
|
||||
Object.fromEntries(response.suggestions.map((s) => [s.id, 'pending'])),
|
||||
)
|
||||
undoInfos.current = {}
|
||||
setModel(response.model)
|
||||
setCached(response.cached)
|
||||
setStatus('reviewing')
|
||||
addEditEntry(editLog, 'ai_suggestion_run', {
|
||||
details: {
|
||||
model: response.model,
|
||||
cached: response.cached,
|
||||
suggestion_count: response.suggestions.length,
|
||||
elapsed_seconds: response.elapsed_seconds,
|
||||
settings: response.settings_applied as unknown as Record<string, unknown>,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
if ((err as Error).name === 'AbortError') {
|
||||
setStatus('idle')
|
||||
return
|
||||
}
|
||||
const message =
|
||||
err instanceof AutoCorrectApiError
|
||||
? err.message
|
||||
: 'Unexpected error generating suggestions'
|
||||
setError(message)
|
||||
setStatus('error')
|
||||
}
|
||||
},
|
||||
[jobId, data, editLog, getAuthToken],
|
||||
)
|
||||
|
||||
const cancel = useCallback(() => {
|
||||
abortRef.current?.abort()
|
||||
}, [])
|
||||
|
||||
// Fire exactly one run on load once references + segments are available.
|
||||
// The ref guard ensures it never re-fires as `data` changes during review.
|
||||
const autoRanRef = useRef(false)
|
||||
useEffect(() => {
|
||||
if (!autoRunOnLoad || autoRanRef.current) return
|
||||
if (!jobId || status !== 'idle') return
|
||||
if (!hasReferences || !(data.corrected_segments?.length > 0)) return
|
||||
autoRanRef.current = true
|
||||
void run()
|
||||
}, [autoRunOnLoad, jobId, status, hasReferences, data.corrected_segments, run])
|
||||
|
||||
const logDecision = useCallback(
|
||||
(s: AiSuggestion, op: 'ai_suggestion_accept' | 'ai_suggestion_reject' | 'ai_suggestion_undo') => {
|
||||
addEditEntry(editLog, op, {
|
||||
segment_id: s.segment_ids[0] ?? null,
|
||||
word_ids_before: s.word_ids,
|
||||
text_before: s.original_text,
|
||||
text_after: s.new_text,
|
||||
details: {
|
||||
suggestion_id: s.id,
|
||||
op: s.op,
|
||||
category: s.category,
|
||||
confidence: s.confidence,
|
||||
reason: s.reason,
|
||||
model,
|
||||
models: s.models,
|
||||
consensus: s.consensus,
|
||||
total_models: s.total_models,
|
||||
conflict_group: s.conflict_group,
|
||||
},
|
||||
})
|
||||
},
|
||||
[editLog, model],
|
||||
)
|
||||
|
||||
const accept = useCallback(
|
||||
(id: string) => {
|
||||
const s = suggestions.find((x) => x.id === id)
|
||||
if (!s || decisions[id] !== 'pending') return
|
||||
const result = applySuggestion(data.corrected_segments, s)
|
||||
if (!result) {
|
||||
setDecisions((d) => ({ ...d, [id]: 'stale' }))
|
||||
return
|
||||
}
|
||||
undoInfos.current[id] = result.undo
|
||||
updateDataWithHistory(
|
||||
{ ...data, corrected_segments: result.segments },
|
||||
'accept AI suggestion',
|
||||
)
|
||||
// Accepting one variant of a conflict group rejects the others —
|
||||
// they target the same words with a different outcome.
|
||||
const siblingUpdates: Record<string, SuggestionDecision> = {}
|
||||
for (const sibling of getConflictSiblings(suggestions, id)) {
|
||||
if (decisions[sibling.id] === 'pending') {
|
||||
siblingUpdates[sibling.id] = 'rejected'
|
||||
logDecision(sibling, 'ai_suggestion_reject')
|
||||
}
|
||||
}
|
||||
setDecisions((d) => ({ ...d, ...siblingUpdates, [id]: 'accepted' }))
|
||||
logDecision(s, 'ai_suggestion_accept')
|
||||
},
|
||||
[suggestions, decisions, data, updateDataWithHistory, logDecision],
|
||||
)
|
||||
|
||||
const reject = useCallback(
|
||||
(id: string) => {
|
||||
const s = suggestions.find((x) => x.id === id)
|
||||
if (!s || decisions[id] !== 'pending') return
|
||||
setDecisions((d) => ({ ...d, [id]: 'rejected' }))
|
||||
logDecision(s, 'ai_suggestion_reject')
|
||||
},
|
||||
[suggestions, decisions, logDecision],
|
||||
)
|
||||
|
||||
const undoAccept = useCallback(
|
||||
(id: string): boolean => {
|
||||
const s = suggestions.find((x) => x.id === id)
|
||||
const undo = undoInfos.current[id]
|
||||
if (!s || decisions[id] !== 'accepted' || !undo) return false
|
||||
const reverted = revertSuggestion(data.corrected_segments, undo)
|
||||
if (!reverted) return false
|
||||
delete undoInfos.current[id]
|
||||
updateDataWithHistory(
|
||||
{ ...data, corrected_segments: reverted },
|
||||
'undo AI suggestion',
|
||||
)
|
||||
setDecisions((d) => ({ ...d, [id]: 'pending' }))
|
||||
logDecision(s, 'ai_suggestion_undo')
|
||||
return true
|
||||
},
|
||||
[suggestions, decisions, data, updateDataWithHistory, logDecision],
|
||||
)
|
||||
|
||||
const acceptAll = useCallback(() => {
|
||||
let segments = data.corrected_segments
|
||||
const newDecisions: Record<string, SuggestionDecision> = { ...decisions }
|
||||
// In conflict groups only the winner (highest consensus, then
|
||||
// confidence) is applied; the losing variants are rejected.
|
||||
const winners = new Set(
|
||||
pickAcceptAllWinners(suggestions.filter((s) => newDecisions[s.id] === 'pending')),
|
||||
)
|
||||
let applied = 0
|
||||
for (const s of suggestions) {
|
||||
if (newDecisions[s.id] !== 'pending') continue
|
||||
if (!winners.has(s.id)) {
|
||||
newDecisions[s.id] = 'rejected'
|
||||
logDecision(s, 'ai_suggestion_reject')
|
||||
continue
|
||||
}
|
||||
const result = applySuggestion(segments, s)
|
||||
if (!result) {
|
||||
newDecisions[s.id] = 'stale'
|
||||
continue
|
||||
}
|
||||
segments = result.segments
|
||||
undoInfos.current[s.id] = result.undo
|
||||
newDecisions[s.id] = 'accepted'
|
||||
logDecision(s, 'ai_suggestion_accept')
|
||||
applied += 1
|
||||
}
|
||||
if (applied > 0) {
|
||||
updateDataWithHistory(
|
||||
{ ...data, corrected_segments: segments },
|
||||
'accept all AI suggestions',
|
||||
)
|
||||
}
|
||||
setDecisions(newDecisions)
|
||||
}, [suggestions, decisions, data, updateDataWithHistory, logDecision])
|
||||
|
||||
const rejectAll = useCallback(() => {
|
||||
const newDecisions: Record<string, SuggestionDecision> = { ...decisions }
|
||||
for (const s of suggestions) {
|
||||
if (newDecisions[s.id] !== 'pending') continue
|
||||
newDecisions[s.id] = 'rejected'
|
||||
logDecision(s, 'ai_suggestion_reject')
|
||||
}
|
||||
setDecisions(newDecisions)
|
||||
}, [suggestions, decisions, logDecision])
|
||||
|
||||
const dismiss = useCallback(() => {
|
||||
abortRef.current?.abort()
|
||||
setStatus('idle')
|
||||
setSuggestions([])
|
||||
setDecisions({})
|
||||
undoInfos.current = {}
|
||||
setError(null)
|
||||
}, [])
|
||||
|
||||
/** Recompute staleness for pending suggestions against the latest data. */
|
||||
const isPendingAndStale = useCallback(
|
||||
(s: AiSuggestion) =>
|
||||
decisions[s.id] === 'pending' &&
|
||||
isSuggestionStale(data.corrected_segments, s),
|
||||
[decisions, data.corrected_segments],
|
||||
)
|
||||
|
||||
const pendingCount = suggestions.filter((s) => decisions[s.id] === 'pending').length
|
||||
const acceptedCount = suggestions.filter((s) => decisions[s.id] === 'accepted').length
|
||||
|
||||
return {
|
||||
status,
|
||||
suggestions,
|
||||
decisions,
|
||||
model,
|
||||
cached,
|
||||
error,
|
||||
hasReferences,
|
||||
pendingCount,
|
||||
acceptedCount,
|
||||
run,
|
||||
cancel,
|
||||
accept,
|
||||
reject,
|
||||
undoAccept,
|
||||
acceptAll,
|
||||
rejectAll,
|
||||
dismiss,
|
||||
isPendingAndStale,
|
||||
}
|
||||
}
|
||||
|
||||
export type AutoCorrectController = ReturnType<typeof useAutoCorrect>
|
||||
@@ -76,6 +76,9 @@ function resetStore() {
|
||||
error: null,
|
||||
isInitialized: false,
|
||||
})
|
||||
// The store now mirrors resolved config onto window.__TENANT_CONFIG__ (so lib/api.ts
|
||||
// can read it synchronously). Clear it between tests to keep them isolated.
|
||||
delete (window as { __TENANT_CONFIG__?: unknown }).__TENANT_CONFIG__
|
||||
}
|
||||
|
||||
describe("useTenant store", () => {
|
||||
|
||||
+79
-2
@@ -55,10 +55,45 @@ function getLocaleFromPath(): string {
|
||||
return 'en';
|
||||
}
|
||||
|
||||
function getAuthHeaders(): HeadersInit {
|
||||
const headers: HeadersInit = {
|
||||
/**
|
||||
* Resolve the current white-label tenant id, if any.
|
||||
*
|
||||
* On tenant portals the Cloudflare Pages edge function (frontend/functions/[[path]].ts)
|
||||
* injects `window.__TENANT_CONFIG__` into the HTML before any app JS runs, and the
|
||||
* tenant store (lib/tenant.ts) mirrors the same shape there in dev/preview. Reading it
|
||||
* directly here keeps api.ts free of an import cycle with tenant.ts (which imports
|
||||
* API_BASE_URL from this module).
|
||||
*
|
||||
* Returns null on the consumer build / consumer domain, so no tenant header is sent and
|
||||
* existing consumer behavior is unchanged.
|
||||
*/
|
||||
export function getTenantId(): string | null {
|
||||
if (typeof window === 'undefined') return null;
|
||||
const injected = (window as { __TENANT_CONFIG__?: { tenant?: { id?: string } | null } }).__TENANT_CONFIG__;
|
||||
const id = injected?.tenant?.id;
|
||||
return typeof id === 'string' && id ? id : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Base headers attached to every API request: locale, and the X-Tenant-ID header when
|
||||
* on a white-label tenant portal. The shared backend (api.nomadkaraoke.com) cannot infer
|
||||
* the tenant from the Host (it's not the tenant subdomain) or from the prod-disabled
|
||||
* `?tenant=` query param, so this header is the primary tenant-detection signal that lets
|
||||
* the backend apply tenant config (locked theme, Dropbox path, no YouTube/GDrive).
|
||||
*/
|
||||
function getBaseHeaders(): Record<string, string> {
|
||||
const headers: Record<string, string> = {
|
||||
'Accept-Language': getLocaleFromPath(),
|
||||
};
|
||||
const tenantId = getTenantId();
|
||||
if (tenantId) {
|
||||
headers['X-Tenant-ID'] = tenantId;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
function getAuthHeaders(): HeadersInit {
|
||||
const headers: Record<string, string> = getBaseHeaders();
|
||||
const token = getAccessToken();
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
@@ -473,6 +508,28 @@ export interface CommunityCheckResponse {
|
||||
best_youtube_url: string | null;
|
||||
}
|
||||
|
||||
export type MatchJudgeKind = 'cosmetic' | 'content' | 'ambiguous' | 'none';
|
||||
|
||||
export interface MatchJudgeVerdict {
|
||||
kind: MatchJudgeKind;
|
||||
confident: boolean;
|
||||
canonical_artist: string;
|
||||
canonical_title: string;
|
||||
alternatives: { artist: string; title: string }[];
|
||||
engine: 'deterministic' | 'catalog' | 'ai';
|
||||
reason: string;
|
||||
// Set by a "fast" (catalog-only) pass that couldn't decide — the client should
|
||||
// follow up with a "full" call once the audio confidence tier is known.
|
||||
needs_ai: boolean;
|
||||
}
|
||||
|
||||
export type MatchJudgeStage = 'fast' | 'full';
|
||||
|
||||
export interface MatchJudgeOptions {
|
||||
stage?: MatchJudgeStage;
|
||||
audioConfidenceTier?: number;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
/**
|
||||
* List all jobs
|
||||
@@ -1285,6 +1342,11 @@ export const api = {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
// Carry tenant context so the backend validates the email domain against the
|
||||
// tenant, embeds tenant_id in the magic-link token, and uses the tenant's
|
||||
// sender email + portal URL. Without this, tenant sign-in silently falls back
|
||||
// to the consumer (nomad) flow.
|
||||
...getBaseHeaders(),
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
@@ -1573,6 +1635,21 @@ export const api = {
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
async matchJudge(artist: string, title: string, opts?: MatchJudgeOptions): Promise<MatchJudgeVerdict> {
|
||||
const body: Record<string, unknown> = { artist, title };
|
||||
if (opts?.audioConfidenceTier != null) body.audio_confidence_tier = opts.audioConfidenceTier;
|
||||
if (opts?.stage != null) body.stage = opts.stage;
|
||||
const response = await fetch(`${API_BASE_URL}/api/catalog/match-judge`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...getAuthHeaders(),
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
async changeVisibility(jobId: string, targetVisibility: 'public' | 'private'): Promise<ChangeVisibilityResponse> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/change-visibility`, {
|
||||
method: 'POST',
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* Client for the AI auto-correct suggestions endpoint.
|
||||
*
|
||||
* POST /api/review/{job_id}/auto-correct
|
||||
*
|
||||
* Stateless: posts the client's current working segments + reference lyrics
|
||||
* and returns word-id-keyed suggestions. Nothing is applied server-side —
|
||||
* the reviewer accepts/rejects each suggestion in the UI and persistence
|
||||
* flows through the existing corrections/complete paths.
|
||||
*/
|
||||
import type { LyricsSegment, ReferenceSource } from '@/lib/lyrics-review/types'
|
||||
|
||||
const API_BASE =
|
||||
process.env.NEXT_PUBLIC_API_BASE ?? 'https://api.nomadkaraoke.com'
|
||||
|
||||
export type AiSuggestionOp = 'replace' | 'delete' | 'insert_after'
|
||||
|
||||
export type AiSuggestionCategory =
|
||||
| 'mishearing'
|
||||
| 'grammar'
|
||||
| 'adlib_removal'
|
||||
| 'repeated_chorus_fix'
|
||||
| 'formatting'
|
||||
| 'other'
|
||||
|
||||
export interface AutoCorrectSettings {
|
||||
suggest_adlib_removal: boolean
|
||||
allow_insertions: boolean
|
||||
min_confidence: number
|
||||
/** Query all configured models in parallel and report consensus. */
|
||||
compare_models: boolean
|
||||
}
|
||||
|
||||
export const DEFAULT_AUTO_CORRECT_SETTINGS: AutoCorrectSettings = {
|
||||
suggest_adlib_removal: true,
|
||||
allow_insertions: true,
|
||||
min_confidence: 0,
|
||||
// Always multi-model. Kept in sync with the backend proactive run
|
||||
// (AutoCorrectSettings(compare_models=True)) so the on-load request is a
|
||||
// cache hit. Not user-configurable.
|
||||
compare_models: true,
|
||||
}
|
||||
|
||||
export interface AiSuggestion {
|
||||
id: string
|
||||
op: AiSuggestionOp
|
||||
word_ids: string[]
|
||||
segment_ids: string[]
|
||||
original_text: string
|
||||
new_text: string
|
||||
reason: string
|
||||
category: AiSuggestionCategory
|
||||
confidence: number
|
||||
/** Models that proposed this exact suggestion. */
|
||||
models: string[]
|
||||
/** How many of total_models agreed on this exact suggestion. */
|
||||
consensus: number
|
||||
total_models: number
|
||||
/** Suggestions sharing a conflict_group target overlapping words with
|
||||
* different outcomes — accept at most one per group. */
|
||||
conflict_group: string | null
|
||||
}
|
||||
|
||||
export interface AutoCorrectResponse {
|
||||
suggestions: AiSuggestion[]
|
||||
model: string
|
||||
elapsed_seconds: number
|
||||
settings_applied: AutoCorrectSettings
|
||||
warnings: string[]
|
||||
/** Served from the per-job cache — no AI cost was incurred. */
|
||||
cached: boolean
|
||||
}
|
||||
|
||||
export class AutoCorrectApiError extends Error {
|
||||
readonly status: number
|
||||
|
||||
constructor(status: number, message: string) {
|
||||
super(message)
|
||||
this.name = 'AutoCorrectApiError'
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
export interface AutoCorrectParams {
|
||||
segments: LyricsSegment[]
|
||||
referenceLyrics: Record<string, ReferenceSource>
|
||||
artist?: string
|
||||
title?: string
|
||||
settings: AutoCorrectSettings
|
||||
}
|
||||
|
||||
export async function fetchAutoCorrectSuggestions(
|
||||
jobId: string,
|
||||
params: AutoCorrectParams,
|
||||
signal?: AbortSignal,
|
||||
token?: string,
|
||||
): Promise<AutoCorrectResponse> {
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
if (token) headers.Authorization = `Bearer ${token}`
|
||||
|
||||
const response = await fetch(
|
||||
`${API_BASE}/api/review/${encodeURIComponent(jobId)}/auto-correct`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers,
|
||||
signal,
|
||||
body: JSON.stringify({
|
||||
segments: params.segments,
|
||||
reference_lyrics: params.referenceLyrics,
|
||||
artist: params.artist,
|
||||
title: params.title,
|
||||
settings: params.settings,
|
||||
}),
|
||||
},
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
let detail = `Request failed (${response.status})`
|
||||
try {
|
||||
const body = await response.json()
|
||||
if (body && typeof body.detail === 'string') detail = body.detail
|
||||
} catch {
|
||||
/* swallow JSON parse errors and use generic message */
|
||||
}
|
||||
throw new AutoCorrectApiError(response.status, detail)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
const rawSuggestions: AiSuggestion[] = Array.isArray(data.suggestions)
|
||||
? data.suggestions
|
||||
: []
|
||||
return {
|
||||
suggestions: rawSuggestions.map((s: AiSuggestion) => ({
|
||||
...s,
|
||||
models: s.models ?? [],
|
||||
consensus: s.consensus ?? 1,
|
||||
total_models: s.total_models ?? 1,
|
||||
conflict_group: s.conflict_group ?? null,
|
||||
})),
|
||||
model: data.model,
|
||||
elapsed_seconds: data.elapsed_seconds,
|
||||
settings_applied: data.settings_applied,
|
||||
warnings: data.warnings ?? [],
|
||||
cached: data.cached ?? false,
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -238,6 +238,11 @@ const useTenantStore = create<TenantStore>()((set, get) => ({
|
||||
isInitialized: true,
|
||||
})
|
||||
|
||||
// Mirror to the edge-config global so synchronous, import-cycle-free consumers
|
||||
// (e.g. getTenantId() in lib/api.ts) can read the tenant in dev/preview where the
|
||||
// Cloudflare edge function does not inject __TENANT_CONFIG__.
|
||||
mirrorTenantConfigToWindow(data)
|
||||
|
||||
// Apply tenant branding to CSS variables
|
||||
if (data.tenant) {
|
||||
applyTenantBranding(data.tenant.branding)
|
||||
@@ -256,6 +261,7 @@ const useTenantStore = create<TenantStore>()((set, get) => ({
|
||||
|
||||
setTenant: (tenant, isDefault) => {
|
||||
set({ tenant, isDefault, isInitialized: true })
|
||||
mirrorTenantConfigToWindow({ tenant, is_default: isDefault })
|
||||
if (tenant) {
|
||||
applyTenantBranding(tenant.branding)
|
||||
}
|
||||
@@ -348,6 +354,19 @@ function applyTenantBranding(branding: TenantBranding) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirror the resolved tenant config onto `window.__TENANT_CONFIG__`.
|
||||
*
|
||||
* The Cloudflare edge function injects this global on tenant subdomains in production,
|
||||
* but not in local dev or admin preview (where the tenant is resolved by fetch or
|
||||
* setTenant). Mirroring it here gives lib/api.ts a single synchronous, import-cycle-free
|
||||
* source of truth for attaching the X-Tenant-ID header in every environment.
|
||||
*/
|
||||
function mirrorTenantConfigToWindow(data: TenantConfigResponse) {
|
||||
if (typeof window === "undefined") return
|
||||
;(window as { __TENANT_CONFIG__?: TenantConfigResponse }).__TENANT_CONFIG__ = data
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to get tenant-aware API headers.
|
||||
* Use this when making API calls that need tenant context.
|
||||
|
||||
@@ -533,7 +533,16 @@
|
||||
"pasteUrlButton": "لصق رابط",
|
||||
"urlSupportedSitesHint": "يعمل مع YouTube و Facebook و SoundCloud و TikTok و Vimeo ومئات المواقع الأخرى.",
|
||||
"urlSupportedSitesLink": "عرض جميع المواقع المدعومة",
|
||||
"useThisUrl": "استخدام هذا الرابط"
|
||||
"useThisUrl": "استخدام هذا الرابط",
|
||||
"matchCorrectedTo": "تم التصحيح إلى {value} — لقد كتبت “{typed}”",
|
||||
"matchDidYouMean": "هل تقصد؟",
|
||||
"matchKeepMine": "الاحتفاظ بما كتبته",
|
||||
"matchTidiedTo": "تم التنسيق إلى {value}",
|
||||
"matchUndo": "تراجع",
|
||||
"matchChecking": "جارٍ التحقق من تفاصيل الأغنية…",
|
||||
"matchUseCorrection": "استخدام التصحيح",
|
||||
"matchUseTidied": "استخدام النسخة المنقحة",
|
||||
"matchUsingTyped": "استخدام ما كتبته: {value}"
|
||||
},
|
||||
"jobStatus": {
|
||||
"settingUp": "جاري الإعداد",
|
||||
@@ -683,7 +692,8 @@
|
||||
},
|
||||
"titleCardPreview": {
|
||||
"songTitle": "عنوان الأغنية",
|
||||
"artist": "الفنان"
|
||||
"artist": "الفنان",
|
||||
"loading": "جارٍ تحميل معاينة شاشة العنوان"
|
||||
},
|
||||
"editTrack": {
|
||||
"title": "تعديل المسار المكتمل",
|
||||
@@ -776,7 +786,17 @@
|
||||
"undoFailed": "فشل التراجع",
|
||||
"redoFailed": "فشلت الإعادة",
|
||||
"restoreFailed": "فشلت الاستعادة — قد لا يتم تطبيق بعض التعديلات",
|
||||
"submitFailed": "فشل الإرسال"
|
||||
"submitFailed": "فشل الإرسال",
|
||||
"fadeIn": "ظهور تدريجي",
|
||||
"fadeInSelection": "ظهور تدريجي في المنطقة المحددة",
|
||||
"fadeOut": "تلاشي تدريجي",
|
||||
"fadeOutSelection": "تلاشي تدريجي في المنطقة المحددة",
|
||||
"fadeInDisabledHint": "لإضافة تأثير الظهور التدريجي، حدد منطقة تبدأ من بداية المسار تماماً",
|
||||
"fadeOutDisabledHint": "لإضافة تأثير التلاشي التدريجي، حدد منطقة تنتهي عند نهاية المسار تماماً",
|
||||
"trimEndDisabledHint": "لقص النهاية، حدد منطقة تنتهي عند نهاية المسار تماماً",
|
||||
"trimEndSelection": "إزالة كل شيء بعد التحديد",
|
||||
"trimStartDisabledHint": "لقص البداية، حدد منطقة تبدأ من بداية المسار تماماً",
|
||||
"trimStartSelection": "إزالة كل شيء قبل التحديد"
|
||||
},
|
||||
"audioEditRestore": {
|
||||
"title": "جلسات تعديل الصوت المحفوظة",
|
||||
@@ -803,7 +823,7 @@
|
||||
"acceptAll": "قبول الكل",
|
||||
"revertAll": "تراجع عن الكل",
|
||||
"undoAll": "تراجع عن الكل",
|
||||
"resetAllChanges": "إعادة تعيين جميع التغييرات إلى الكلمات الأصلية المصححة بالذكاء الاصطناعي",
|
||||
"resetAllChanges": "إعادة تعيين جميع التغييرات والعودة إلى الكلمات المصححة الأصلية",
|
||||
"undo": "تراجع",
|
||||
"redo": "إعادة",
|
||||
"findReplace": "بحث/استبدال",
|
||||
@@ -816,7 +836,9 @@
|
||||
"playback": "التشغيل",
|
||||
"audioLoadError": "تعذر تحميل الصوت",
|
||||
"audioStillLoading": "لا يزال الصوت قيد التحميل...",
|
||||
"loadingAudio": "جاري تحميل الصوت..."
|
||||
"loadingAudio": "جاري تحميل الصوت...",
|
||||
"autoCorrect": "التصحيح التلقائي",
|
||||
"autoCorrectDesc": "إنشاء اقتراحات تصحيح من خلال مقارنة التفريغ الصوتي مع الكلمات المرجعية. لن يتم تغيير أي شيء حتى توافق على كل اقتراح."
|
||||
},
|
||||
"guidance": {
|
||||
"showTips": "إظهار النصائح",
|
||||
@@ -1274,6 +1296,52 @@
|
||||
},
|
||||
"toasts": {
|
||||
"customLyricsSaved": "تم تطبيق الكلمات المخصصة. يرجى مزامنة كل مقطع معدل يدوياً لضمان توافق توقيت الكلمات بشكل مثالي."
|
||||
},
|
||||
"autoCorrect": {
|
||||
"accept": "قبول الاقتراح",
|
||||
"acceptAll": "قبول الكل",
|
||||
"accepted": "تم القبول",
|
||||
"adlibRemovalHint": "السماح بالاقتراحات التي تحذف الغناء الخلفي غير الموجود في المراجع",
|
||||
"adlibRemovalLabel": "اقتراح إزالة الارتجالات",
|
||||
"category_adlib_removal": "ارتجال",
|
||||
"category_formatting": "تنسيق",
|
||||
"category_grammar": "قواعد",
|
||||
"category_mishearing": "خطأ سمعي",
|
||||
"category_other": "أخرى",
|
||||
"category_repeated_chorus_fix": "كورس",
|
||||
"collapse": "طي الاقتراحات",
|
||||
"confidenceHint": "مستوى الثقة المطلوب للاقتراح قبل ظهوره",
|
||||
"confidenceLabel": "تصفية الاقتراحات",
|
||||
"confidence_all": "عرض الكل",
|
||||
"confidence_high": "ثقة عالية",
|
||||
"description": "يقارن التصحيح التلقائي التفريغ الصوتي بالمصادر المرجعية ويقترح تعديلات على مستوى الكلمة. يمكنك مراجعة كل اقتراح — ولن يتم تطبيق أي شيء حتى توافق عليه.",
|
||||
"dismiss": "تجاهل الاقتراحات",
|
||||
"expand": "توسيع الاقتراحات",
|
||||
"insertMarker": "إدراج:",
|
||||
"insertionsHint": "السماح بالاقتراحات التي تدرج الكلمات المفقودة في النسخ",
|
||||
"insertionsLabel": "اقتراح الكلمات المفقودة",
|
||||
"noReferences": "لا تتوفر كلمات مرجعية لهذه الأغنية، لذا لا يمكن إنشاء اقتراحات. أضف الكلمات من اللوحة المرجعية أولاً.",
|
||||
"noSuggestions": "لم يتم العثور على أي مشاكل — لا توجد تغييرات مقترحة.",
|
||||
"reject": "رفض الاقتراح",
|
||||
"rejectAll": "رفض الكل",
|
||||
"rejected": "مرفوض",
|
||||
"runButton": "الحصول على اقتراحات",
|
||||
"running": "جاري تحليل الكلمات... يستغرق هذا عادةً بين 15 و 60 ثانية.",
|
||||
"staleHint": "تم تعديل هذه الكلمات بعد إنشاء الاقتراحات، لذا لم يعد هذا الاقتراح صالحاً.",
|
||||
"summary": "{total} اقتراحات · {pending} قيد الانتظار · {accepted} مقبولة",
|
||||
"title": "اقتراحات التصحيح التلقائي",
|
||||
"undo": "التراجع عن هذا الاقتراح",
|
||||
"cancel": "إلغاء",
|
||||
"close": "إغلاق",
|
||||
"confidence_balanced": "متوازن",
|
||||
"compareHint": "أبطأ وأعلى تكلفة، لكنه يوضح الاقتراحات التي تتفق عليها عدة نماذج",
|
||||
"compareLabel": "مقارنة عدة نماذج للذكاء الاصطناعي",
|
||||
"conflictBadge": "بديل",
|
||||
"conflictTooltip": "توجد اقتراحات مختلفة لهذه الكلمات — قبول أحد الخيارات يؤدي إلى رفض الخيارات الأخرى.",
|
||||
"consensusBadge": "{consensus}/{total} من النماذج",
|
||||
"consensusTooltip": "مقترح من: {models}",
|
||||
"cachedBadge": "مخزن مؤقتاً",
|
||||
"cachedTooltip": "تمت الاستعادة من معالجة سابقة لنفس الكلمات — لم يتم احتساب أي تكلفة للذكاء الاصطناعي."
|
||||
}
|
||||
},
|
||||
"instrumentalReview": {
|
||||
@@ -1508,5 +1576,8 @@
|
||||
"estimatedLabel": "تكلفة تقديرية — يتم تأكيد التكلفة النهائية بعد التنزيل",
|
||||
"reconcileTitle": "هذه الأغنية أطول من المتوقع",
|
||||
"cancel": "إلغاء"
|
||||
},
|
||||
"karaokeBackgroundPreview": {
|
||||
"loading": "جارٍ تحميل معاينة الخلفية"
|
||||
}
|
||||
}
|
||||
@@ -533,7 +533,16 @@
|
||||
"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"
|
||||
"useThisUrl": "Utilitza aquest URL",
|
||||
"matchCorrectedTo": "Corregit a {value} — has escrit “{typed}”",
|
||||
"matchDidYouMean": "Volies dir?",
|
||||
"matchKeepMine": "mantenir el que he escrit",
|
||||
"matchTidiedTo": "Ajustat a {value}",
|
||||
"matchUndo": "Desfer",
|
||||
"matchChecking": "Comprovant els detalls de la cançó…",
|
||||
"matchUseCorrection": "utilitza la correcció",
|
||||
"matchUseTidied": "utilitza la versió polida",
|
||||
"matchUsingTyped": "Utilitzant el que has escrit: {value}"
|
||||
},
|
||||
"jobStatus": {
|
||||
"settingUp": "Configurant",
|
||||
@@ -683,7 +692,8 @@
|
||||
},
|
||||
"titleCardPreview": {
|
||||
"songTitle": "Títol de la cançó",
|
||||
"artist": "Artista"
|
||||
"artist": "Artista",
|
||||
"loading": "Carregant la previsualització de la pantalla de títol"
|
||||
},
|
||||
"editTrack": {
|
||||
"title": "Edita la pista completada",
|
||||
@@ -776,7 +786,17 @@
|
||||
"undoFailed": "No s'ha pogut desfer",
|
||||
"redoFailed": "No s'ha pogut refer",
|
||||
"restoreFailed": "La restauració ha fallat — és possible que algunes edicions no s'hagin aplicat",
|
||||
"submitFailed": "L'enviament ha fallat"
|
||||
"submitFailed": "L'enviament ha fallat",
|
||||
"fadeIn": "Fosa d'entrada",
|
||||
"fadeInSelection": "Aplica una fosa d'entrada a la regió seleccionada",
|
||||
"fadeOut": "Fosa de sortida",
|
||||
"fadeOutSelection": "Aplica una fosa de sortida a la regió seleccionada",
|
||||
"fadeInDisabledHint": "Per fer una fosa d'entrada, selecciona una regió que comenci just al principi de la pista",
|
||||
"fadeOutDisabledHint": "Per fer una fosa de sortida, selecciona una regió que acabi just al final de la pista",
|
||||
"trimEndDisabledHint": "Per retallar el final, selecciona una regió que acabi just al final de la pista",
|
||||
"trimEndSelection": "Elimina tot el que hi ha després de la selecció",
|
||||
"trimStartDisabledHint": "Per retallar el principi, selecciona una regió que comenci just al principi de la pista",
|
||||
"trimStartSelection": "Elimina tot el que hi ha abans de la selecció"
|
||||
},
|
||||
"audioEditRestore": {
|
||||
"title": "Sessions d'edició d'àudio desades",
|
||||
@@ -803,7 +823,7 @@
|
||||
"acceptAll": "Accepta-ho tot",
|
||||
"revertAll": "Reverteix-ho tot",
|
||||
"undoAll": "Desfés-ho tot",
|
||||
"resetAllChanges": "Restableix tots els canvis a les lletres originals corregides per IA",
|
||||
"resetAllChanges": "Restableix tots els canvis a la lletra corregida original",
|
||||
"undo": "Desfés",
|
||||
"redo": "Refés",
|
||||
"findReplace": "Cerca/Reemplaça",
|
||||
@@ -816,7 +836,9 @@
|
||||
"playback": "Reproducció",
|
||||
"audioLoadError": "No s'ha pogut carregar l'àudio",
|
||||
"audioStillLoading": "L'àudio encara s'està carregant...",
|
||||
"loadingAudio": "Carregant l'àudio..."
|
||||
"loadingAudio": "Carregant l'àudio...",
|
||||
"autoCorrect": "Autocorrecció",
|
||||
"autoCorrectDesc": "Genera suggeriments de correcció comparant la transcripció amb la lletra de referència. No es canvia res fins que acceptes cada suggeriment."
|
||||
},
|
||||
"guidance": {
|
||||
"showTips": "Mostra els consells",
|
||||
@@ -1274,6 +1296,52 @@
|
||||
},
|
||||
"toasts": {
|
||||
"customLyricsSaved": "Lletra personalitzada aplicada. Sincronitza manualment cada segment editat per assegurar-te que els temps de les paraules són correctes per a la lletra personalitzada."
|
||||
},
|
||||
"autoCorrect": {
|
||||
"accept": "Accepta el suggeriment",
|
||||
"acceptAll": "Accepta-ho tot",
|
||||
"accepted": "Acceptat",
|
||||
"adlibRemovalHint": "Permet suggeriments que eliminin les veus de fons que les referències no tenen",
|
||||
"adlibRemovalLabel": "Suggereix eliminar els adlibs",
|
||||
"category_adlib_removal": "adlib",
|
||||
"category_formatting": "format",
|
||||
"category_grammar": "gramàtica",
|
||||
"category_mishearing": "error d'audició",
|
||||
"category_other": "altres",
|
||||
"category_repeated_chorus_fix": "tornada",
|
||||
"collapse": "Contreu els suggeriments",
|
||||
"confidenceHint": "Quin nivell de confiança ha de tenir un suggeriment abans de mostrar-se",
|
||||
"confidenceLabel": "Filtre de suggeriments",
|
||||
"confidence_all": "Mostra-ho tot",
|
||||
"confidence_high": "Certesa alta",
|
||||
"description": "L'autocorrecció compara la lletra transcrita amb les fonts de referència i suggereix correccions a nivell de paraula. Tu revises cada suggeriment — no s'aplica res fins que ho acceptes.",
|
||||
"dismiss": "Descarta els suggeriments",
|
||||
"expand": "Desplega els suggeriments",
|
||||
"insertMarker": "insereix:",
|
||||
"insertionsHint": "Permet suggeriments que insereixin paraules que la transcripció ha omès",
|
||||
"insertionsLabel": "Suggereix paraules que falten",
|
||||
"noReferences": "No hi ha cap lletra de referència disponible per a aquesta cançó, així que no es poden generar suggeriments. Afegeix primer la lletra des del panell de referència.",
|
||||
"noSuggestions": "No s'han trobat problemes — no hi ha cap canvi suggerit.",
|
||||
"reject": "Rebutja el suggeriment",
|
||||
"rejectAll": "Rebutja-ho tot",
|
||||
"rejected": "Rebutjat",
|
||||
"runButton": "Obtén suggeriments",
|
||||
"running": "S'està analitzant la lletra... això sol trigar entre 15 i 60 segons.",
|
||||
"staleHint": "Aquestes paraules s'han editat des que es van generar els suggeriments, per la qual cosa aquest suggeriment ja no és vàlid.",
|
||||
"summary": "{total} suggeriments · {pending} pendents · {accepted} acceptats",
|
||||
"title": "Suggeriments d'autocorrecció",
|
||||
"undo": "Desfés aquest suggeriment",
|
||||
"cancel": "Cancel·la",
|
||||
"close": "Tanca",
|
||||
"confidence_balanced": "Equilibrat",
|
||||
"compareHint": "Més lent i més car, però mostra en quins suggeriments coincideixen diversos models",
|
||||
"compareLabel": "Compara diversos models d'IA",
|
||||
"conflictBadge": "variant",
|
||||
"conflictTooltip": "Hi ha diferents suggeriments per a aquestes paraules — si acceptes una variant, es rebutgen les altres.",
|
||||
"consensusBadge": "{consensus}/{total} models",
|
||||
"consensusTooltip": "Proposat per: {models}",
|
||||
"cachedBadge": "en memòria cau",
|
||||
"cachedTooltip": "Restaurat a partir d'una execució anterior amb la mateixa lletra — no s'ha generat cap cost d'IA."
|
||||
}
|
||||
},
|
||||
"instrumentalReview": {
|
||||
@@ -1508,5 +1576,8 @@
|
||||
"estimatedLabel": "Aproximat — el cost final es confirmarà després de la descàrrega",
|
||||
"reconcileTitle": "Aquesta cançó és més llarga del que s'esperava",
|
||||
"cancel": "Cancel·la"
|
||||
},
|
||||
"karaokeBackgroundPreview": {
|
||||
"loading": "Carregant la previsualització del fons"
|
||||
}
|
||||
}
|
||||
@@ -533,7 +533,16 @@
|
||||
"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"
|
||||
"useThisUrl": "Použít tuto URL",
|
||||
"matchCorrectedTo": "Opraveno na {value} — zadal jsi „{typed}“",
|
||||
"matchDidYouMean": "Měl jsi na mysli?",
|
||||
"matchKeepMine": "ponechat můj text",
|
||||
"matchTidiedTo": "Upraveno na {value}",
|
||||
"matchUndo": "Zpět",
|
||||
"matchChecking": "Kontrola detailů písně…",
|
||||
"matchUseCorrection": "použít opravu",
|
||||
"matchUseTidied": "použít upravenou verzi",
|
||||
"matchUsingTyped": "Používám to, co jsi zadal: {value}"
|
||||
},
|
||||
"jobStatus": {
|
||||
"settingUp": "Nastavování",
|
||||
@@ -683,7 +692,8 @@
|
||||
},
|
||||
"titleCardPreview": {
|
||||
"songTitle": "Název písničky",
|
||||
"artist": "Interpret"
|
||||
"artist": "Interpret",
|
||||
"loading": "Načítání náhledu úvodní obrazovky"
|
||||
},
|
||||
"editTrack": {
|
||||
"title": "Upravit dokončenou stopu",
|
||||
@@ -776,7 +786,17 @@
|
||||
"undoFailed": "Krok zpět selhal",
|
||||
"redoFailed": "Krok znovu selhal",
|
||||
"restoreFailed": "Obnovení selhalo — některé úpravy možná nebyly aplikovány",
|
||||
"submitFailed": "Odeslání selhalo"
|
||||
"submitFailed": "Odeslání selhalo",
|
||||
"fadeIn": "Postupné zesílení",
|
||||
"fadeInSelection": "Postupné zesílení vybraného úseku",
|
||||
"fadeOut": "Postupné zeslabení",
|
||||
"fadeOutSelection": "Postupné zeslabení vybraného úseku",
|
||||
"fadeInDisabledHint": "Pro postupné zesílení vyber úsek, který začíná na úplném začátku stopy",
|
||||
"fadeOutDisabledHint": "Pro postupné zeslabení vyber úsek, který končí na úplném konci stopy",
|
||||
"trimEndDisabledHint": "Pro oříznutí konce vyber úsek, který končí na úplném konci stopy",
|
||||
"trimEndSelection": "Odstranit vše za výběrem",
|
||||
"trimStartDisabledHint": "Pro oříznutí začátku vyber úsek, který začíná na úplném začátku stopy",
|
||||
"trimStartSelection": "Odstranit vše před výběrem"
|
||||
},
|
||||
"audioEditRestore": {
|
||||
"title": "Uložené relace úprav zvuku",
|
||||
@@ -803,7 +823,7 @@
|
||||
"acceptAll": "Přijmout vše",
|
||||
"revertAll": "Vrátit vše",
|
||||
"undoAll": "Vrátit vše zpět",
|
||||
"resetAllChanges": "Resetovat všechny změny zpět na původní text opravený AI",
|
||||
"resetAllChanges": "Vrátit všechny změny zpět na původní opravený text",
|
||||
"undo": "Zpět",
|
||||
"redo": "Znovu",
|
||||
"findReplace": "Najít/Nahradit",
|
||||
@@ -816,7 +836,9 @@
|
||||
"playback": "Přehrávání",
|
||||
"audioLoadError": "Nepodařilo se načíst audio",
|
||||
"audioStillLoading": "Audio se stále načítá...",
|
||||
"loadingAudio": "Načítání audia..."
|
||||
"loadingAudio": "Načítání audia...",
|
||||
"autoCorrect": "Automatická oprava",
|
||||
"autoCorrectDesc": "Vygenerovat návrhy oprav porovnáním přepisu s referenčním textem. Nic se nezmění, dokud každý návrh nepřijmeš."
|
||||
},
|
||||
"guidance": {
|
||||
"showTips": "Zobrazit tipy",
|
||||
@@ -1274,6 +1296,52 @@
|
||||
},
|
||||
"toasts": {
|
||||
"customLyricsSaved": "Vlastní text byl aplikován. Ručně synchronizuj každý upravený segment, aby bylo zajištěno správné načasování slov pro upravený text."
|
||||
},
|
||||
"autoCorrect": {
|
||||
"accept": "Přijmout návrh",
|
||||
"acceptAll": "Přijmout vše",
|
||||
"accepted": "Přijato",
|
||||
"adlibRemovalHint": "Povolit návrhy, které odstraní doprovodné vokály, které v referenčním textu chybí",
|
||||
"adlibRemovalLabel": "Navrhnout odstranění adlibů",
|
||||
"category_adlib_removal": "adlib",
|
||||
"category_formatting": "formát",
|
||||
"category_grammar": "gramatika",
|
||||
"category_mishearing": "přeslechnutí",
|
||||
"category_other": "ostatní",
|
||||
"category_repeated_chorus_fix": "refrén",
|
||||
"collapse": "Sbalit návrhy",
|
||||
"confidenceHint": "Jak vysoká musí být jistota návrhu, než se zobrazí",
|
||||
"confidenceLabel": "Filtr návrhů",
|
||||
"confidence_all": "Zobrazit vše",
|
||||
"confidence_high": "Vysoká jistota",
|
||||
"description": "Automatická oprava porovnává přepsaný text s referenčními zdroji a navrhuje opravy na úrovni slov. Každý návrh si zkontroluješ — nic se neaplikuje, dokud ho nepřijmeš.",
|
||||
"dismiss": "Skrýt návrhy",
|
||||
"expand": "Rozbalit návrhy",
|
||||
"insertMarker": "vložit:",
|
||||
"insertionsHint": "Povolit návrhy, které vkládají slova, která v přepisu chybí",
|
||||
"insertionsLabel": "Navrhnout chybějící slova",
|
||||
"noReferences": "Pro tuto píseň nejsou k dispozici žádné referenční texty, takže nelze vygenerovat návrhy. Nejprve přidej text z referenčního panelu.",
|
||||
"noSuggestions": "Nebyly nalezeny žádné problémy — nejsou navrženy žádné změny.",
|
||||
"reject": "Odmítnout návrh",
|
||||
"rejectAll": "Odmítnout vše",
|
||||
"rejected": "Odmítnuto",
|
||||
"runButton": "Získat návrhy",
|
||||
"running": "Analyzuji text… obvykle to trvá 15–60 sekund.",
|
||||
"staleHint": "Tato slova byla upravena od chvíle, kdy byly návrhy vygenerovány, takže tento návrh již neplatí.",
|
||||
"summary": "{total} návrhů · {pending} čeká · {accepted} přijato",
|
||||
"title": "Návrhy automatické opravy",
|
||||
"undo": "Vzít tento návrh zpět",
|
||||
"cancel": "Zrušit",
|
||||
"close": "Zavřít",
|
||||
"confidence_balanced": "Vyvážená",
|
||||
"compareHint": "Pomalejší a dražší, ale ukáže, na kterých návrzích se shodne více modelů",
|
||||
"compareLabel": "Porovnat více AI modelů",
|
||||
"conflictBadge": "varianta",
|
||||
"conflictTooltip": "Pro tato slova existují různé návrhy — přijetím jedné varianty odmítneš ostatní.",
|
||||
"consensusBadge": "{consensus}/{total} modelů",
|
||||
"consensusTooltip": "Navrženo: {models}",
|
||||
"cachedBadge": "z mezipaměti",
|
||||
"cachedTooltip": "Obnoveno z předchozího zpracování stejného textu — nevznikly žádné náklady na AI."
|
||||
}
|
||||
},
|
||||
"instrumentalReview": {
|
||||
@@ -1508,5 +1576,8 @@
|
||||
"estimatedLabel": "Odhad — konečná cena se potvrdí po stažení",
|
||||
"reconcileTitle": "Tato píseň je delší, než jsme čekali",
|
||||
"cancel": "Zrušit"
|
||||
},
|
||||
"karaokeBackgroundPreview": {
|
||||
"loading": "Načítání náhledu pozadí"
|
||||
}
|
||||
}
|
||||
@@ -533,7 +533,16 @@
|
||||
"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"
|
||||
"useThisUrl": "Brug denne URL",
|
||||
"matchCorrectedTo": "Rettet til {value} — du skrev “{typed}”",
|
||||
"matchDidYouMean": "Mente du?",
|
||||
"matchKeepMine": "behold det, jeg skrev",
|
||||
"matchTidiedTo": "Finpudset til {value}",
|
||||
"matchUndo": "Fortryd",
|
||||
"matchChecking": "Tjekker sangdetaljer…",
|
||||
"matchUseCorrection": "brug rettelsen",
|
||||
"matchUseTidied": "brug den tilrettede version",
|
||||
"matchUsingTyped": "Bruger det, du indtastede: {value}"
|
||||
},
|
||||
"jobStatus": {
|
||||
"settingUp": "Sætter op",
|
||||
@@ -683,7 +692,8 @@
|
||||
},
|
||||
"titleCardPreview": {
|
||||
"songTitle": "Sangtitel",
|
||||
"artist": "Kunstner"
|
||||
"artist": "Kunstner",
|
||||
"loading": "Indlæser forhåndsvisning af titelskærm"
|
||||
},
|
||||
"editTrack": {
|
||||
"title": "Rediger fuldført nummer",
|
||||
@@ -776,7 +786,17 @@
|
||||
"undoFailed": "Fortryd mislykkedes",
|
||||
"redoFailed": "Gendan mislykkedes",
|
||||
"restoreFailed": "Gendannelse mislykkedes — nogle redigeringer er muligvis ikke blevet anvendt",
|
||||
"submitFailed": "Indsendelse mislykkedes"
|
||||
"submitFailed": "Indsendelse mislykkedes",
|
||||
"fadeIn": "Fade ind",
|
||||
"fadeInSelection": "Fade ind over det valgte område",
|
||||
"fadeOut": "Fade ud",
|
||||
"fadeOutSelection": "Fade ud over det valgte område",
|
||||
"fadeInDisabledHint": "For at fade ind skal du vælge et område, der begynder helt i starten af sporet",
|
||||
"fadeOutDisabledHint": "For at fade ud skal du vælge et område, der slutter helt for enden af sporet",
|
||||
"trimEndDisabledHint": "For at beskære slutningen skal du vælge et område, der slutter helt for enden af sporet",
|
||||
"trimEndSelection": "Fjern alt efter markeringen",
|
||||
"trimStartDisabledHint": "For at beskære starten skal du vælge et område, der begynder helt i starten af sporet",
|
||||
"trimStartSelection": "Fjern alt før markeringen"
|
||||
},
|
||||
"audioEditRestore": {
|
||||
"title": "Gemte lydredigeringssessioner",
|
||||
@@ -803,7 +823,7 @@
|
||||
"acceptAll": "Accepter alle",
|
||||
"revertAll": "Gendan alle",
|
||||
"undoAll": "Fortryd alle",
|
||||
"resetAllChanges": "Nulstil alle ændringer tilbage til de originale AI-rettede sangtekster",
|
||||
"resetAllChanges": "Nulstil alle ændringer tilbage til den oprindelige rettede sangtekst",
|
||||
"undo": "Fortryd",
|
||||
"redo": "Gendan",
|
||||
"findReplace": "Find/Erstat",
|
||||
@@ -816,7 +836,9 @@
|
||||
"playback": "Afspilning",
|
||||
"audioLoadError": "Kunne ikke indlæse lyd",
|
||||
"audioStillLoading": "Lyden indlæses stadig...",
|
||||
"loadingAudio": "Indlæser lyd..."
|
||||
"loadingAudio": "Indlæser lyd...",
|
||||
"autoCorrect": "Autokorrektur",
|
||||
"autoCorrectDesc": "Generer forslag til rettelser ved at sammenligne transskriptionen med referenceteksten. Intet ændres, før du accepterer hvert forslag."
|
||||
},
|
||||
"guidance": {
|
||||
"showTips": "Vis tips",
|
||||
@@ -1274,6 +1296,52 @@
|
||||
},
|
||||
"toasts": {
|
||||
"customLyricsSaved": "Tilpasset sangtekst anvendt. Synkroniser manuelt hvert redigeret segment for at sikre, at ordtimingen passer til den tilpassede sangtekst."
|
||||
},
|
||||
"autoCorrect": {
|
||||
"accept": "Accepter forslag",
|
||||
"acceptAll": "Accepter alle",
|
||||
"accepted": "Accepteret",
|
||||
"adlibRemovalHint": "Tillad forslag, der sletter korvokal, som ikke findes i referencerne",
|
||||
"adlibRemovalLabel": "Foreslå at fjerne adlibs",
|
||||
"category_adlib_removal": "adlib",
|
||||
"category_formatting": "format",
|
||||
"category_grammar": "grammatik",
|
||||
"category_mishearing": "fejlhørt",
|
||||
"category_other": "andet",
|
||||
"category_repeated_chorus_fix": "omkvæd",
|
||||
"collapse": "Skjul forslag",
|
||||
"confidenceHint": "Hvor sikkert et forslag skal være, før det vises",
|
||||
"confidenceLabel": "Forslagsfilter",
|
||||
"confidence_all": "Vis alle",
|
||||
"confidence_high": "Høj sikkerhed",
|
||||
"description": "Autokorrektur sammenligner den transskriberede sangtekst med referencekilderne og foreslår rettelser på ordniveau. Du gennemgår hvert forslag — intet anvendes, før du accepterer det.",
|
||||
"dismiss": "Fjern forslag",
|
||||
"expand": "Udvid forslag",
|
||||
"insertMarker": "indsæt:",
|
||||
"insertionsHint": "Tillad forslag, der indsætter ord, som transskriptionen overså",
|
||||
"insertionsLabel": "Foreslå manglende ord",
|
||||
"noReferences": "Der er ingen referencetekster tilgængelige for denne sang, så der kan ikke genereres forslag. Tilføj en sangtekst fra referencepanelet først.",
|
||||
"noSuggestions": "Ingen problemer fundet — der er ingen foreslåede ændringer.",
|
||||
"reject": "Afvis forslag",
|
||||
"rejectAll": "Afvis alle",
|
||||
"rejected": "Afvist",
|
||||
"runButton": "Hent forslag",
|
||||
"running": "Analyserer tekst… dette tager normalt 15–60 sekunder.",
|
||||
"staleHint": "Disse ord er blevet redigeret, siden forslagene blev genereret, så dette forslag gælder ikke længere.",
|
||||
"summary": "{total} forslag · {pending} afventer · {accepted} accepteret",
|
||||
"title": "Forslag til autokorrektur",
|
||||
"undo": "Fortryd dette forslag",
|
||||
"cancel": "Annuller",
|
||||
"close": "Luk",
|
||||
"confidence_balanced": "Balanceret",
|
||||
"compareHint": "Langsommere og koster mere, men viser, hvilke forslag flere modeller er enige om",
|
||||
"compareLabel": "Sammenlign flere AI-modeller",
|
||||
"conflictBadge": "variant",
|
||||
"conflictTooltip": "Der er forskellige forslag til disse ord — hvis du accepterer én variant, afvises de andre.",
|
||||
"consensusBadge": "{consensus}/{total} modeller",
|
||||
"consensusTooltip": "Foreslået af: {models}",
|
||||
"cachedBadge": "cachet",
|
||||
"cachedTooltip": "Gendannet fra en tidligere kørsel med de samme sangtekster — der påløb ingen AI-omkostninger."
|
||||
}
|
||||
},
|
||||
"instrumentalReview": {
|
||||
@@ -1508,5 +1576,8 @@
|
||||
"estimatedLabel": "Anslået — endelig pris bekræftes efter download",
|
||||
"reconcileTitle": "Denne sang er længere end forventet",
|
||||
"cancel": "Annuller"
|
||||
},
|
||||
"karaokeBackgroundPreview": {
|
||||
"loading": "Indlæser forhåndsvisning af baggrund"
|
||||
}
|
||||
}
|
||||
@@ -533,7 +533,16 @@
|
||||
"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"
|
||||
"useThisUrl": "Diese URL verwenden",
|
||||
"matchCorrectedTo": "Korrigiert zu {value} – du hast „{typed}“ eingegeben",
|
||||
"matchDidYouMean": "Meintest du?",
|
||||
"matchKeepMine": "meine Eingabe behalten",
|
||||
"matchTidiedTo": "Bereinigt zu {value}",
|
||||
"matchUndo": "Rückgängig",
|
||||
"matchChecking": "Songdetails werden überprüft…",
|
||||
"matchUseCorrection": "Korrektur verwenden",
|
||||
"matchUseTidied": "bereinigte Version verwenden",
|
||||
"matchUsingTyped": "Verwende deine Eingabe: {value}"
|
||||
},
|
||||
"jobStatus": {
|
||||
"settingUp": "Richte ein",
|
||||
@@ -683,7 +692,8 @@
|
||||
},
|
||||
"titleCardPreview": {
|
||||
"songTitle": "Songtitel",
|
||||
"artist": "Künstler"
|
||||
"artist": "Künstler",
|
||||
"loading": "Titelbildschirm-Vorschau wird geladen"
|
||||
},
|
||||
"editTrack": {
|
||||
"title": "Abgeschlossenen Track bearbeiten",
|
||||
@@ -776,7 +786,17 @@
|
||||
"undoFailed": "Rückgängig machen fehlgeschlagen",
|
||||
"redoFailed": "Wiederholen fehlgeschlagen",
|
||||
"restoreFailed": "Wiederherstellung fehlgeschlagen — einige Bearbeitungen wurden möglicherweise nicht angewendet",
|
||||
"submitFailed": "Einreichen fehlgeschlagen"
|
||||
"submitFailed": "Einreichen fehlgeschlagen",
|
||||
"fadeIn": "Einblenden",
|
||||
"fadeInSelection": "Über den ausgewählten Bereich einblenden",
|
||||
"fadeOut": "Ausblenden",
|
||||
"fadeOutSelection": "Über den ausgewählten Bereich ausblenden",
|
||||
"fadeInDisabledHint": "Um einzublenden, wähle einen Bereich, der ganz am Anfang des Tracks beginnt",
|
||||
"fadeOutDisabledHint": "Um auszublenden, wähle einen Bereich, der ganz am Ende des Tracks endet",
|
||||
"trimEndDisabledHint": "Um das Ende abzuschneiden, wähle einen Bereich, der ganz am Ende des Tracks endet",
|
||||
"trimEndSelection": "Alles nach der Auswahl entfernen",
|
||||
"trimStartDisabledHint": "Um den Anfang abzuschneiden, wähle einen Bereich, der ganz am Anfang des Tracks beginnt",
|
||||
"trimStartSelection": "Alles vor der Auswahl entfernen"
|
||||
},
|
||||
"audioEditRestore": {
|
||||
"title": "Gespeicherte Audiobearbeitungs-Sitzungen",
|
||||
@@ -803,7 +823,7 @@
|
||||
"acceptAll": "Alle akzeptieren",
|
||||
"revertAll": "Alle verwerfen",
|
||||
"undoAll": "Alle rückgängig machen",
|
||||
"resetAllChanges": "Alle Änderungen auf den ursprünglichen KI-korrigierten Text zurücksetzen",
|
||||
"resetAllChanges": "Alle Änderungen auf den ursprünglich korrigierten Text zurücksetzen",
|
||||
"undo": "Rückgängig",
|
||||
"redo": "Wiederholen",
|
||||
"findReplace": "Suchen/Ersetzen",
|
||||
@@ -816,7 +836,9 @@
|
||||
"playback": "Wiedergabe",
|
||||
"audioLoadError": "Audio konnte nicht geladen werden",
|
||||
"audioStillLoading": "Audio wird noch geladen...",
|
||||
"loadingAudio": "Audio wird geladen..."
|
||||
"loadingAudio": "Audio wird geladen...",
|
||||
"autoCorrect": "Autokorrektur",
|
||||
"autoCorrectDesc": "Generiere Korrekturvorschläge, indem du die Transkription mit dem Referenztext vergleichst. Nichts wird geändert, bis du jeden Vorschlag akzeptierst."
|
||||
},
|
||||
"guidance": {
|
||||
"showTips": "Tipps anzeigen",
|
||||
@@ -1274,6 +1296,52 @@
|
||||
},
|
||||
"toasts": {
|
||||
"customLyricsSaved": "Benutzerdefinierter Text angewendet. Synchronisiere jedes bearbeitete Segment manuell, um sicherzustellen, dass das Wort-Timing für den neuen Text stimmt."
|
||||
},
|
||||
"autoCorrect": {
|
||||
"accept": "Vorschlag akzeptieren",
|
||||
"acceptAll": "Alle akzeptieren",
|
||||
"accepted": "Akzeptiert",
|
||||
"adlibRemovalHint": "Erlaube Vorschläge, die Hintergrundgesang entfernen, der im Referenztext nicht vorkommt",
|
||||
"adlibRemovalLabel": "Entfernen von Adlibs vorschlagen",
|
||||
"category_adlib_removal": "Adlib",
|
||||
"category_formatting": "Format",
|
||||
"category_grammar": "Grammatik",
|
||||
"category_mishearing": "Falsch erkannt",
|
||||
"category_other": "Sonstiges",
|
||||
"category_repeated_chorus_fix": "Refrain",
|
||||
"collapse": "Vorschläge einklappen",
|
||||
"confidenceHint": "Wie sicher ein Vorschlag sein muss, bevor er angezeigt wird",
|
||||
"confidenceLabel": "Vorschlagsfilter",
|
||||
"confidence_all": "Alle anzeigen",
|
||||
"confidence_high": "Hohe Sicherheit",
|
||||
"description": "Die Autokorrektur vergleicht den transkribierten Text mit den Referenzquellen und schlägt Korrekturen auf Wortebene vor. Du überprüfst jeden Vorschlag — nichts wird angewendet, bis du ihn akzeptierst.",
|
||||
"dismiss": "Vorschläge verwerfen",
|
||||
"expand": "Vorschläge ausklappen",
|
||||
"insertMarker": "einfügen:",
|
||||
"insertionsHint": "Erlaube Vorschläge, die Wörter einfügen, die bei der Transkription übersehen wurden",
|
||||
"insertionsLabel": "Fehlende Wörter vorschlagen",
|
||||
"noReferences": "Für diesen Song ist kein Referenztext verfügbar, daher können keine Vorschläge generiert werden. Füge zuerst einen Text über das Referenz-Panel hinzu.",
|
||||
"noSuggestions": "Keine Probleme gefunden — es gibt keine Änderungsvorschläge.",
|
||||
"reject": "Vorschlag ablehnen",
|
||||
"rejectAll": "Alle ablehnen",
|
||||
"rejected": "Abgelehnt",
|
||||
"runButton": "Vorschläge abrufen",
|
||||
"running": "Text wird analysiert… dies dauert normalerweise 15–60 Sekunden.",
|
||||
"staleHint": "Diese Wörter wurden bearbeitet, seit die Vorschläge generiert wurden, daher gilt dieser Vorschlag nicht mehr.",
|
||||
"summary": "{total} Vorschläge · {pending} ausstehend · {accepted} akzeptiert",
|
||||
"title": "Autokorrektur-Vorschläge",
|
||||
"undo": "Diesen Vorschlag rückgängig machen",
|
||||
"cancel": "Abbrechen",
|
||||
"close": "Schließen",
|
||||
"confidence_balanced": "Ausgewogen",
|
||||
"compareHint": "Langsamer und teurer, zeigt aber, bei welchen Vorschlägen mehrere Modelle übereinstimmen",
|
||||
"compareLabel": "Mehrere KI-Modelle vergleichen",
|
||||
"conflictBadge": "Variante",
|
||||
"conflictTooltip": "Es gibt verschiedene Vorschläge für diese Wörter — wenn du eine Variante akzeptierst, werden die anderen abgelehnt.",
|
||||
"consensusBadge": "{consensus}/{total} Modelle",
|
||||
"consensusTooltip": "Vorgeschlagen von: {models}",
|
||||
"cachedBadge": "zwischengespeichert",
|
||||
"cachedTooltip": "Wiederhergestellt aus einem vorherigen Durchlauf mit demselben Text — es sind keine KI-Kosten angefallen."
|
||||
}
|
||||
},
|
||||
"instrumentalReview": {
|
||||
@@ -1508,5 +1576,8 @@
|
||||
"estimatedLabel": "Geschätzt — endgültige Kosten werden nach dem Download bestätigt",
|
||||
"reconcileTitle": "Dieser Song ist länger als erwartet",
|
||||
"cancel": "Abbrechen"
|
||||
},
|
||||
"karaokeBackgroundPreview": {
|
||||
"loading": "Hintergrundvorschau wird geladen"
|
||||
}
|
||||
}
|
||||
@@ -533,7 +533,16 @@
|
||||
"pasteUrlButton": "Επικόλλησε έναν σύνδεσμο",
|
||||
"urlSupportedSitesHint": "Λειτουργεί με YouTube, Facebook, SoundCloud, TikTok, Vimeo και εκατοντάδες άλλους ιστότοπους.",
|
||||
"urlSupportedSitesLink": "Δες όλους τους υποστηριζόμενους ιστότοπους",
|
||||
"useThisUrl": "Χρησιμοποίησε αυτό το URL"
|
||||
"useThisUrl": "Χρησιμοποίησε αυτό το URL",
|
||||
"matchCorrectedTo": "Διορθώθηκε σε {value} — πληκτρολόγησες “{typed}”",
|
||||
"matchDidYouMean": "Μήπως εννοούσες;",
|
||||
"matchKeepMine": "κράτα αυτό που πληκτρολόγησα",
|
||||
"matchTidiedTo": "Διαμορφώθηκε σε {value}",
|
||||
"matchUndo": "Αναίρεση",
|
||||
"matchChecking": "Έλεγχος λεπτομερειών τραγουδιού…",
|
||||
"matchUseCorrection": "χρησιμοποίησε τη διόρθωση",
|
||||
"matchUseTidied": "χρησιμοποίησε την καθαρισμένη έκδοση",
|
||||
"matchUsingTyped": "Χρησιμοποιείται αυτό που πληκτρολόγησες: {value}"
|
||||
},
|
||||
"jobStatus": {
|
||||
"settingUp": "Ρύθμιση",
|
||||
@@ -683,7 +692,8 @@
|
||||
},
|
||||
"titleCardPreview": {
|
||||
"songTitle": "Τίτλος Τραγουδιού",
|
||||
"artist": "Καλλιτέχνης"
|
||||
"artist": "Καλλιτέχνης",
|
||||
"loading": "Φόρτωση προεπισκόπησης οθόνης τίτλου"
|
||||
},
|
||||
"editTrack": {
|
||||
"title": "Επεξεργασία Ολοκληρωμένου Κομματιού",
|
||||
@@ -776,7 +786,17 @@
|
||||
"undoFailed": "Η αναίρεση απέτυχε",
|
||||
"redoFailed": "Η επανάληψη απέτυχε",
|
||||
"restoreFailed": "Η επαναφορά απέτυχε — κάποιες επεξεργασίες μπορεί να μην έχουν εφαρμοστεί",
|
||||
"submitFailed": "Η υποβολή απέτυχε"
|
||||
"submitFailed": "Η υποβολή απέτυχε",
|
||||
"fadeIn": "Fade In",
|
||||
"fadeInSelection": "Εφάρμοσε fade in στην επιλεγμένη περιοχή",
|
||||
"fadeOut": "Fade Out",
|
||||
"fadeOutSelection": "Εφάρμοσε fade out στην επιλεγμένη περιοχή",
|
||||
"fadeInDisabledHint": "Για fade in, επίλεξε μια περιοχή που ξεκινά ακριβώς στην αρχή του κομματιού",
|
||||
"fadeOutDisabledHint": "Για fade out, επίλεξε μια περιοχή που τελειώνει ακριβώς στο τέλος του κομματιού",
|
||||
"trimEndDisabledHint": "Για να περικόψεις το τέλος, επίλεξε μια περιοχή που τελειώνει ακριβώς στο τέλος του κομματιού",
|
||||
"trimEndSelection": "Αφαίρεσε τα πάντα μετά την επιλογή",
|
||||
"trimStartDisabledHint": "Για να περικόψεις την αρχή, επίλεξε μια περιοχή που ξεκινά ακριβώς στην αρχή του κομματιού",
|
||||
"trimStartSelection": "Αφαίρεσε τα πάντα πριν από την επιλογή"
|
||||
},
|
||||
"audioEditRestore": {
|
||||
"title": "Αποθηκευμένες Συνεδρίες Επεξεργασίας Ήχου",
|
||||
@@ -803,7 +823,7 @@
|
||||
"acceptAll": "Αποδοχή Όλων",
|
||||
"revertAll": "Επαναφορά Όλων",
|
||||
"undoAll": "Αναίρεση Όλων",
|
||||
"resetAllChanges": "Επαναφορά όλων των αλλαγών πίσω στους αρχικούς στίχους που διορθώθηκαν από το AI",
|
||||
"resetAllChanges": "Επαναφορά όλων των αλλαγών στους αρχικούς διορθωμένους στίχους",
|
||||
"undo": "Αναίρεση",
|
||||
"redo": "Επανάληψη",
|
||||
"findReplace": "Εύρεση/Αντικατάσταση",
|
||||
@@ -816,7 +836,9 @@
|
||||
"playback": "Αναπαραγωγή",
|
||||
"audioLoadError": "Δεν ήταν δυνατή η φόρτωση του ήχου",
|
||||
"audioStillLoading": "Ο ήχος φορτώνει ακόμα...",
|
||||
"loadingAudio": "Φόρτωση ήχου..."
|
||||
"loadingAudio": "Φόρτωση ήχου...",
|
||||
"autoCorrect": "Αυτόματη διόρθωση",
|
||||
"autoCorrectDesc": "Δημιούργησε προτάσεις διόρθωσης συγκρίνοντας τη μεταγραφή με τους στίχους αναφοράς. Τίποτα δεν αλλάζει μέχρι να αποδεχτείς κάθε πρόταση."
|
||||
},
|
||||
"guidance": {
|
||||
"showTips": "Εμφάνιση συμβουλών",
|
||||
@@ -1274,6 +1296,52 @@
|
||||
},
|
||||
"toasts": {
|
||||
"customLyricsSaved": "Οι προσαρμοσμένοι στίχοι εφαρμόστηκαν. Συγχρόνισε χειροκίνητα κάθε επεξεργασμένο τμήμα για να βεβαιωθείς ότι ο χρονισμός των λέξεων είναι σωστός για τους προσαρμοσμένους στίχους."
|
||||
},
|
||||
"autoCorrect": {
|
||||
"accept": "Αποδοχή πρότασης",
|
||||
"acceptAll": "Αποδοχή όλων",
|
||||
"accepted": "Έγινε αποδοχή",
|
||||
"adlibRemovalHint": "Επίτρεψε προτάσεις που διαγράφουν δεύτερα φωνητικά τα οποία δεν υπάρχουν στις πηγές αναφοράς",
|
||||
"adlibRemovalLabel": "Πρόταση αφαίρεσης adlibs",
|
||||
"category_adlib_removal": "adlib",
|
||||
"category_formatting": "μορφοποίηση",
|
||||
"category_grammar": "γραμματική",
|
||||
"category_mishearing": "παρανόηση",
|
||||
"category_other": "άλλο",
|
||||
"category_repeated_chorus_fix": "ρεφρέν",
|
||||
"collapse": "Σύμπτυξη προτάσεων",
|
||||
"confidenceHint": "Πόσο βέβαιη πρέπει να είναι μια πρόταση πριν εμφανιστεί",
|
||||
"confidenceLabel": "Φίλτρο προτάσεων",
|
||||
"confidence_all": "Εμφάνιση όλων",
|
||||
"confidence_high": "Υψηλή βεβαιότητα",
|
||||
"description": "Η αυτόματη διόρθωση συγκρίνει τους μεταγραμμένους στίχους με τις πηγές αναφοράς και προτείνει διορθώσεις σε επίπεδο λέξης. Ελέγχεις κάθε πρόταση — τίποτα δεν εφαρμόζεται μέχρι να την αποδεχτείς.",
|
||||
"dismiss": "Αγνόηση προτάσεων",
|
||||
"expand": "Ανάπτυξη προτάσεων",
|
||||
"insertMarker": "εισαγωγή:",
|
||||
"insertionsHint": "Επίτρεψε προτάσεις που εισάγουν λέξεις που παραλείφθηκαν κατά τη μεταγραφή",
|
||||
"insertionsLabel": "Πρόταση λέξεων που λείπουν",
|
||||
"noReferences": "Δεν υπάρχουν διαθέσιμοι στίχοι αναφοράς για αυτό το τραγούδι, επομένως δεν μπορούν να δημιουργηθούν προτάσεις. Πρόσθεσε πρώτα στίχους από τον πίνακα αναφοράς.",
|
||||
"noSuggestions": "Δεν βρέθηκαν προβλήματα — δεν υπάρχουν προτεινόμενες αλλαγές.",
|
||||
"reject": "Απόρριψη πρότασης",
|
||||
"rejectAll": "Απόρριψη όλων",
|
||||
"rejected": "Απορρίφθηκε",
|
||||
"runButton": "Λήψη προτάσεων",
|
||||
"running": "Ανάλυση στίχων… αυτό συνήθως διαρκεί 15–60 δευτερόλεπτα.",
|
||||
"staleHint": "Αυτές οι λέξεις επεξεργάστηκαν μετά τη δημιουργία των προτάσεων, επομένως αυτή η πρόταση δεν ισχύει πλέον.",
|
||||
"summary": "{total} προτάσεις · {pending} σε εκκρεμότητα · {accepted} αποδεκτές",
|
||||
"title": "Προτάσεις αυτόματης διόρθωσης",
|
||||
"undo": "Αναίρεση αυτής της πρότασης",
|
||||
"cancel": "Ακύρωση",
|
||||
"close": "Κλείσιμο",
|
||||
"confidence_balanced": "Ισορροπημένη",
|
||||
"compareHint": "Πιο αργό και κοστίζει περισσότερο, αλλά δείχνει σε ποιες προτάσεις συμφωνούν πολλαπλά μοντέλα",
|
||||
"compareLabel": "Σύγκρινε πολλαπλά μοντέλα AI",
|
||||
"conflictBadge": "παραλλαγή",
|
||||
"conflictTooltip": "Υπάρχουν διαφορετικές προτάσεις για αυτές τις λέξεις — η αποδοχή μιας παραλλαγής απορρίπτει τις υπόλοιπες.",
|
||||
"consensusBadge": "{consensus}/{total} μοντέλα",
|
||||
"consensusTooltip": "Προτάθηκε από: {models}",
|
||||
"cachedBadge": "προσωρινά αποθηκευμένο",
|
||||
"cachedTooltip": "Ανακτήθηκε από προηγούμενη επεξεργασία των ίδιων στίχων — δεν υπήρξε χρέωση AI."
|
||||
}
|
||||
},
|
||||
"instrumentalReview": {
|
||||
@@ -1508,5 +1576,8 @@
|
||||
"estimatedLabel": "Εκτιμώμενο — το τελικό κόστος επιβεβαιώνεται μετά τη λήψη",
|
||||
"reconcileTitle": "Αυτό το τραγούδι διαρκεί περισσότερο από το αναμενόμενο",
|
||||
"cancel": "Ακύρωση"
|
||||
},
|
||||
"karaokeBackgroundPreview": {
|
||||
"loading": "Φόρτωση προεπισκόπησης φόντου"
|
||||
}
|
||||
}
|
||||
@@ -470,6 +470,15 @@
|
||||
"createAnother": "Create Another",
|
||||
"noCreditsWarning": "You have no credits remaining. Buy credits to create new karaoke videos.",
|
||||
"buyCredits": "Buy Credits",
|
||||
"matchTidiedTo": "Tidied to {value}",
|
||||
"matchKeepMine": "keep what I typed",
|
||||
"matchCorrectedTo": "Corrected to {value} — you typed “{typed}”",
|
||||
"matchUndo": "Undo",
|
||||
"matchUsingTyped": "Using what you typed: {value}",
|
||||
"matchUseTidied": "use tidied version",
|
||||
"matchUseCorrection": "use the correction",
|
||||
"matchChecking": "Checking song details…",
|
||||
"matchDidYouMean": "Did you mean?",
|
||||
"weFindBestAudio": "We find the best audio",
|
||||
"uploadAFile": "upload a file",
|
||||
"youtubeUrl": "YouTube URL",
|
||||
@@ -683,7 +692,11 @@
|
||||
},
|
||||
"titleCardPreview": {
|
||||
"songTitle": "Song Title",
|
||||
"artist": "Artist"
|
||||
"artist": "Artist",
|
||||
"loading": "Loading title screen preview"
|
||||
},
|
||||
"karaokeBackgroundPreview": {
|
||||
"loading": "Loading background preview"
|
||||
},
|
||||
"editTrack": {
|
||||
"title": "Edit Completed Track",
|
||||
@@ -753,6 +766,16 @@
|
||||
"trimEnd": "Trim End",
|
||||
"cutSelection": "Cut selection (Delete)",
|
||||
"muteSelection": "Mute selection (M)",
|
||||
"fadeIn": "Fade In",
|
||||
"fadeOut": "Fade Out",
|
||||
"fadeInSelection": "Fade in over the selected region",
|
||||
"fadeOutSelection": "Fade out over the selected region",
|
||||
"trimStartSelection": "Remove everything before the selection",
|
||||
"trimEndSelection": "Remove everything after the selection",
|
||||
"trimStartDisabledHint": "To trim the start, select a region that begins at the very start of the track",
|
||||
"trimEndDisabledHint": "To trim the end, select a region that ends at the very end of the track",
|
||||
"fadeInDisabledHint": "To fade in, select a region that begins at the very start of the track",
|
||||
"fadeOutDisabledHint": "To fade out, select a region that ends at the very end of the track",
|
||||
"undo": "Undo (Ctrl+Z)",
|
||||
"redo": "Redo (Ctrl+Shift+Z)",
|
||||
"playPause": "Play/Pause (Space)",
|
||||
@@ -803,7 +826,7 @@
|
||||
"acceptAll": "Accept All",
|
||||
"revertAll": "Revert All",
|
||||
"undoAll": "Undo All",
|
||||
"resetAllChanges": "Reset all changes back to the original AI-corrected lyrics",
|
||||
"resetAllChanges": "Reset all changes back to the original corrected lyrics",
|
||||
"undo": "Undo",
|
||||
"redo": "Redo",
|
||||
"findReplace": "Find/Replace",
|
||||
@@ -816,7 +839,9 @@
|
||||
"playback": "Playback",
|
||||
"loadingAudio": "Loading audio...",
|
||||
"audioStillLoading": "Audio is still loading...",
|
||||
"audioLoadError": "Couldn't load audio"
|
||||
"audioLoadError": "Couldn't load audio",
|
||||
"autoCorrect": "Auto-correct",
|
||||
"autoCorrectDesc": "Generate correction suggestions by comparing the transcription against the reference lyrics. Nothing is changed until you accept each suggestion."
|
||||
},
|
||||
"guidance": {
|
||||
"showTips": "Show tips",
|
||||
@@ -1274,6 +1299,52 @@
|
||||
"legendSinger": "Singer:",
|
||||
"keyboardHintSegment": "With a segment focused, press 1 / 2 / B",
|
||||
"resetOverridesTooltip": "Reset word overrides in this segment"
|
||||
},
|
||||
"autoCorrect": {
|
||||
"title": "Auto-correct suggestions",
|
||||
"description": "Auto-correct compares the transcribed lyrics against the reference sources and suggests word-level fixes. You review every suggestion — nothing is applied until you accept it.",
|
||||
"noReferences": "No reference lyrics are available for this song, so suggestions can’t be generated. Add lyrics from the reference panel first.",
|
||||
"running": "Analyzing lyrics… this usually takes 15–60 seconds.",
|
||||
"adlibRemovalLabel": "Suggest removing adlibs",
|
||||
"adlibRemovalHint": "Allow suggestions that delete backing vocals the references don’t have",
|
||||
"insertionsLabel": "Suggest missing words",
|
||||
"insertionsHint": "Allow suggestions that insert words the transcription missed",
|
||||
"confidenceLabel": "Suggestion filter",
|
||||
"confidenceHint": "How confident a suggestion must be before it’s shown",
|
||||
"confidence_all": "Show all",
|
||||
"confidence_balanced": "Balanced",
|
||||
"confidence_high": "High confidence",
|
||||
"cancel": "Cancel",
|
||||
"close": "Close",
|
||||
"runButton": "Get suggestions",
|
||||
"noSuggestions": "No issues found — there are no suggested changes.",
|
||||
"summary": "{total} suggestions · {pending} pending · {accepted} accepted",
|
||||
"acceptAll": "Accept all",
|
||||
"rejectAll": "Reject all",
|
||||
"expand": "Expand suggestions",
|
||||
"collapse": "Collapse suggestions",
|
||||
"dismiss": "Dismiss suggestions",
|
||||
"insertMarker": "insert:",
|
||||
"staleHint": "These words were edited since suggestions were generated, so this suggestion no longer applies.",
|
||||
"accept": "Accept suggestion",
|
||||
"reject": "Reject suggestion",
|
||||
"accepted": "Accepted",
|
||||
"rejected": "Rejected",
|
||||
"undo": "Undo this suggestion",
|
||||
"category_mishearing": "misheard",
|
||||
"category_grammar": "grammar",
|
||||
"category_adlib_removal": "adlib",
|
||||
"category_repeated_chorus_fix": "chorus",
|
||||
"category_formatting": "format",
|
||||
"category_other": "other",
|
||||
"compareLabel": "Compare multiple AI models",
|
||||
"compareHint": "Slower and costs more, but shows which suggestions multiple models agree on",
|
||||
"consensusBadge": "{consensus}/{total} models",
|
||||
"consensusTooltip": "Proposed by: {models}",
|
||||
"conflictBadge": "variant",
|
||||
"conflictTooltip": "There are different suggestions for these words — accepting one variant rejects the others.",
|
||||
"cachedBadge": "cached",
|
||||
"cachedTooltip": "Restored from a previous run on the same lyrics — no AI cost was incurred."
|
||||
}
|
||||
},
|
||||
"instrumentalReview": {
|
||||
|
||||
@@ -533,7 +533,16 @@
|
||||
"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"
|
||||
"useThisUrl": "Usar esta URL",
|
||||
"matchCorrectedTo": "Corregido a {value} — escribiste “{typed}”",
|
||||
"matchDidYouMean": "¿Quisiste decir?",
|
||||
"matchKeepMine": "mantener lo que escribí",
|
||||
"matchTidiedTo": "Ajustado a {value}",
|
||||
"matchUndo": "Deshacer",
|
||||
"matchChecking": "Revisando los detalles de la canción…",
|
||||
"matchUseCorrection": "usar la corrección",
|
||||
"matchUseTidied": "usar la versión arreglada",
|
||||
"matchUsingTyped": "Usando lo que escribiste: {value}"
|
||||
},
|
||||
"jobStatus": {
|
||||
"settingUp": "Configurando",
|
||||
@@ -683,7 +692,8 @@
|
||||
},
|
||||
"titleCardPreview": {
|
||||
"songTitle": "Título de la canción",
|
||||
"artist": "Artista"
|
||||
"artist": "Artista",
|
||||
"loading": "Cargando vista previa de la pantalla de título"
|
||||
},
|
||||
"editTrack": {
|
||||
"title": "Editar pista completada",
|
||||
@@ -776,7 +786,17 @@
|
||||
"undoFailed": "Error al deshacer",
|
||||
"redoFailed": "Error al rehacer",
|
||||
"restoreFailed": "Error al restaurar — algunas ediciones pueden no haberse aplicado",
|
||||
"submitFailed": "Error al enviar"
|
||||
"submitFailed": "Error al enviar",
|
||||
"fadeIn": "Fundido de entrada",
|
||||
"fadeInSelection": "Aplicar fundido de entrada en la región seleccionada",
|
||||
"fadeOut": "Fundido de salida",
|
||||
"fadeOutSelection": "Aplicar fundido de salida en la región seleccionada",
|
||||
"fadeInDisabledHint": "Para hacer un fundido de entrada, selecciona una región que comience justo al principio de la pista",
|
||||
"fadeOutDisabledHint": "Para hacer un fundido de salida, selecciona una región que termine justo al final de la pista",
|
||||
"trimEndDisabledHint": "Para recortar el final, selecciona una región que termine justo al final de la pista",
|
||||
"trimEndSelection": "Eliminar todo después de la selección",
|
||||
"trimStartDisabledHint": "Para recortar el principio, selecciona una región que comience justo al principio de la pista",
|
||||
"trimStartSelection": "Eliminar todo antes de la selección"
|
||||
},
|
||||
"audioEditRestore": {
|
||||
"title": "Sesiones de edición de audio guardadas",
|
||||
@@ -803,7 +823,7 @@
|
||||
"acceptAll": "Aceptar todo",
|
||||
"revertAll": "Revertir todo",
|
||||
"undoAll": "Deshacer todo",
|
||||
"resetAllChanges": "Restablecer todos los cambios a las letras originales corregidas por IA",
|
||||
"resetAllChanges": "Restablecer todos los cambios a las letras corregidas originales",
|
||||
"undo": "Deshacer",
|
||||
"redo": "Rehacer",
|
||||
"findReplace": "Buscar/Reemplazar",
|
||||
@@ -816,7 +836,9 @@
|
||||
"playback": "Reproducción",
|
||||
"audioLoadError": "No se pudo cargar el audio",
|
||||
"audioStillLoading": "El audio aún se está cargando...",
|
||||
"loadingAudio": "Cargando audio..."
|
||||
"loadingAudio": "Cargando audio...",
|
||||
"autoCorrect": "Autocorrección",
|
||||
"autoCorrectDesc": "Genera sugerencias de corrección comparando la transcripción con las letras de referencia. No se cambia nada hasta que aceptas cada sugerencia."
|
||||
},
|
||||
"guidance": {
|
||||
"showTips": "Mostrar consejos",
|
||||
@@ -1274,6 +1296,52 @@
|
||||
},
|
||||
"toasts": {
|
||||
"customLyricsSaved": "Letras personalizadas aplicadas. Sincroniza manualmente cada segmento editado para asegurar que los tiempos de las palabras sean correctos para las letras personalizadas."
|
||||
},
|
||||
"autoCorrect": {
|
||||
"accept": "Aceptar sugerencia",
|
||||
"acceptAll": "Aceptar todas",
|
||||
"accepted": "Aceptada",
|
||||
"adlibRemovalHint": "Permitir sugerencias que eliminen coros que las referencias no tienen",
|
||||
"adlibRemovalLabel": "Sugerir eliminar improvisaciones",
|
||||
"category_adlib_removal": "improvisación",
|
||||
"category_formatting": "formato",
|
||||
"category_grammar": "gramática",
|
||||
"category_mishearing": "mal escuchada",
|
||||
"category_other": "otro",
|
||||
"category_repeated_chorus_fix": "estribillo",
|
||||
"collapse": "Contraer sugerencias",
|
||||
"confidenceHint": "Qué nivel de confianza debe tener una sugerencia para mostrarse",
|
||||
"confidenceLabel": "Filtro de sugerencias",
|
||||
"confidence_all": "Mostrar todas",
|
||||
"confidence_high": "Alta confianza",
|
||||
"description": "La autocorrección compara las letras transcritas con las fuentes de referencia y sugiere correcciones a nivel de palabra. Revisas cada sugerencia — no se aplica nada hasta que la aceptas.",
|
||||
"dismiss": "Descartar sugerencias",
|
||||
"expand": "Expandir sugerencias",
|
||||
"insertMarker": "insertar:",
|
||||
"insertionsHint": "Permitir sugerencias que inserten palabras que la transcripción omitió",
|
||||
"insertionsLabel": "Sugerir palabras faltantes",
|
||||
"noReferences": "No hay letras de referencia disponibles para esta canción, por lo que no se pueden generar sugerencias. Primero añade letras desde el panel de referencia.",
|
||||
"noSuggestions": "No se encontraron problemas — no hay cambios sugeridos.",
|
||||
"reject": "Rechazar sugerencia",
|
||||
"rejectAll": "Rechazar todas",
|
||||
"rejected": "Rechazada",
|
||||
"runButton": "Obtener sugerencias",
|
||||
"running": "Analizando letras… esto suele tardar entre 15 y 60 segundos.",
|
||||
"staleHint": "Estas palabras fueron editadas desde que se generaron las sugerencias, por lo que esta sugerencia ya no es válida.",
|
||||
"summary": "{total} sugerencias · {pending} pendientes · {accepted} aceptadas",
|
||||
"title": "Sugerencias de autocorrección",
|
||||
"undo": "Deshacer esta sugerencia",
|
||||
"cancel": "Cancelar",
|
||||
"close": "Cerrar",
|
||||
"confidence_balanced": "Equilibrada",
|
||||
"compareHint": "Es más lento y cuesta más, pero muestra en qué sugerencias coinciden varios modelos",
|
||||
"compareLabel": "Comparar varios modelos de IA",
|
||||
"conflictBadge": "variante",
|
||||
"conflictTooltip": "Hay diferentes sugerencias para estas palabras — al aceptar una variante se rechazan las demás.",
|
||||
"consensusBadge": "{consensus}/{total} modelos",
|
||||
"consensusTooltip": "Propuesto por: {models}",
|
||||
"cachedBadge": "en caché",
|
||||
"cachedTooltip": "Restaurado de una ejecución anterior con las mismas letras — no generó costos de IA."
|
||||
}
|
||||
},
|
||||
"instrumentalReview": {
|
||||
@@ -1508,5 +1576,8 @@
|
||||
"estimatedLabel": "Estimado — el costo final se confirmará después de la descarga",
|
||||
"reconcileTitle": "Esta canción es más larga de lo esperado",
|
||||
"cancel": "Cancelar"
|
||||
},
|
||||
"karaokeBackgroundPreview": {
|
||||
"loading": "Cargando vista previa del fondo"
|
||||
}
|
||||
}
|
||||
@@ -533,7 +533,16 @@
|
||||
"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"
|
||||
"useThisUrl": "Käytä tätä osoitetta",
|
||||
"matchCorrectedTo": "Korjattu muotoon {value} — kirjoitit ”{typed}”",
|
||||
"matchDidYouMean": "Tarkoititko?",
|
||||
"matchKeepMine": "säilytä kirjoittamani",
|
||||
"matchTidiedTo": "Siistitty muotoon {value}",
|
||||
"matchUndo": "Kumoa",
|
||||
"matchChecking": "Tarkistetaan kappaleen tietoja…",
|
||||
"matchUseCorrection": "käytä korjausta",
|
||||
"matchUseTidied": "käytä siistittyä versiota",
|
||||
"matchUsingTyped": "Käytetään kirjoittamaasi: {value}"
|
||||
},
|
||||
"jobStatus": {
|
||||
"settingUp": "Asetetaan",
|
||||
@@ -683,7 +692,8 @@
|
||||
},
|
||||
"titleCardPreview": {
|
||||
"songTitle": "Kappaleen nimi",
|
||||
"artist": "Esittäjä"
|
||||
"artist": "Esittäjä",
|
||||
"loading": "Ladataan otsikkonäytön esikatselua"
|
||||
},
|
||||
"editTrack": {
|
||||
"title": "Muokkaa valmista raitaa",
|
||||
@@ -776,7 +786,17 @@
|
||||
"undoFailed": "Kumoaminen epäonnistui",
|
||||
"redoFailed": "Uudelleentekeminen epäonnistui",
|
||||
"restoreFailed": "Palauttaminen epäonnistui — joitain muokkauksia ei ehkä ole sovellettu",
|
||||
"submitFailed": "Lähetys epäonnistui"
|
||||
"submitFailed": "Lähetys epäonnistui",
|
||||
"fadeIn": "Häivytä sisään",
|
||||
"fadeInSelection": "Häivytä sisään valitulla alueella",
|
||||
"fadeOut": "Häivytä ulos",
|
||||
"fadeOutSelection": "Häivytä ulos valitulla alueella",
|
||||
"fadeInDisabledHint": "Jos haluat lisätä sisäänhäivytyksen, valitse alue, joka alkaa aivan raidan alusta",
|
||||
"fadeOutDisabledHint": "Jos haluat lisätä uloshäivytyksen, valitse alue, joka päättyy aivan raidan loppuun",
|
||||
"trimEndDisabledHint": "Jos haluat leikata lopun, valitse alue, joka päättyy aivan raidan loppuun",
|
||||
"trimEndSelection": "Poista kaikki valinnan jälkeen",
|
||||
"trimStartDisabledHint": "Jos haluat leikata alun, valitse alue, joka alkaa aivan raidan alusta",
|
||||
"trimStartSelection": "Poista kaikki ennen valintaa"
|
||||
},
|
||||
"audioEditRestore": {
|
||||
"title": "Tallennetut äänimuokkausistunnot",
|
||||
@@ -803,7 +823,7 @@
|
||||
"acceptAll": "Hyväksy kaikki",
|
||||
"revertAll": "Palauta kaikki",
|
||||
"undoAll": "Kumoa kaikki",
|
||||
"resetAllChanges": "Palauta kaikki muutokset takaisin alkuperäisiin tekoälyn korjaamiin sanoituksiin",
|
||||
"resetAllChanges": "Peru kaikki muutokset ja palauta alkuperäiset korjatut sanoitukset",
|
||||
"undo": "Kumoa",
|
||||
"redo": "Tee uudelleen",
|
||||
"findReplace": "Etsi/Korvaa",
|
||||
@@ -816,7 +836,9 @@
|
||||
"playback": "Toisto",
|
||||
"audioLoadError": "Ääntä ei voitu ladata",
|
||||
"audioStillLoading": "Ääni latautuu yhä...",
|
||||
"loadingAudio": "Ladataan ääntä..."
|
||||
"loadingAudio": "Ladataan ääntä...",
|
||||
"autoCorrect": "Automaattinen korjaus",
|
||||
"autoCorrectDesc": "Luo korjausehdotuksia vertaamalla litterointia vertailusanoituksiin. Mitään ei muuteta ennen kuin hyväksyt jokaisen ehdotuksen."
|
||||
},
|
||||
"guidance": {
|
||||
"showTips": "Näytä vinkit",
|
||||
@@ -1274,6 +1296,52 @@
|
||||
},
|
||||
"toasts": {
|
||||
"customLyricsSaved": "Mukautetut sanoitukset otettu käyttöön. Synkronoi jokainen muokattu segmentti manuaalisesti varmistaaksesi, että sanojen ajoitukset sopivat mukautettuihin sanoituksiin."
|
||||
},
|
||||
"autoCorrect": {
|
||||
"accept": "Hyväksy ehdotus",
|
||||
"acceptAll": "Hyväksy kaikki",
|
||||
"accepted": "Hyväksytty",
|
||||
"adlibRemovalHint": "Salli ehdotukset, jotka poistavat taustalauluja, joita ei ole viitesanoituksissa",
|
||||
"adlibRemovalLabel": "Ehdotukset adlibien poistamisesta",
|
||||
"category_adlib_removal": "adlib",
|
||||
"category_formatting": "muotoilu",
|
||||
"category_grammar": "kielioppi",
|
||||
"category_mishearing": "väärin kuultu",
|
||||
"category_other": "muu",
|
||||
"category_repeated_chorus_fix": "kertosäe",
|
||||
"collapse": "Pienennä ehdotukset",
|
||||
"confidenceHint": "Kuinka varma ehdotuksen pitää olla, jotta se näytetään",
|
||||
"confidenceLabel": "Ehdotusten suodatin",
|
||||
"confidence_all": "Näytä kaikki",
|
||||
"confidence_high": "Korkea varmuus",
|
||||
"description": "Automaattinen korjaus vertaa litteroituja sanoituksia vertailulähteisiin ja ehdottaa sanakohtaisia korjauksia. Käyt läpi jokaisen ehdotuksen — mitään ei oteta käyttöön ennen kuin hyväksyt sen.",
|
||||
"dismiss": "Ohita ehdotukset",
|
||||
"expand": "Laajenna ehdotukset",
|
||||
"insertMarker": "lisää:",
|
||||
"insertionsHint": "Salli ehdotukset, jotka lisäävät transkriptiosta puuttuvia sanoja",
|
||||
"insertionsLabel": "Ehdotukset puuttuvien sanojen lisäämisestä",
|
||||
"noReferences": "Tälle kappaleelle ei ole saatavilla vertailusanoituksia, joten ehdotuksia ei voida luoda. Lisää sanoitukset ensin vertailupaneelista.",
|
||||
"noSuggestions": "Ongelmia ei löytynyt — ei ehdotettuja muutoksia.",
|
||||
"reject": "Hylkää ehdotus",
|
||||
"rejectAll": "Hylkää kaikki",
|
||||
"rejected": "Hylätty",
|
||||
"runButton": "Hae ehdotuksia",
|
||||
"running": "Analysoidaan sanoituksia… tässä kestää yleensä 15–60 sekuntia.",
|
||||
"staleHint": "Näitä sanoja on muokattu sen jälkeen, kun ehdotukset luotiin, joten tämä ehdotus ei enää päde.",
|
||||
"summary": "{total} ehdotusta · {pending} odottaa · {accepted} hyväksytty",
|
||||
"title": "Automaattisen korjauksen ehdotukset",
|
||||
"undo": "Kumoa tämä ehdotus",
|
||||
"cancel": "Peruuta",
|
||||
"close": "Sulje",
|
||||
"confidence_balanced": "Tasapainoinen",
|
||||
"compareHint": "Hitaampi ja kalliimpi, mutta näyttää, mistä ehdotuksista useampi malli on samaa mieltä",
|
||||
"compareLabel": "Vertaile useita tekoälymalleja",
|
||||
"conflictBadge": "vaihtoehto",
|
||||
"conflictTooltip": "Näille sanoille on eri ehdotuksia — yhden vaihtoehdon hyväksyminen hylkää muut.",
|
||||
"consensusBadge": "{consensus}/{total} mallia",
|
||||
"consensusTooltip": "Ehdottanut: {models}",
|
||||
"cachedBadge": "välimuistissa",
|
||||
"cachedTooltip": "Palautettu aiemmasta ajosta samoilla sanoituksilla — tekoälykustannuksia ei syntynyt."
|
||||
}
|
||||
},
|
||||
"instrumentalReview": {
|
||||
@@ -1508,5 +1576,8 @@
|
||||
"estimatedLabel": "Arvioitu — lopullinen hinta vahvistetaan latauksen jälkeen",
|
||||
"reconcileTitle": "Tämä kappale on odotettua pidempi",
|
||||
"cancel": "Peruuta"
|
||||
},
|
||||
"karaokeBackgroundPreview": {
|
||||
"loading": "Ladataan taustan esikatselua"
|
||||
}
|
||||
}
|
||||
@@ -533,7 +533,16 @@
|
||||
"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"
|
||||
"useThisUrl": "Utiliser cette URL",
|
||||
"matchCorrectedTo": "Corrigé en {value} — tu as tapé « {typed} »",
|
||||
"matchDidYouMean": "Tu voulais dire ?",
|
||||
"matchKeepMine": "garder ce que j'ai tapé",
|
||||
"matchTidiedTo": "Ajusté en {value}",
|
||||
"matchUndo": "Annuler",
|
||||
"matchChecking": "Vérification des détails de la chanson…",
|
||||
"matchUseCorrection": "utiliser la correction",
|
||||
"matchUseTidied": "utiliser la version nettoyée",
|
||||
"matchUsingTyped": "Utilisation de ce que tu as tapé : {value}"
|
||||
},
|
||||
"jobStatus": {
|
||||
"settingUp": "Configuration",
|
||||
@@ -683,7 +692,8 @@
|
||||
},
|
||||
"titleCardPreview": {
|
||||
"songTitle": "Titre de la chanson",
|
||||
"artist": "Artiste"
|
||||
"artist": "Artiste",
|
||||
"loading": "Chargement de l'aperçu de l'écran titre"
|
||||
},
|
||||
"editTrack": {
|
||||
"title": "Modifier la piste terminée",
|
||||
@@ -776,7 +786,17 @@
|
||||
"undoFailed": "Échec de l'annulation",
|
||||
"redoFailed": "Échec du rétablissement",
|
||||
"restoreFailed": "Échec de la restauration — certaines modifications peuvent ne pas avoir été appliquées",
|
||||
"submitFailed": "Échec de la soumission"
|
||||
"submitFailed": "Échec de la soumission",
|
||||
"fadeIn": "Fondu entrant",
|
||||
"fadeInSelection": "Fondu entrant sur la zone sélectionnée",
|
||||
"fadeOut": "Fondu sortant",
|
||||
"fadeOutSelection": "Fondu sortant sur la zone sélectionnée",
|
||||
"fadeInDisabledHint": "Pour faire un fondu en ouverture, sélectionne une région qui commence tout au début de la piste",
|
||||
"fadeOutDisabledHint": "Pour faire un fondu en fermeture, sélectionne une région qui se termine tout à la fin de la piste",
|
||||
"trimEndDisabledHint": "Pour couper la fin, sélectionne une région qui se termine tout à la fin de la piste",
|
||||
"trimEndSelection": "Tout supprimer après la sélection",
|
||||
"trimStartDisabledHint": "Pour couper le début, sélectionne une région qui commence tout au début de la piste",
|
||||
"trimStartSelection": "Tout supprimer avant la sélection"
|
||||
},
|
||||
"audioEditRestore": {
|
||||
"title": "Sessions d'édition audio sauvegardées",
|
||||
@@ -803,7 +823,7 @@
|
||||
"acceptAll": "Tout accepter",
|
||||
"revertAll": "Tout annuler",
|
||||
"undoAll": "Tout défaire",
|
||||
"resetAllChanges": "Réinitialiser toutes les modifications aux paroles originales corrigées par l'IA",
|
||||
"resetAllChanges": "Réinitialiser toutes les modifications pour revenir aux paroles corrigées d'origine",
|
||||
"undo": "Annuler",
|
||||
"redo": "Rétablir",
|
||||
"findReplace": "Chercher/Remplacer",
|
||||
@@ -816,7 +836,9 @@
|
||||
"playback": "Lecture",
|
||||
"audioLoadError": "Impossible de charger l'audio",
|
||||
"audioStillLoading": "L'audio est toujours en cours de chargement...",
|
||||
"loadingAudio": "Chargement de l'audio..."
|
||||
"loadingAudio": "Chargement de l'audio...",
|
||||
"autoCorrect": "Correction automatique",
|
||||
"autoCorrectDesc": "Génère des suggestions de correction en comparant la transcription aux paroles de référence. Rien n'est modifié tant que tu n'as pas accepté chaque suggestion."
|
||||
},
|
||||
"guidance": {
|
||||
"showTips": "Afficher les conseils",
|
||||
@@ -1274,6 +1296,52 @@
|
||||
},
|
||||
"toasts": {
|
||||
"customLyricsSaved": "Paroles personnalisées appliquées. Synchronise manuellement chaque segment modifié pour t'assurer que le timing des mots est correct."
|
||||
},
|
||||
"autoCorrect": {
|
||||
"accept": "Accepter la suggestion",
|
||||
"acceptAll": "Tout accepter",
|
||||
"accepted": "Accepté",
|
||||
"adlibRemovalHint": "Autoriser les suggestions qui suppriment les voix de fond absentes des références",
|
||||
"adlibRemovalLabel": "Suggérer la suppression des adlibs",
|
||||
"category_adlib_removal": "adlib",
|
||||
"category_formatting": "format",
|
||||
"category_grammar": "grammaire",
|
||||
"category_mishearing": "mal compris",
|
||||
"category_other": "autre",
|
||||
"category_repeated_chorus_fix": "refrain",
|
||||
"collapse": "Réduire les suggestions",
|
||||
"confidenceHint": "Le niveau de certitude requis pour qu'une suggestion soit affichée",
|
||||
"confidenceLabel": "Filtre de suggestions",
|
||||
"confidence_all": "Tout afficher",
|
||||
"confidence_high": "Certitude élevée",
|
||||
"description": "La correction automatique compare les paroles transcrites aux sources de référence et suggère des corrections mot par mot. Tu examines chaque suggestion — rien n'est appliqué tant que tu ne l'as pas acceptée.",
|
||||
"dismiss": "Ignorer les suggestions",
|
||||
"expand": "Développer les suggestions",
|
||||
"insertMarker": "insérer :",
|
||||
"insertionsHint": "Autoriser les suggestions qui insèrent les mots manquants dans la transcription",
|
||||
"insertionsLabel": "Suggérer les mots manquants",
|
||||
"noReferences": "Il n'y a pas de paroles de référence disponibles pour cette chanson, les suggestions ne peuvent donc pas être générées. Ajoute d'abord des paroles depuis le panneau de référence.",
|
||||
"noSuggestions": "Aucun problème trouvé — il n'y a aucune modification suggérée.",
|
||||
"reject": "Rejeter la suggestion",
|
||||
"rejectAll": "Tout rejeter",
|
||||
"rejected": "Rejeté",
|
||||
"runButton": "Obtenir des suggestions",
|
||||
"running": "Analyse des paroles… cela prend généralement 15 à 60 secondes.",
|
||||
"staleHint": "Ces mots ont été modifiés depuis la génération des suggestions, celle-ci ne s'applique donc plus.",
|
||||
"summary": "{total} suggestions · {pending} en attente · {accepted} acceptées",
|
||||
"title": "Suggestions de correction automatique",
|
||||
"undo": "Annuler cette suggestion",
|
||||
"cancel": "Annuler",
|
||||
"close": "Fermer",
|
||||
"confidence_balanced": "Équilibrée",
|
||||
"compareHint": "Plus lent et plus cher, mais montre les suggestions sur lesquelles plusieurs modèles s'accordent",
|
||||
"compareLabel": "Comparer plusieurs modèles d'IA",
|
||||
"conflictBadge": "variante",
|
||||
"conflictTooltip": "Plusieurs suggestions sont proposées pour ces mots — en accepter une rejette les autres.",
|
||||
"consensusBadge": "{consensus}/{total} modèles",
|
||||
"consensusTooltip": "Proposé par : {models}",
|
||||
"cachedBadge": "en cache",
|
||||
"cachedTooltip": "Restauré depuis un traitement précédent sur les mêmes paroles — aucun coût d'IA n'a été engagé."
|
||||
}
|
||||
},
|
||||
"instrumentalReview": {
|
||||
@@ -1508,5 +1576,8 @@
|
||||
"estimatedLabel": "Estimé — coût final confirmé après le téléchargement",
|
||||
"reconcileTitle": "Cette chanson est plus longue que prévu",
|
||||
"cancel": "Annuler"
|
||||
},
|
||||
"karaokeBackgroundPreview": {
|
||||
"loading": "Chargement de l'aperçu de l'arrière-plan"
|
||||
}
|
||||
}
|
||||
@@ -533,7 +533,16 @@
|
||||
"pasteUrlButton": "הדבקת קישור",
|
||||
"urlSupportedSitesHint": "עובד עם YouTube, Facebook, SoundCloud, TikTok, Vimeo ומאות אתרים נוספים.",
|
||||
"urlSupportedSitesLink": "לצפייה בכל האתרים הנתמכים",
|
||||
"useThisUrl": "שימוש בכתובת זו"
|
||||
"useThisUrl": "שימוש בכתובת זו",
|
||||
"matchCorrectedTo": "תוקן ל-{value} — הקלדת “{typed}”",
|
||||
"matchDidYouMean": "האם התכוונת?",
|
||||
"matchKeepMine": "להשאיר את מה שהקלדתי",
|
||||
"matchTidiedTo": "סודר ל-{value}",
|
||||
"matchUndo": "ביטול",
|
||||
"matchChecking": "בודקים את פרטי השיר…",
|
||||
"matchUseCorrection": "להשתמש בתיקון",
|
||||
"matchUseTidied": "להשתמש בגרסה המסודרת",
|
||||
"matchUsingTyped": "משתמשים במה שהקלדת: {value}"
|
||||
},
|
||||
"jobStatus": {
|
||||
"settingUp": "מגדיר",
|
||||
@@ -683,7 +692,8 @@
|
||||
},
|
||||
"titleCardPreview": {
|
||||
"songTitle": "שם השיר",
|
||||
"artist": "אמן"
|
||||
"artist": "אמן",
|
||||
"loading": "טעינת תצוגה מקדימה של מסך הכותרת"
|
||||
},
|
||||
"editTrack": {
|
||||
"title": "ערוך רצועה שהושלמה",
|
||||
@@ -776,7 +786,17 @@
|
||||
"undoFailed": "ביטול נכשל",
|
||||
"redoFailed": "ביצוע שוב נכשל",
|
||||
"restoreFailed": "שחזור נכשל — ייתכן שחלק מהעריכות לא הוחלו",
|
||||
"submitFailed": "שליחה נכשלה"
|
||||
"submitFailed": "שליחה נכשלה",
|
||||
"fadeIn": "פייד אין",
|
||||
"fadeInSelection": "החלת פייד אין על האזור הנבחר",
|
||||
"fadeOut": "פייד אאוט",
|
||||
"fadeOutSelection": "החלת פייד אאוט על האזור הנבחר",
|
||||
"fadeInDisabledHint": "כדי לבצע הגברה הדרגתית, בחרו אזור שמתחיל בדיוק בתחילת הרצועה",
|
||||
"fadeOutDisabledHint": "כדי לבצע הנמכה הדרגתית, בחרו אזור שמסתיים בדיוק בסוף הרצועה",
|
||||
"trimEndDisabledHint": "כדי לחתוך את הסוף, בחרו אזור שמסתיים בדיוק בסוף הרצועה",
|
||||
"trimEndSelection": "הסירו הכל אחרי האזור הנבחר",
|
||||
"trimStartDisabledHint": "כדי לחתוך את ההתחלה, בחרו אזור שמתחיל בדיוק בתחילת הרצועה",
|
||||
"trimStartSelection": "הסירו הכל לפני האזור הנבחר"
|
||||
},
|
||||
"audioEditRestore": {
|
||||
"title": "הפעלות עריכת אודיו שמורות",
|
||||
@@ -803,7 +823,7 @@
|
||||
"acceptAll": "אשר הכל",
|
||||
"revertAll": "החזר הכל",
|
||||
"undoAll": "בטל הכל",
|
||||
"resetAllChanges": "אפס את כל השינויים חזרה למילים המקוריות שתוקנו על ידי AI",
|
||||
"resetAllChanges": "איפוס כל השינויים בחזרה למילים המתוקנות המקוריות",
|
||||
"undo": "בטל",
|
||||
"redo": "בצע שוב",
|
||||
"findReplace": "חפש/החלף",
|
||||
@@ -816,7 +836,9 @@
|
||||
"playback": "השמעה",
|
||||
"audioLoadError": "לא הצלחנו לטעון את האודיו",
|
||||
"audioStillLoading": "האודיו עדיין נטען...",
|
||||
"loadingAudio": "טוען אודיו..."
|
||||
"loadingAudio": "טוען אודיו...",
|
||||
"autoCorrect": "תיקון אוטומטי",
|
||||
"autoCorrectDesc": "הפקת הצעות לתיקון על ידי השוואת התמלול למילות הייחוס. שום שינוי לא יחול עד לאישור כל הצעה."
|
||||
},
|
||||
"guidance": {
|
||||
"showTips": "הצג טיפים",
|
||||
@@ -1274,6 +1296,52 @@
|
||||
},
|
||||
"toasts": {
|
||||
"customLyricsSaved": "המילים המותאמות אישית הוחלו. יש לסנכרן ידנית כל מקטע שנערך כדי להבטיח שתזמוני המילים מדויקים."
|
||||
},
|
||||
"autoCorrect": {
|
||||
"accept": "קבל הצעה",
|
||||
"acceptAll": "קבל הכל",
|
||||
"accepted": "התקבל",
|
||||
"adlibRemovalHint": "אפשר הצעות שמוחקות קולות רקע שאינם מופיעים במקורות",
|
||||
"adlibRemovalLabel": "הצע הסרת אלתורים",
|
||||
"category_adlib_removal": "אלתור",
|
||||
"category_formatting": "עיצוב",
|
||||
"category_grammar": "דקדוק",
|
||||
"category_mishearing": "שמיעה שגויה",
|
||||
"category_other": "אחר",
|
||||
"category_repeated_chorus_fix": "פזמון",
|
||||
"collapse": "צמצם הצעות",
|
||||
"confidenceHint": "רמת הוודאות הנדרשת לפני שהצעה תוצג",
|
||||
"confidenceLabel": "מסנן הצעות",
|
||||
"confidence_all": "הצג הכל",
|
||||
"confidence_high": "ביטחון גבוה",
|
||||
"description": "התיקון האוטומטי משווה את המילים שתומללו למקורות הייחוס ומציע תיקונים ברמת המילה. באפשרותך לעבור על כל הצעה — שום שינוי לא יחול עד לאישורו.",
|
||||
"dismiss": "הסתר הצעות",
|
||||
"expand": "הרחב הצעות",
|
||||
"insertMarker": "הוסף:",
|
||||
"insertionsHint": "אפשר הצעות שמוסיפות מילים שהתפספסו בתמלול",
|
||||
"insertionsLabel": "הצע מילים חסרות",
|
||||
"noReferences": "אין מילות ייחוס זמינות לשיר זה, ולכן לא ניתן להפיק הצעות. יש להוסיף תחילה מילים מחלונית הייחוס.",
|
||||
"noSuggestions": "לא נמצאו בעיות — אין שינויים מוצעים.",
|
||||
"reject": "דחה הצעה",
|
||||
"rejectAll": "דחה הכל",
|
||||
"rejected": "נדחה",
|
||||
"runButton": "קבל הצעות",
|
||||
"running": "מנתח מילים… פעולה זו אורכת בדרך כלל 15–60 שניות.",
|
||||
"staleHint": "מילים אלו נערכו מאז שההצעות נוצרו, ולכן הצעה זו כבר אינה רלוונטית.",
|
||||
"summary": "{total} הצעות · {pending} ממתינות · {accepted} התקבלו",
|
||||
"title": "הצעות לתיקון אוטומטי",
|
||||
"undo": "בטל הצעה זו",
|
||||
"cancel": "ביטול",
|
||||
"close": "סגירה",
|
||||
"confidence_balanced": "מאוזנת",
|
||||
"compareHint": "איטי ויקר יותר, אבל מראה על אילו הצעות מספר מודלים מסכימים",
|
||||
"compareLabel": "השוואה בין מספר מודלי AI",
|
||||
"conflictBadge": "גרסה",
|
||||
"conflictTooltip": "ישנן הצעות שונות למילים אלו — אישור גרסה אחת ידחה את האחרות.",
|
||||
"consensusBadge": "{consensus}/{total} מודלים",
|
||||
"consensusTooltip": "הוצע על ידי: {models}",
|
||||
"cachedBadge": "שמור במטמון",
|
||||
"cachedTooltip": "שוחזר מהרצה קודמת על אותן מילים — ללא חיוב עלות AI."
|
||||
}
|
||||
},
|
||||
"instrumentalReview": {
|
||||
@@ -1508,5 +1576,8 @@
|
||||
"estimatedLabel": "משוער — העלות הסופית תאושר לאחר ההורדה",
|
||||
"reconcileTitle": "השיר הזה ארוך מהצפוי",
|
||||
"cancel": "ביטול"
|
||||
},
|
||||
"karaokeBackgroundPreview": {
|
||||
"loading": "טעינת תצוגה מקדימה של הרקע"
|
||||
}
|
||||
}
|
||||
@@ -533,7 +533,16 @@
|
||||
"pasteUrlButton": "एक लिंक पेस्ट करो",
|
||||
"urlSupportedSitesHint": "यह YouTube, Facebook, SoundCloud, TikTok, Vimeo और सैकड़ों अन्य साइटों के साथ काम करता है।",
|
||||
"urlSupportedSitesLink": "सभी समर्थित साइटें देखो",
|
||||
"useThisUrl": "इस URL का इस्तेमाल करो"
|
||||
"useThisUrl": "इस URL का इस्तेमाल करो",
|
||||
"matchCorrectedTo": "सही करके {value} कर दिया गया — तुमने “{typed}” टाइप किया था",
|
||||
"matchDidYouMean": "क्या तुम्हारा मतलब यह था?",
|
||||
"matchKeepMine": "जो मैंने टाइप किया है वही रखो",
|
||||
"matchTidiedTo": "ठीक करके {value} कर दिया गया",
|
||||
"matchUndo": "पूर्ववत करो",
|
||||
"matchChecking": "गाने की जानकारी चेक की जा रही है…",
|
||||
"matchUseCorrection": "सुधार का इस्तेमाल करो",
|
||||
"matchUseTidied": "व्यवस्थित वर्शन का इस्तेमाल करो",
|
||||
"matchUsingTyped": "जो तुमने टाइप किया है, उसका इस्तेमाल हो रहा है: {value}"
|
||||
},
|
||||
"jobStatus": {
|
||||
"settingUp": "सेटअप हो रहा है",
|
||||
@@ -683,7 +692,8 @@
|
||||
},
|
||||
"titleCardPreview": {
|
||||
"songTitle": "गाने का टाइटल",
|
||||
"artist": "आर्टिस्ट"
|
||||
"artist": "आर्टिस्ट",
|
||||
"loading": "टाइटल स्क्रीन प्रीव्यू लोड हो रहा है"
|
||||
},
|
||||
"editTrack": {
|
||||
"title": "पूरा हुआ ट्रैक एडिट करो",
|
||||
@@ -776,7 +786,17 @@
|
||||
"undoFailed": "अनडू विफल रहा",
|
||||
"redoFailed": "रीडू विफल रहा",
|
||||
"restoreFailed": "रिस्टोर विफल रहा — कुछ एडिट्स लागू नहीं हुए होंगे",
|
||||
"submitFailed": "सबमिट विफल रहा"
|
||||
"submitFailed": "सबमिट विफल रहा",
|
||||
"fadeIn": "फ़ेड इन",
|
||||
"fadeInSelection": "चुने गए हिस्से पर फ़ेड इन करो",
|
||||
"fadeOut": "फ़ेड आउट",
|
||||
"fadeOutSelection": "चुने गए हिस्से पर फ़ेड आउट करो",
|
||||
"fadeInDisabledHint": "फेड इन करने के लिए, एक ऐसा हिस्सा चुनो जो ट्रैक की बिल्कुल शुरुआत से शुरू होता हो",
|
||||
"fadeOutDisabledHint": "फेड आउट करने के लिए, एक ऐसा हिस्सा चुनो जो ट्रैक के बिल्कुल अंत में खत्म होता हो",
|
||||
"trimEndDisabledHint": "अंत को ट्रिम करने के लिए, एक ऐसा हिस्सा चुनो जो ट्रैक के बिल्कुल अंत में खत्म होता हो",
|
||||
"trimEndSelection": "चुने हुए हिस्से के बाद का सब कुछ हटा दो",
|
||||
"trimStartDisabledHint": "शुरुआत को ट्रिम करने के लिए, एक ऐसा हिस्सा चुनो जो ट्रैक की बिल्कुल शुरुआत से शुरू होता हो",
|
||||
"trimStartSelection": "चुने हुए हिस्से से पहले का सब कुछ हटा दो"
|
||||
},
|
||||
"audioEditRestore": {
|
||||
"title": "सेव किए गए ऑडियो एडिट सेशंस",
|
||||
@@ -803,7 +823,7 @@
|
||||
"acceptAll": "सभी एक्सेप्ट करो",
|
||||
"revertAll": "सभी रिवर्ट करो",
|
||||
"undoAll": "सभी अनडू करो",
|
||||
"resetAllChanges": "सभी बदलावों को ओरिजिनल AI-करेक्टेड लिरिक्स पर रीसेट करो",
|
||||
"resetAllChanges": "सभी बदलावों को वापस मूल सही किए गए लिरिक्स पर रीसेट करो",
|
||||
"undo": "अनडू",
|
||||
"redo": "रीडू",
|
||||
"findReplace": "ढूंढो/बदलो",
|
||||
@@ -816,7 +836,9 @@
|
||||
"playback": "प्लेबैक",
|
||||
"audioLoadError": "ऑडियो लोड नहीं हो सका",
|
||||
"audioStillLoading": "ऑडियो अभी भी लोड हो रहा है...",
|
||||
"loadingAudio": "ऑडियो लोड हो रहा है..."
|
||||
"loadingAudio": "ऑडियो लोड हो रहा है...",
|
||||
"autoCorrect": "ऑटो-करेक्ट",
|
||||
"autoCorrectDesc": "ट्रांसक्रिप्शन की तुलना रेफरेंस लिरिक्स से करके सुधार के सुझाव जनरेट करो। जब तक तुम हर सुझाव को स्वीकार नहीं करते, तब तक कुछ नहीं बदलता।"
|
||||
},
|
||||
"guidance": {
|
||||
"showTips": "टिप्स दिखाओ",
|
||||
@@ -1274,6 +1296,52 @@
|
||||
},
|
||||
"toasts": {
|
||||
"customLyricsSaved": "कस्टम लिरिक्स लागू हो गए। यह पक्का करने के लिए कि कस्टमाइज़्ड लिरिक्स के लिए शब्दों की टाइमिंग सही है, हर एडिट किए गए हिस्से को मैन्युअली सिंक करो।"
|
||||
},
|
||||
"autoCorrect": {
|
||||
"accept": "सुझाव स्वीकार करो",
|
||||
"acceptAll": "सभी स्वीकार करो",
|
||||
"accepted": "स्वीकार किया गया",
|
||||
"adlibRemovalHint": "उन सुझावों को अनुमति दो जो ऐसे बैकिंग वोकल्स को हटाते हैं जो रेफरेंस में नहीं हैं",
|
||||
"adlibRemovalLabel": "एडलिब्स हटाने का सुझाव दो",
|
||||
"category_adlib_removal": "एडलिब",
|
||||
"category_formatting": "फॉर्मेट",
|
||||
"category_grammar": "व्याकरण",
|
||||
"category_mishearing": "गलत सुना गया",
|
||||
"category_other": "अन्य",
|
||||
"category_repeated_chorus_fix": "कोरस",
|
||||
"collapse": "सुझाव छिपाओ",
|
||||
"confidenceHint": "दिखाए जाने से पहले किसी सुझाव का कितना सटीक होना ज़रूरी है",
|
||||
"confidenceLabel": "सुझाव फ़िल्टर",
|
||||
"confidence_all": "सभी दिखाओ",
|
||||
"confidence_high": "ज़्यादा आश्वस्त",
|
||||
"description": "ऑटो-करेक्ट ट्रांसक्राइब किए गए लिरिक्स की तुलना रेफरेंस सोर्स से करता है और शब्दों को ठीक करने के सुझाव देता है। तुम हर सुझाव का रिव्यू कर सकते हो — जब तक तुम इसे स्वीकार नहीं करते, तब तक कुछ भी लागू नहीं होता।",
|
||||
"dismiss": "सुझाव हटाओ",
|
||||
"expand": "सुझाव पूरे दिखाओ",
|
||||
"insertMarker": "जोड़ो:",
|
||||
"insertionsHint": "उन सुझावों को अनुमति दो जो ट्रांसक्रिप्शन में छूटे हुए शब्दों को जोड़ते हैं",
|
||||
"insertionsLabel": "छूटे हुए शब्दों का सुझाव दो",
|
||||
"noReferences": "इस गाने के लिए कोई रेफरेंस लिरिक्स उपलब्ध नहीं हैं, इसलिए सुझाव जनरेट नहीं किए जा सकते। पहले रेफरेंस पैनल से लिरिक्स जोड़ो।",
|
||||
"noSuggestions": "कोई समस्या नहीं मिली — बदलाव के लिए कोई सुझाव नहीं हैं।",
|
||||
"reject": "सुझाव अस्वीकार करो",
|
||||
"rejectAll": "सभी अस्वीकार करो",
|
||||
"rejected": "अस्वीकार किया गया",
|
||||
"runButton": "सुझाव प्राप्त करो",
|
||||
"running": "लिरिक्स का विश्लेषण हो रहा है… इसमें आमतौर पर 15–60 सेकंड लगते हैं।",
|
||||
"staleHint": "सुझाव आने के बाद इन शब्दों को एडिट किया गया था, इसलिए यह सुझाव अब लागू नहीं होता।",
|
||||
"summary": "{total} सुझाव · {pending} लंबित · {accepted} स्वीकार किए गए",
|
||||
"title": "ऑटो-करेक्ट सुझाव",
|
||||
"undo": "इस सुझाव को पूर्ववत करो",
|
||||
"cancel": "कैंसल",
|
||||
"close": "बंद करो",
|
||||
"confidence_balanced": "संतुलित",
|
||||
"compareHint": "यह धीमा है और इसमें ज़्यादा खर्च आता है, लेकिन यह दिखाता है कि किन सुझावों पर कई मॉडल सहमत हैं",
|
||||
"compareLabel": "कई AI मॉडलों की तुलना करो",
|
||||
"conflictBadge": "विकल्प",
|
||||
"conflictTooltip": "इन शब्दों के लिए अलग-अलग सुझाव हैं — एक विकल्प को स्वीकार करने पर बाकी अस्वीकार हो जाएंगे।",
|
||||
"consensusBadge": "{consensus}/{total} मॉडल",
|
||||
"consensusTooltip": "इनके द्वारा प्रस्तावित: {models}",
|
||||
"cachedBadge": "कैश्ड",
|
||||
"cachedTooltip": "इन्हीं लिरिक्स पर पिछले रन से रीस्टोर किया गया — कोई AI लागत नहीं आई।"
|
||||
}
|
||||
},
|
||||
"instrumentalReview": {
|
||||
@@ -1508,5 +1576,8 @@
|
||||
"estimatedLabel": "अनुमानित — डाउनलोड के बाद अंतिम लागत की पुष्टि की जाएगी",
|
||||
"reconcileTitle": "यह गाना उम्मीद से लंबा है",
|
||||
"cancel": "कैंसल"
|
||||
},
|
||||
"karaokeBackgroundPreview": {
|
||||
"loading": "बैकग्राउंड प्रीव्यू लोड हो रहा है"
|
||||
}
|
||||
}
|
||||
@@ -533,7 +533,16 @@
|
||||
"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"
|
||||
"useThisUrl": "Upotrijebi ovaj URL",
|
||||
"matchCorrectedTo": "Ispravljeno u {value} — tvoj unos: “{typed}”",
|
||||
"matchDidYouMean": "Jesi li mislio/la?",
|
||||
"matchKeepMine": "zadrži moj unos",
|
||||
"matchTidiedTo": "Uređeno u {value}",
|
||||
"matchUndo": "Poništi",
|
||||
"matchChecking": "Provjera detalja pjesme…",
|
||||
"matchUseCorrection": "koristi ispravak",
|
||||
"matchUseTidied": "koristi uređenu verziju",
|
||||
"matchUsingTyped": "Koristimo ono što si upisao: {value}"
|
||||
},
|
||||
"jobStatus": {
|
||||
"settingUp": "Postavljanje",
|
||||
@@ -683,7 +692,8 @@
|
||||
},
|
||||
"titleCardPreview": {
|
||||
"songTitle": "Naslov pjesme",
|
||||
"artist": "Izvođač"
|
||||
"artist": "Izvođač",
|
||||
"loading": "Učitavanje pregleda naslovnog zaslona"
|
||||
},
|
||||
"editTrack": {
|
||||
"title": "Uredi završenu pjesmu",
|
||||
@@ -776,7 +786,17 @@
|
||||
"undoFailed": "Poništavanje nije uspjelo",
|
||||
"redoFailed": "Ponavljanje nije uspjelo",
|
||||
"restoreFailed": "Vraćanje nije uspjelo — neka uređivanja možda nisu primijenjena",
|
||||
"submitFailed": "Slanje nije uspjelo"
|
||||
"submitFailed": "Slanje nije uspjelo",
|
||||
"fadeIn": "Postupno pojačavanje",
|
||||
"fadeInSelection": "Postupno pojačaj odabrano područje",
|
||||
"fadeOut": "Postupno stišavanje",
|
||||
"fadeOutSelection": "Postupno stišaj odabrano područje",
|
||||
"fadeInDisabledHint": "Za postepeno pojačavanje zvuka, odaberi dio koji počinje na samom početku trake",
|
||||
"fadeOutDisabledHint": "Za postepeno stišavanje zvuka, odaberi dio koji završava na samom kraju trake",
|
||||
"trimEndDisabledHint": "Za skraćivanje kraja, odaberi dio koji završava na samom kraju trake",
|
||||
"trimEndSelection": "Ukloni sve nakon odabira",
|
||||
"trimStartDisabledHint": "Za skraćivanje početka, odaberi dio koji počinje na samom početku trake",
|
||||
"trimStartSelection": "Ukloni sve prije odabira"
|
||||
},
|
||||
"audioEditRestore": {
|
||||
"title": "Spremljene sesije uređivanja zvuka",
|
||||
@@ -803,7 +823,7 @@
|
||||
"acceptAll": "Prihvati sve",
|
||||
"revertAll": "Vrati sve",
|
||||
"undoAll": "Poništi sve",
|
||||
"resetAllChanges": "Poništi sve promjene natrag na originalni AI-ispravljeni tekst",
|
||||
"resetAllChanges": "Poništi sve promjene i vrati na izvorni ispravljeni tekst",
|
||||
"undo": "Poništi",
|
||||
"redo": "Ponovi",
|
||||
"findReplace": "Pronađi/Zamijeni",
|
||||
@@ -816,7 +836,9 @@
|
||||
"playback": "Reprodukcija",
|
||||
"audioLoadError": "Nije moguće učitati audio",
|
||||
"audioStillLoading": "Audio se još uvijek učitava...",
|
||||
"loadingAudio": "Učitavanje audija..."
|
||||
"loadingAudio": "Učitavanje audija...",
|
||||
"autoCorrect": "Automatski ispravak",
|
||||
"autoCorrectDesc": "Generiraj prijedloge za ispravak usporedbom transkripcije s referentnim tekstom. Ništa se ne mijenja dok ne prihvatiš svaki prijedlog."
|
||||
},
|
||||
"guidance": {
|
||||
"showTips": "Prikaži savjete",
|
||||
@@ -1274,6 +1296,52 @@
|
||||
},
|
||||
"toasts": {
|
||||
"customLyricsSaved": "Prilagođeni tekst je primijenjen. Ručno sinkroniziraj svaki uređeni segment kako bi tempiranje riječi bilo točno za prilagođeni tekst."
|
||||
},
|
||||
"autoCorrect": {
|
||||
"accept": "Prihvati prijedlog",
|
||||
"acceptAll": "Prihvati sve",
|
||||
"accepted": "Prihvaćeno",
|
||||
"adlibRemovalHint": "Dopusti prijedloge za brisanje pratećih vokala kojih nema u referentnom tekstu",
|
||||
"adlibRemovalLabel": "Predloži uklanjanje adlibova",
|
||||
"category_adlib_removal": "adlib",
|
||||
"category_formatting": "format",
|
||||
"category_grammar": "gramatika",
|
||||
"category_mishearing": "pogrešno prepoznato",
|
||||
"category_other": "ostalo",
|
||||
"category_repeated_chorus_fix": "refren",
|
||||
"collapse": "Sažmi prijedloge",
|
||||
"confidenceHint": "Koliko prijedlog mora biti pouzdan prije nego što se prikaže",
|
||||
"confidenceLabel": "Filtar prijedloga",
|
||||
"confidence_all": "Prikaži sve",
|
||||
"confidence_high": "Visoka pouzdanost",
|
||||
"description": "Automatski ispravak uspoređuje transkribirani tekst s referentnim izvorima i predlaže ispravke na razini riječi. Pregledavaš svaki prijedlog — ništa se ne primjenjuje dok ga ne prihvatiš.",
|
||||
"dismiss": "Odbaci prijedloge",
|
||||
"expand": "Proširi prijedloge",
|
||||
"insertMarker": "umetni:",
|
||||
"insertionsHint": "Dopusti prijedloge za umetanje riječi koje nedostaju u transkripciji",
|
||||
"insertionsLabel": "Predloži riječi koje nedostaju",
|
||||
"noReferences": "Za ovu pjesmu nema dostupnog referentnog teksta, pa se prijedlozi ne mogu generirati. Prvo dodaj tekst iz referentnog panela.",
|
||||
"noSuggestions": "Nisu pronađeni problemi — nema predloženih promjena.",
|
||||
"reject": "Odbij prijedlog",
|
||||
"rejectAll": "Odbij sve",
|
||||
"rejected": "Odbijeno",
|
||||
"runButton": "Dohvati prijedloge",
|
||||
"running": "Analiziram tekst… ovo obično traje 15–60 sekundi.",
|
||||
"staleHint": "Ove su riječi uređene nakon generiranja prijedloga, pa ovaj prijedlog više ne vrijedi.",
|
||||
"summary": "{total} prijedloga · {pending} na čekanju · {accepted} prihvaćeno",
|
||||
"title": "Prijedlozi automatskog ispravka",
|
||||
"undo": "Poništi ovaj prijedlog",
|
||||
"cancel": "Odustani",
|
||||
"close": "Zatvori",
|
||||
"confidence_balanced": "Uravnoteženo",
|
||||
"compareHint": "Sporije je i košta više, ali pokazuje oko kojih se prijedloga slaže više modela",
|
||||
"compareLabel": "Usporedi više AI modela",
|
||||
"conflictBadge": "varijanta",
|
||||
"conflictTooltip": "Postoje različiti prijedlozi za ove riječi — prihvaćanjem jedne varijante odbacuješ ostale.",
|
||||
"consensusBadge": "{consensus}/{total} modela",
|
||||
"consensusTooltip": "Predložili: {models}",
|
||||
"cachedBadge": "predmemorirano",
|
||||
"cachedTooltip": "Obnovljeno iz prethodnog pokretanja s istim tekstom pjesme — nije bilo troškova za AI."
|
||||
}
|
||||
},
|
||||
"instrumentalReview": {
|
||||
@@ -1508,5 +1576,8 @@
|
||||
"estimatedLabel": "Procijenjeno — konačna cijena potvrđuje se nakon preuzimanja",
|
||||
"reconcileTitle": "Ova pjesma je duža od očekivanog",
|
||||
"cancel": "Odustani"
|
||||
},
|
||||
"karaokeBackgroundPreview": {
|
||||
"loading": "Učitavanje pregleda pozadine"
|
||||
}
|
||||
}
|
||||
@@ -533,7 +533,16 @@
|
||||
"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"
|
||||
"useThisUrl": "Használd ezt az URL-t",
|
||||
"matchCorrectedTo": "Javítva erre: {value} — ezt írtad: „{typed}”",
|
||||
"matchDidYouMean": "Erre gondoltál?",
|
||||
"matchKeepMine": "maradjon, amit írtam",
|
||||
"matchTidiedTo": "Rendezve erre: {value}",
|
||||
"matchUndo": "Visszavonás",
|
||||
"matchChecking": "A dal adatainak ellenőrzése…",
|
||||
"matchUseCorrection": "javítás használata",
|
||||
"matchUseTidied": "letisztított verzió használata",
|
||||
"matchUsingTyped": "Az általad beírtak használata: {value}"
|
||||
},
|
||||
"jobStatus": {
|
||||
"settingUp": "Beállítás",
|
||||
@@ -683,7 +692,8 @@
|
||||
},
|
||||
"titleCardPreview": {
|
||||
"songTitle": "Dal címe",
|
||||
"artist": "Előadó"
|
||||
"artist": "Előadó",
|
||||
"loading": "Címképernyő előnézetének betöltése"
|
||||
},
|
||||
"editTrack": {
|
||||
"title": "Befejezett dal szerkesztése",
|
||||
@@ -776,7 +786,17 @@
|
||||
"undoFailed": "Visszavonás sikertelen",
|
||||
"redoFailed": "Újra sikertelen",
|
||||
"restoreFailed": "Visszaállítás sikertelen — előfordulhat, hogy néhány szerkesztés nem lett alkalmazva",
|
||||
"submitFailed": "Beküldés sikertelen"
|
||||
"submitFailed": "Beküldés sikertelen",
|
||||
"fadeIn": "Felerősítés",
|
||||
"fadeInSelection": "Felerősítés a kijelölt szakaszon",
|
||||
"fadeOut": "Elhalkítás",
|
||||
"fadeOutSelection": "Elhalkítás a kijelölt szakaszon",
|
||||
"fadeInDisabledHint": "A felerősítéshez jelölj ki egy olyan részt, amely pontosan a sáv legeléjén kezdődik",
|
||||
"fadeOutDisabledHint": "Az elhalkításhoz jelölj ki egy olyan részt, amely pontosan a sáv legvégéig tart",
|
||||
"trimEndDisabledHint": "A végének levágásához jelölj ki egy olyan részt, amely pontosan a sáv legvégéig tart",
|
||||
"trimEndSelection": "Minden eltávolítása a kijelölés után",
|
||||
"trimStartDisabledHint": "Az elejének levágásához jelölj ki egy olyan részt, amely pontosan a sáv legeléjén kezdődik",
|
||||
"trimStartSelection": "Minden eltávolítása a kijelölés előtt"
|
||||
},
|
||||
"audioEditRestore": {
|
||||
"title": "Mentett hangszerkesztési munkamenetek",
|
||||
@@ -803,7 +823,7 @@
|
||||
"acceptAll": "Összes elfogadása",
|
||||
"revertAll": "Összes visszaállítása",
|
||||
"undoAll": "Összes visszavonása",
|
||||
"resetAllChanges": "Minden változtatás visszaállítása az eredeti AI által javított dalszövegre",
|
||||
"resetAllChanges": "Minden módosítás visszaállítása az eredeti, javított dalszövegre",
|
||||
"undo": "Visszavonás",
|
||||
"redo": "Újra",
|
||||
"findReplace": "Keresés/Csere",
|
||||
@@ -816,7 +836,9 @@
|
||||
"playback": "Lejátszás",
|
||||
"audioLoadError": "Nem sikerült betölteni a hanganyagot",
|
||||
"audioStillLoading": "A hanganyag még töltődik...",
|
||||
"loadingAudio": "Hanganyag betöltése..."
|
||||
"loadingAudio": "Hanganyag betöltése...",
|
||||
"autoCorrect": "Automatikus javítás",
|
||||
"autoCorrectDesc": "Javítási javaslatok generálása a leírt és a referencia-dalszöveg összehasonlításával. Semmi sem módosul, amíg el nem fogadod az egyes javaslatokat."
|
||||
},
|
||||
"guidance": {
|
||||
"showTips": "Tippek mutatása",
|
||||
@@ -1274,6 +1296,52 @@
|
||||
},
|
||||
"toasts": {
|
||||
"customLyricsSaved": "Egyedi dalszöveg alkalmazva. Szinkronizáld manuálisan az összes szerkesztett szegmenst, hogy a szavak időzítése megfelelő legyen a testreszabott dalszöveghez."
|
||||
},
|
||||
"autoCorrect": {
|
||||
"accept": "Javaslat elfogadása",
|
||||
"acceptAll": "Összes elfogadása",
|
||||
"accepted": "Elfogadva",
|
||||
"adlibRemovalHint": "Engedélyezd az olyan javaslatokat, amelyek törlik a referenciákban nem szereplő háttérvokálokat",
|
||||
"adlibRemovalLabel": "Adlibek eltávolításának javaslata",
|
||||
"category_adlib_removal": "adlib",
|
||||
"category_formatting": "formátum",
|
||||
"category_grammar": "nyelvtan",
|
||||
"category_mishearing": "félrehallás",
|
||||
"category_other": "egyéb",
|
||||
"category_repeated_chorus_fix": "refrén",
|
||||
"collapse": "Javaslatok összecsukása",
|
||||
"confidenceHint": "Mennyire legyen biztos a javaslat, mielőtt megjelenik",
|
||||
"confidenceLabel": "Javaslatszűrő",
|
||||
"confidence_all": "Összes megjelenítése",
|
||||
"confidence_high": "Nagy bizonyosság",
|
||||
"description": "Az automatikus javítás összehasonlítja a leírt dalszöveget a referenciaforrásokkal, és szavankénti javításokat javasol. Minden javaslatot átnézhetsz — semmi sem módosul, amíg el nem fogadod.",
|
||||
"dismiss": "Javaslatok elvetése",
|
||||
"expand": "Javaslatok kibontása",
|
||||
"insertMarker": "beszúrás:",
|
||||
"insertionsHint": "Engedélyezd az olyan javaslatokat, amelyek beszúrják az átírásból kimaradt szavakat",
|
||||
"insertionsLabel": "Hiányzó szavak javaslata",
|
||||
"noReferences": "Ehhez a dalhoz nincs elérhető referencia-dalszöveg, így nem tudunk javaslatokat generálni. Először adj hozzá dalszöveget a referenciapanelen.",
|
||||
"noSuggestions": "Nem találtunk problémát — nincsenek javasolt módosítások.",
|
||||
"reject": "Javaslat elutasítása",
|
||||
"rejectAll": "Összes elutasítása",
|
||||
"rejected": "Elutasítva",
|
||||
"runButton": "Javaslatok kérése",
|
||||
"running": "Dalszöveg elemzése… ez általában 15–60 másodpercet vesz igénybe.",
|
||||
"staleHint": "Ezeket a szavakat módosítottad a javaslatok generálása óta, így ez a javaslat már nem érvényes.",
|
||||
"summary": "{total} javaslat · {pending} függőben · {accepted} elfogadva",
|
||||
"title": "Automatikus javítási javaslatok",
|
||||
"undo": "Javaslat visszavonása",
|
||||
"cancel": "Mégse",
|
||||
"close": "Bezárás",
|
||||
"confidence_balanced": "Kiegyensúlyozott",
|
||||
"compareHint": "Lassabb és többe kerül, de megmutatja, mely javaslatokban ért egyet több modell.",
|
||||
"compareLabel": "Több MI-modell összehasonlítása",
|
||||
"conflictBadge": "változat",
|
||||
"conflictTooltip": "Több különböző javaslat is van ezekre a szavakra — az egyik változat elfogadásával elutasítod a többit.",
|
||||
"consensusBadge": "{consensus}/{total} modell",
|
||||
"consensusTooltip": "Javasolta: {models}",
|
||||
"cachedBadge": "gyorsítótárazott",
|
||||
"cachedTooltip": "Egy korábbi, azonos dalszövegen végzett futtatásból visszaállítva — nem merült fel AI-költség."
|
||||
}
|
||||
},
|
||||
"instrumentalReview": {
|
||||
@@ -1508,5 +1576,8 @@
|
||||
"estimatedLabel": "Becsült — a végső költséget a letöltés után erősítjük meg",
|
||||
"reconcileTitle": "Ez a dal hosszabb a vártnál",
|
||||
"cancel": "Mégse"
|
||||
},
|
||||
"karaokeBackgroundPreview": {
|
||||
"loading": "Háttér előnézetének betöltése"
|
||||
}
|
||||
}
|
||||
@@ -533,7 +533,16 @@
|
||||
"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"
|
||||
"useThisUrl": "Gunakan URL Ini",
|
||||
"matchCorrectedTo": "Dikoreksi menjadi {value} — Anda mengetik “{typed}”",
|
||||
"matchDidYouMean": "Maksud Anda?",
|
||||
"matchKeepMine": "tetap gunakan yang saya ketik",
|
||||
"matchTidiedTo": "Dirapikan menjadi {value}",
|
||||
"matchUndo": "Urungkan",
|
||||
"matchChecking": "Memeriksa detail lagu…",
|
||||
"matchUseCorrection": "gunakan koreksi",
|
||||
"matchUseTidied": "gunakan versi yang dirapikan",
|
||||
"matchUsingTyped": "Menggunakan yang Anda ketik: {value}"
|
||||
},
|
||||
"jobStatus": {
|
||||
"settingUp": "Menyiapkan",
|
||||
@@ -683,7 +692,8 @@
|
||||
},
|
||||
"titleCardPreview": {
|
||||
"songTitle": "Judul Lagu",
|
||||
"artist": "Artis"
|
||||
"artist": "Artis",
|
||||
"loading": "Memuat pratinjau layar judul"
|
||||
},
|
||||
"editTrack": {
|
||||
"title": "Edit Track yang Selesai",
|
||||
@@ -776,7 +786,17 @@
|
||||
"undoFailed": "Gagal mengurungkan",
|
||||
"redoFailed": "Gagal mengulangi",
|
||||
"restoreFailed": "Gagal memulihkan — beberapa editan mungkin tidak diterapkan",
|
||||
"submitFailed": "Gagal mengirim"
|
||||
"submitFailed": "Gagal mengirim",
|
||||
"fadeIn": "Fade In",
|
||||
"fadeInSelection": "Terapkan fade in pada bagian yang dipilih",
|
||||
"fadeOut": "Fade Out",
|
||||
"fadeOutSelection": "Terapkan fade out pada bagian yang dipilih",
|
||||
"fadeInDisabledHint": "Untuk menerapkan fade in, pilih bagian yang dimulai tepat dari awal trek",
|
||||
"fadeOutDisabledHint": "Untuk menerapkan fade out, pilih bagian yang berakhir tepat di akhir trek",
|
||||
"trimEndDisabledHint": "Untuk memotong bagian akhir, pilih bagian yang berakhir tepat di akhir trek",
|
||||
"trimEndSelection": "Hapus semua setelah bagian yang dipilih",
|
||||
"trimStartDisabledHint": "Untuk memotong bagian awal, pilih bagian yang dimulai tepat dari awal trek",
|
||||
"trimStartSelection": "Hapus semua sebelum bagian yang dipilih"
|
||||
},
|
||||
"audioEditRestore": {
|
||||
"title": "Sesi Edit Audio Tersimpan",
|
||||
@@ -803,7 +823,7 @@
|
||||
"acceptAll": "Terima Semua",
|
||||
"revertAll": "Kembalikan Semua",
|
||||
"undoAll": "Batalkan Semua",
|
||||
"resetAllChanges": "Atur ulang semua perubahan kembali ke lirik asli yang dikoreksi AI",
|
||||
"resetAllChanges": "Kembalikan semua perubahan ke lirik asli yang telah dikoreksi",
|
||||
"undo": "Urungkan",
|
||||
"redo": "Ulangi",
|
||||
"findReplace": "Cari/Ganti",
|
||||
@@ -816,7 +836,9 @@
|
||||
"playback": "Pemutaran",
|
||||
"audioLoadError": "Gagal memuat audio",
|
||||
"audioStillLoading": "Audio masih dimuat...",
|
||||
"loadingAudio": "Memuat audio..."
|
||||
"loadingAudio": "Memuat audio...",
|
||||
"autoCorrect": "Koreksi otomatis",
|
||||
"autoCorrectDesc": "Hasilkan saran koreksi dengan membandingkan transkripsi dengan lirik referensi. Tidak ada perubahan yang diterapkan sampai Anda menyetujui setiap saran."
|
||||
},
|
||||
"guidance": {
|
||||
"showTips": "Tampilkan tips",
|
||||
@@ -1274,6 +1296,52 @@
|
||||
},
|
||||
"toasts": {
|
||||
"customLyricsSaved": "Lirik kustom berhasil diterapkan. Sinkronkan setiap segmen yang diedit secara manual untuk memastikan ketepatan waktu lirik yang baru."
|
||||
},
|
||||
"autoCorrect": {
|
||||
"accept": "Terima saran",
|
||||
"acceptAll": "Terima semua",
|
||||
"accepted": "Diterima",
|
||||
"adlibRemovalHint": "Izinkan saran yang menghapus vokal latar yang tidak ada di referensi",
|
||||
"adlibRemovalLabel": "Sarankan penghapusan adlib",
|
||||
"category_adlib_removal": "adlib",
|
||||
"category_formatting": "format",
|
||||
"category_grammar": "tata bahasa",
|
||||
"category_mishearing": "salah dengar",
|
||||
"category_other": "lainnya",
|
||||
"category_repeated_chorus_fix": "korus",
|
||||
"collapse": "Perkecil saran",
|
||||
"confidenceHint": "Tingkat keyakinan minimum sebelum saran ditampilkan",
|
||||
"confidenceLabel": "Filter saran",
|
||||
"confidence_all": "Tampilkan semua",
|
||||
"confidence_high": "Keyakinan tinggi",
|
||||
"description": "Koreksi otomatis membandingkan lirik yang ditranskripsi dengan sumber referensi dan menyarankan perbaikan per kata. Anda dapat meninjau setiap saran — tidak ada perubahan yang diterapkan sampai Anda menyetujuinya.",
|
||||
"dismiss": "Abaikan saran",
|
||||
"expand": "Perluas saran",
|
||||
"insertMarker": "sisipkan:",
|
||||
"insertionsHint": "Izinkan saran untuk menyisipkan kata yang terlewat dalam transkripsi",
|
||||
"insertionsLabel": "Sarankan kata yang hilang",
|
||||
"noReferences": "Tidak ada lirik referensi yang tersedia untuk lagu ini, sehingga saran tidak dapat dibuat. Tambahkan lirik dari panel referensi terlebih dahulu.",
|
||||
"noSuggestions": "Tidak ada masalah yang ditemukan — tidak ada perubahan yang disarankan.",
|
||||
"reject": "Tolak saran",
|
||||
"rejectAll": "Tolak semua",
|
||||
"rejected": "Ditolak",
|
||||
"runButton": "Dapatkan saran",
|
||||
"running": "Menganalisis lirik… biasanya memakan waktu 15–60 detik.",
|
||||
"staleHint": "Kata-kata ini telah diedit sejak saran dibuat, sehingga saran ini tidak lagi berlaku.",
|
||||
"summary": "{total} saran · {pending} tertunda · {accepted} diterima",
|
||||
"title": "Saran koreksi otomatis",
|
||||
"undo": "Batalkan saran ini",
|
||||
"cancel": "Batal",
|
||||
"close": "Tutup",
|
||||
"confidence_balanced": "Seimbang",
|
||||
"compareHint": "Lebih lambat dan lebih mahal, tapi menunjukkan saran mana yang disetujui oleh beberapa model",
|
||||
"compareLabel": "Bandingkan beberapa model AI",
|
||||
"conflictBadge": "varian",
|
||||
"conflictTooltip": "Ada beberapa saran berbeda untuk kata-kata ini — menerima satu varian akan mengabaikan varian lainnya.",
|
||||
"consensusBadge": "{consensus}/{total} model",
|
||||
"consensusTooltip": "Diusulkan oleh: {models}",
|
||||
"cachedBadge": "di-cache",
|
||||
"cachedTooltip": "Dipulihkan dari proses sebelumnya untuk lirik yang sama — tidak ada biaya AI yang dikenakan."
|
||||
}
|
||||
},
|
||||
"instrumentalReview": {
|
||||
@@ -1508,5 +1576,8 @@
|
||||
"estimatedLabel": "Estimasi — biaya akhir dikonfirmasi setelah diunduh",
|
||||
"reconcileTitle": "Lagu ini lebih panjang dari perkiraan",
|
||||
"cancel": "Batal"
|
||||
},
|
||||
"karaokeBackgroundPreview": {
|
||||
"loading": "Memuat pratinjau latar belakang"
|
||||
}
|
||||
}
|
||||
@@ -533,7 +533,16 @@
|
||||
"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"
|
||||
"useThisUrl": "Usa questo URL",
|
||||
"matchCorrectedTo": "Corretto in {value} — hai digitato “{typed}”",
|
||||
"matchDidYouMean": "Intendevi dire?",
|
||||
"matchKeepMine": "mantieni quello che ho digitato",
|
||||
"matchTidiedTo": "Sistemato in {value}",
|
||||
"matchUndo": "Annulla",
|
||||
"matchChecking": "Controllo dei dettagli del brano…",
|
||||
"matchUseCorrection": "usa la correzione",
|
||||
"matchUseTidied": "usa la versione ripulita",
|
||||
"matchUsingTyped": "Uso quello che hai digitato: {value}"
|
||||
},
|
||||
"jobStatus": {
|
||||
"settingUp": "Configurazione",
|
||||
@@ -683,7 +692,8 @@
|
||||
},
|
||||
"titleCardPreview": {
|
||||
"songTitle": "Titolo della canzone",
|
||||
"artist": "Artista"
|
||||
"artist": "Artista",
|
||||
"loading": "Caricamento dell'anteprima della schermata del titolo"
|
||||
},
|
||||
"editTrack": {
|
||||
"title": "Modifica traccia completata",
|
||||
@@ -776,7 +786,17 @@
|
||||
"undoFailed": "Annullamento fallito",
|
||||
"redoFailed": "Ripetizione fallita",
|
||||
"restoreFailed": "Ripristino fallito — alcune modifiche potrebbero non essere state applicate",
|
||||
"submitFailed": "Invio fallito"
|
||||
"submitFailed": "Invio fallito",
|
||||
"fadeIn": "Dissolvenza in entrata",
|
||||
"fadeInSelection": "Dissolvenza in entrata sulla regione selezionata",
|
||||
"fadeOut": "Dissolvenza in uscita",
|
||||
"fadeOutSelection": "Dissolvenza in uscita sulla regione selezionata",
|
||||
"fadeInDisabledHint": "Per la dissolvenza in entrata, seleziona una regione che parta esattamente dall'inizio della traccia",
|
||||
"fadeOutDisabledHint": "Per la dissolvenza in uscita, seleziona una regione che termini esattamente alla fine della traccia",
|
||||
"trimEndDisabledHint": "Per tagliare la fine, seleziona una regione che termini esattamente alla fine della traccia",
|
||||
"trimEndSelection": "Rimuovi tutto dopo la selezione",
|
||||
"trimStartDisabledHint": "Per tagliare l'inizio, seleziona una regione che parta esattamente dall'inizio della traccia",
|
||||
"trimStartSelection": "Rimuovi tutto prima della selezione"
|
||||
},
|
||||
"audioEditRestore": {
|
||||
"title": "Sessioni di modifica audio salvate",
|
||||
@@ -803,7 +823,7 @@
|
||||
"acceptAll": "Accetta tutto",
|
||||
"revertAll": "Ripristina tutto",
|
||||
"undoAll": "Annulla tutto",
|
||||
"resetAllChanges": "Reimposta tutte le modifiche al testo originale corretto dall'IA",
|
||||
"resetAllChanges": "Annulla tutte le modifiche e torna al testo corretto originale",
|
||||
"undo": "Annulla",
|
||||
"redo": "Ripeti",
|
||||
"findReplace": "Trova/Sostituisci",
|
||||
@@ -816,7 +836,9 @@
|
||||
"playback": "Riproduzione",
|
||||
"audioLoadError": "Impossibile caricare l'audio",
|
||||
"audioStillLoading": "L'audio è ancora in caricamento...",
|
||||
"loadingAudio": "Caricamento audio..."
|
||||
"loadingAudio": "Caricamento audio...",
|
||||
"autoCorrect": "Correzione automatica",
|
||||
"autoCorrectDesc": "Genera suggerimenti di correzione confrontando la trascrizione con il testo di riferimento. Non viene modificato nulla finché non accetti ogni suggerimento."
|
||||
},
|
||||
"guidance": {
|
||||
"showTips": "Mostra suggerimenti",
|
||||
@@ -1274,6 +1296,52 @@
|
||||
},
|
||||
"toasts": {
|
||||
"customLyricsSaved": "Testo personalizzato applicato. Sincronizza manualmente ogni segmento modificato per assicurarti che il tempismo delle parole sia corretto per il testo personalizzato."
|
||||
},
|
||||
"autoCorrect": {
|
||||
"accept": "Accetta suggerimento",
|
||||
"acceptAll": "Accetta tutti",
|
||||
"accepted": "Accettato",
|
||||
"adlibRemovalHint": "Consenti suggerimenti che eliminano le voci di sottofondo non presenti nei riferimenti",
|
||||
"adlibRemovalLabel": "Suggerisci di rimuovere gli adlib",
|
||||
"category_adlib_removal": "adlib",
|
||||
"category_formatting": "formattazione",
|
||||
"category_grammar": "grammatica",
|
||||
"category_mishearing": "fraintendimento",
|
||||
"category_other": "altro",
|
||||
"category_repeated_chorus_fix": "ritornello",
|
||||
"collapse": "Comprimi suggerimenti",
|
||||
"confidenceHint": "Quanto deve essere attendibile un suggerimento prima di essere mostrato",
|
||||
"confidenceLabel": "Filtro suggerimenti",
|
||||
"confidence_all": "Mostra tutti",
|
||||
"confidence_high": "Alta sicurezza",
|
||||
"description": "La correzione automatica confronta il testo trascritto con le fonti di riferimento e suggerisce correzioni a livello di singola parola. Puoi rivedere ogni suggerimento — non verrà applicato nulla finché non lo accetti.",
|
||||
"dismiss": "Ignora suggerimenti",
|
||||
"expand": "Espandi suggerimenti",
|
||||
"insertMarker": "inserisci:",
|
||||
"insertionsHint": "Consenti suggerimenti che inseriscono le parole omesse nella trascrizione",
|
||||
"insertionsLabel": "Suggerisci parole mancanti",
|
||||
"noReferences": "Non ci sono testi di riferimento disponibili per questa canzone, quindi non è possibile generare suggerimenti. Aggiungi prima il testo dal pannello di riferimento.",
|
||||
"noSuggestions": "Nessun problema trovato — non ci sono modifiche suggerite.",
|
||||
"reject": "Rifiuta suggerimento",
|
||||
"rejectAll": "Rifiuta tutti",
|
||||
"rejected": "Rifiutato",
|
||||
"runButton": "Ottieni suggerimenti",
|
||||
"running": "Analisi del testo in corso… di solito richiede dai 15 ai 60 secondi.",
|
||||
"staleHint": "Queste parole sono state modificate dopo la generazione dei suggerimenti, quindi questo suggerimento non è più valido.",
|
||||
"summary": "{total} suggerimenti · {pending} in attesa · {accepted} accettati",
|
||||
"title": "Suggerimenti di correzione automatica",
|
||||
"undo": "Annulla questo suggerimento",
|
||||
"cancel": "Annulla",
|
||||
"close": "Chiudi",
|
||||
"confidence_balanced": "Bilanciato",
|
||||
"compareHint": "Più lento e costoso, ma mostra su quali suggerimenti concordano più modelli",
|
||||
"compareLabel": "Confronta più modelli IA",
|
||||
"conflictBadge": "variante",
|
||||
"conflictTooltip": "Ci sono diversi suggerimenti per queste parole — accettando una variante rifiuterai le altre.",
|
||||
"consensusBadge": "{consensus}/{total} modelli",
|
||||
"consensusTooltip": "Proposto da: {models}",
|
||||
"cachedBadge": "in cache",
|
||||
"cachedTooltip": "Ripristinato da un'elaborazione precedente dello stesso testo — non ha comportato alcun costo per l'IA."
|
||||
}
|
||||
},
|
||||
"instrumentalReview": {
|
||||
@@ -1508,5 +1576,8 @@
|
||||
"estimatedLabel": "Stimato — costo finale confermato dopo il download",
|
||||
"reconcileTitle": "Questa canzone è più lunga del previsto",
|
||||
"cancel": "Annulla"
|
||||
},
|
||||
"karaokeBackgroundPreview": {
|
||||
"loading": "Caricamento dell'anteprima dello sfondo"
|
||||
}
|
||||
}
|
||||
@@ -533,7 +533,16 @@
|
||||
"pasteUrlButton": "リンクを貼り付ける",
|
||||
"urlSupportedSitesHint": "YouTube、Facebook、SoundCloud、TikTok、Vimeoなど、数百ものサイトに対応しています。",
|
||||
"urlSupportedSitesLink": "対応サイト一覧を見る",
|
||||
"useThisUrl": "このURLを使用する"
|
||||
"useThisUrl": "このURLを使用する",
|
||||
"matchCorrectedTo": "{value} に修正しました — 入力内容: 「{typed}」",
|
||||
"matchDidYouMean": "もしかして?",
|
||||
"matchKeepMine": "入力した内容をそのまま使う",
|
||||
"matchTidiedTo": "{value} に整えました",
|
||||
"matchUndo": "元に戻す",
|
||||
"matchChecking": "曲の詳細を確認しています…",
|
||||
"matchUseCorrection": "修正を適用する",
|
||||
"matchUseTidied": "整形版を使用する",
|
||||
"matchUsingTyped": "入力された内容を使用します: {value}"
|
||||
},
|
||||
"jobStatus": {
|
||||
"settingUp": "セットアップ中",
|
||||
@@ -683,7 +692,8 @@
|
||||
},
|
||||
"titleCardPreview": {
|
||||
"songTitle": "曲名",
|
||||
"artist": "アーティスト"
|
||||
"artist": "アーティスト",
|
||||
"loading": "タイトル画面のプレビューを読み込んでいます"
|
||||
},
|
||||
"editTrack": {
|
||||
"title": "完了したトラックを編集",
|
||||
@@ -776,7 +786,17 @@
|
||||
"undoFailed": "元に戻す操作に失敗しました",
|
||||
"redoFailed": "やり直し操作に失敗しました",
|
||||
"restoreFailed": "復元に失敗しました — 一部の編集が適用されていない可能性があります",
|
||||
"submitFailed": "送信に失敗しました"
|
||||
"submitFailed": "送信に失敗しました",
|
||||
"fadeIn": "フェードイン",
|
||||
"fadeInSelection": "選択した範囲をフェードイン",
|
||||
"fadeOut": "フェードアウト",
|
||||
"fadeOutSelection": "選択した範囲をフェードアウト",
|
||||
"fadeInDisabledHint": "フェードインするには、トラックの先頭から始まる範囲を選択してください",
|
||||
"fadeOutDisabledHint": "フェードアウトするには、トラックの末尾で終わる範囲を選択してください",
|
||||
"trimEndDisabledHint": "末尾をトリミングするには、トラックの末尾で終わる範囲を選択してください",
|
||||
"trimEndSelection": "選択範囲より後の部分をすべて削除します",
|
||||
"trimStartDisabledHint": "先頭をトリミングするには、トラックの先頭から始まる範囲を選択してください",
|
||||
"trimStartSelection": "選択範囲より前の部分をすべて削除します"
|
||||
},
|
||||
"audioEditRestore": {
|
||||
"title": "保存されたオーディオ編集セッション",
|
||||
@@ -803,7 +823,7 @@
|
||||
"acceptAll": "すべて承認",
|
||||
"revertAll": "すべて元に戻す",
|
||||
"undoAll": "すべて取り消す",
|
||||
"resetAllChanges": "すべての変更を元のAI修正済み歌詞にリセット",
|
||||
"resetAllChanges": "すべての変更をリセットして、元の修正済み歌詞に戻す",
|
||||
"undo": "元に戻す",
|
||||
"redo": "やり直し",
|
||||
"findReplace": "検索/置換",
|
||||
@@ -816,7 +836,9 @@
|
||||
"playback": "再生",
|
||||
"audioLoadError": "音声を読み込めませんでした",
|
||||
"audioStillLoading": "音声はまだ読み込み中です...",
|
||||
"loadingAudio": "音声を読み込み中..."
|
||||
"loadingAudio": "音声を読み込み中...",
|
||||
"autoCorrect": "自動補正",
|
||||
"autoCorrectDesc": "文字起こしした歌詞と参照用の歌詞を比較して、修正の提案を生成します。各提案を承認するまで変更は適用されません。"
|
||||
},
|
||||
"guidance": {
|
||||
"showTips": "ヒントを表示",
|
||||
@@ -1274,6 +1296,52 @@
|
||||
},
|
||||
"toasts": {
|
||||
"customLyricsSaved": "カスタム歌詞を適用しました。カスタマイズした歌詞のタイミングが合うように、編集した各セグメントを手動で同期してください。"
|
||||
},
|
||||
"autoCorrect": {
|
||||
"accept": "提案を採用する",
|
||||
"acceptAll": "すべて採用する",
|
||||
"accepted": "採用済み",
|
||||
"adlibRemovalHint": "リファレンスにないバックボーカルを削除する提案を表示します。",
|
||||
"adlibRemovalLabel": "アドリブの削除を提案",
|
||||
"category_adlib_removal": "アドリブ",
|
||||
"category_formatting": "フォーマット",
|
||||
"category_grammar": "文法",
|
||||
"category_mishearing": "聞き間違い",
|
||||
"category_other": "その他",
|
||||
"category_repeated_chorus_fix": "コーラス",
|
||||
"collapse": "提案を折りたたむ",
|
||||
"confidenceHint": "提案を表示するために必要な信頼度の基準",
|
||||
"confidenceLabel": "提案フィルター",
|
||||
"confidence_all": "すべて表示",
|
||||
"confidence_high": "高い確信度",
|
||||
"description": "自動補正は、文字起こしした歌詞を参照用の歌詞と比較し、単語レベルで修正を提案します。すべての提案はご自身で確認でき、承認するまで適用されることはありません。",
|
||||
"dismiss": "提案を非表示にする",
|
||||
"expand": "提案を展開する",
|
||||
"insertMarker": "挿入:",
|
||||
"insertionsHint": "文字起こしで抜けている単語を追加する提案を表示します。",
|
||||
"insertionsLabel": "不足している単語の追加を提案",
|
||||
"noReferences": "この曲には参照用の歌詞がないため、提案を生成できません。まずは参照パネルから歌詞を追加してください。",
|
||||
"noSuggestions": "問題は見つかりませんでした。修正の提案はありません。",
|
||||
"reject": "提案を却下する",
|
||||
"rejectAll": "すべて却下する",
|
||||
"rejected": "却下済み",
|
||||
"runButton": "提案を取得する",
|
||||
"running": "歌詞を分析しています… 通常15〜60秒かかります。",
|
||||
"staleHint": "提案の生成後に歌詞が編集されたため、この提案は無効になりました。",
|
||||
"summary": "{total}件の提案 · 保留中 {pending}件 · 採用済み {accepted}件",
|
||||
"title": "自動補正の提案",
|
||||
"undo": "この提案を元に戻す",
|
||||
"cancel": "キャンセル",
|
||||
"close": "閉じる",
|
||||
"confidence_balanced": "バランス",
|
||||
"compareHint": "時間とコストはかかりますが、複数のモデルで一致した提案を確認できます。",
|
||||
"compareLabel": "複数のAIモデルを比較する",
|
||||
"conflictBadge": "別案",
|
||||
"conflictTooltip": "これらの単語には複数の修正候補があります。1つの候補を承認すると、他の候補は破棄されます。",
|
||||
"consensusBadge": "{consensus}/{total} モデル",
|
||||
"consensusTooltip": "提案元: {models}",
|
||||
"cachedBadge": "キャッシュ済み",
|
||||
"cachedTooltip": "同じ歌詞の過去のデータから復元されました。AIのコストは発生していません。"
|
||||
}
|
||||
},
|
||||
"instrumentalReview": {
|
||||
@@ -1508,5 +1576,8 @@
|
||||
"estimatedLabel": "目安 — 最終的な料金はダウンロード後に確定します",
|
||||
"reconcileTitle": "この曲は想定より長くなっています",
|
||||
"cancel": "キャンセル"
|
||||
},
|
||||
"karaokeBackgroundPreview": {
|
||||
"loading": "背景プレビューを読み込んでいます"
|
||||
}
|
||||
}
|
||||
Loaded 100 of 144 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user