mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-04 00:56:43 +09:00
Compare commits
No files matched your search
@@ -1921,7 +1921,7 @@ 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,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,EDGE_AUTH_MODE=enforce,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
|
||||
--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,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,EDGE_AUTH_MODE=enforce,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,EDGE_ORIGIN_SECRET=edge-origin-secret:latest"
|
||||
|
||||
- name: Update Cloud Run Jobs with new image
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
name: PyPI prune reminder
|
||||
|
||||
# PyPI caps total *project* size at 10 GB. karaoke-gen auto-publishes a ~62 MiB
|
||||
# wheel on every merge to main (~3 GB/month), so the project refills the cap
|
||||
# every few months and `poetry publish` then fails with "Project size too large".
|
||||
#
|
||||
# PyPI has NO deletion API (upload tokens are upload-only), so this can't
|
||||
# auto-delete. Instead it runs monthly, computes the retention plan
|
||||
# (scripts/prune_pypi_releases.py), and opens/updates a single tracking issue
|
||||
# containing a paste-into-browser-console snippet you run on your logged-in PyPI
|
||||
# releases page to actually prune. No secrets are stored.
|
||||
#
|
||||
# See docs/PYPI-STORAGE-PRUNE.md.
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# 09:00 UTC on the 1st of each month.
|
||||
- cron: "0 9 1 * *"
|
||||
workflow_dispatch: {}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
prune-reminder:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PROJECT: karaoke-gen
|
||||
KEEP_DAYS: "60"
|
||||
# Only nag once the project crosses this watermark — pruning holds it at
|
||||
# ~4-7 GB, and there are always old releases to consolidate, so without a
|
||||
# threshold this would open an issue every month for no real reason. 7 GB
|
||||
# leaves ~1 month of ~3 GB/month growth before the 10 GB cap.
|
||||
NAG_THRESHOLD_GB: "7"
|
||||
ISSUE_TITLE: "🧹 PyPI storage prune due: karaoke-gen"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python 3.13
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.13"
|
||||
|
||||
- name: Compute prune plan
|
||||
id: plan
|
||||
run: |
|
||||
python scripts/prune_pypi_releases.py \
|
||||
--project "$PROJECT" --keep-days "$KEEP_DAYS" \
|
||||
--format markdown --output plan.md
|
||||
python scripts/prune_pypi_releases.py \
|
||||
--project "$PROJECT" --keep-days "$KEEP_DAYS" \
|
||||
--format json --output plan.json
|
||||
python - <<'PY' >> "$GITHUB_OUTPUT"
|
||||
import json, os
|
||||
d = json.load(open("plan.json"))
|
||||
threshold = float(os.environ["NAG_THRESHOLD_GB"])
|
||||
should_nag = d["delete_count"] > 0 and d["current_gb"] >= threshold
|
||||
print(f"delete_count={d['delete_count']}")
|
||||
print(f"reclaimable_gb={d['reclaimable_gb']:.2f}")
|
||||
print(f"current_gb={d['current_gb']:.2f}")
|
||||
print(f"should_nag={'true' if should_nag else 'false'}")
|
||||
PY
|
||||
|
||||
- name: Job summary
|
||||
run: cat plan.md >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
- name: Open or update tracking issue
|
||||
if: steps.plan.outputs.should_nag == 'true'
|
||||
run: |
|
||||
# Search by a stable ASCII substring (emoji in search queries is
|
||||
# flaky); the exact-title jq filter below is the real dedupe guard.
|
||||
existing=$(gh issue list --repo "$GITHUB_REPOSITORY" \
|
||||
--state open --search "PyPI storage prune due in:title" \
|
||||
--json number,title \
|
||||
--jq "map(select(.title == \"$ISSUE_TITLE\")) | .[0].number // empty")
|
||||
note="🔁 Refreshed $(date -u +%Y-%m-%d): ${{ steps.plan.outputs.delete_count }} releases prunable, ~${{ steps.plan.outputs.reclaimable_gb }} GB reclaimable (project at ${{ steps.plan.outputs.current_gb }} GB)."
|
||||
if [ -n "$existing" ]; then
|
||||
echo "Updating existing issue #$existing"
|
||||
gh issue edit "$existing" --repo "$GITHUB_REPOSITORY" --body-file plan.md
|
||||
gh issue comment "$existing" --repo "$GITHUB_REPOSITORY" --body "$note"
|
||||
else
|
||||
echo "Creating new tracking issue"
|
||||
gh issue create --repo "$GITHUB_REPOSITORY" \
|
||||
--title "$ISSUE_TITLE" --body-file plan.md
|
||||
fi
|
||||
@@ -93,6 +93,10 @@ class JobUpdateRequest(BaseModel):
|
||||
youtube_description_template: Optional[str] = None
|
||||
customer_email: Optional[str] = None
|
||||
customer_notes: Optional[str] = None
|
||||
# Review autonomy: "auto" (skip review when confident) | "always_review"
|
||||
review_mode: Optional[str] = None
|
||||
# Backing-vocals preference: "auto" | "clean" | "review"
|
||||
backing_preference: Optional[str] = None
|
||||
|
||||
# Editable boolean fields
|
||||
enable_cdg: Optional[bool] = None
|
||||
@@ -129,6 +133,8 @@ EDITABLE_JOB_FIELDS = {
|
||||
"non_interactive",
|
||||
"prep_only",
|
||||
"is_private",
|
||||
"review_mode",
|
||||
"backing_preference",
|
||||
}
|
||||
|
||||
|
||||
@@ -988,6 +994,23 @@ async def update_job(
|
||||
f"no account existed, created one"
|
||||
)
|
||||
|
||||
# The executor treats any value other than "auto" as an enforcement blocker,
|
||||
# so a typo (e.g. "always-review") would silently force human review.
|
||||
if "review_mode" in updates and updates["review_mode"] not in ("auto", "always_review"):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail='review_mode must be "auto" or "always_review"',
|
||||
)
|
||||
|
||||
# backing_preference likewise gates the instrumental decision — reject typos.
|
||||
if "backing_preference" in updates and updates["backing_preference"] not in (
|
||||
"auto", "clean", "review",
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail='backing_preference must be "auto", "clean", or "review"',
|
||||
)
|
||||
|
||||
# Check if we're toggling is_private from False to True on a completed job
|
||||
# If so, auto-delete existing outputs (YouTube, Dropbox, GDrive)
|
||||
toggling_to_private = (
|
||||
@@ -1877,6 +1900,133 @@ async def delete_job_outputs(
|
||||
)
|
||||
|
||||
|
||||
class OrphanedOutputsCleanupRequest(BaseModel):
|
||||
"""Explicit targets for cleaning up distributed outputs whose owning job doc no
|
||||
longer exists (e.g. a job deleted before its outputs were cleaned up)."""
|
||||
youtube_video_id: Optional[str] = None
|
||||
dropbox_folder_path: Optional[str] = None
|
||||
gdrive_file_ids: List[str] = []
|
||||
mirror_filename_prefix: Optional[str] = None # e.g. "NOMAD-1583 - Mazzy Star"
|
||||
|
||||
|
||||
@router.post("/orphaned-outputs/cleanup")
|
||||
async def cleanup_orphaned_outputs(
|
||||
req: OrphanedOutputsCleanupRequest,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
) -> dict:
|
||||
"""
|
||||
Delete distributed outputs that no longer have an owning job doc (admin only).
|
||||
|
||||
The per-job cleanup endpoints (delete-outputs, cleanup-distribution) all require
|
||||
the job document to resolve file IDs and paths. When a job was deleted while its
|
||||
outputs were still published (the pre-fix DELETE /api/jobs/{id} behavior), those
|
||||
outputs are orphaned and must be targeted explicitly:
|
||||
|
||||
- youtube_video_id: YouTube video to delete (bare video ID)
|
||||
- dropbox_folder_path: full Dropbox folder path to delete
|
||||
- gdrive_file_ids: Google Drive file IDs to delete (from upload logs)
|
||||
- mirror_filename_prefix: "NOMAD-#### - Artist..." prefix for kjbox GCS mirror
|
||||
objects (masters + vocals guides); must include artist text so it can't match
|
||||
another track sharing a recycled brand code
|
||||
|
||||
Returns per-service results; each requested service reports success/failed/error.
|
||||
"""
|
||||
admin_email = auth_data.user_email or "unknown"
|
||||
if not any([req.youtube_video_id, req.dropbox_folder_path, req.gdrive_file_ids, req.mirror_filename_prefix]):
|
||||
raise HTTPException(status_code=400, detail="No cleanup targets specified")
|
||||
|
||||
if req.mirror_filename_prefix:
|
||||
from backend.services.nomad_master_mirror import is_safe_track_filename_prefix
|
||||
|
||||
if not is_safe_track_filename_prefix(req.mirror_filename_prefix):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=(
|
||||
f"Unsafe mirror_filename_prefix {req.mirror_filename_prefix!r}: must be "
|
||||
f"'NOMAD-#### - Artist...' (brand code plus artist text) so it cannot "
|
||||
f"match another track sharing a recycled brand code"
|
||||
),
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"Admin {admin_email} cleaning up orphaned outputs: "
|
||||
f"youtube={req.youtube_video_id}, dropbox={req.dropbox_folder_path}, "
|
||||
f"gdrive={req.gdrive_file_ids}, mirror_prefix={req.mirror_filename_prefix}"
|
||||
)
|
||||
results: Dict[str, Any] = {}
|
||||
|
||||
if req.youtube_video_id:
|
||||
try:
|
||||
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
|
||||
from backend.services.youtube_service import get_youtube_service
|
||||
|
||||
youtube_service = get_youtube_service()
|
||||
if youtube_service.is_configured:
|
||||
finalise = KaraokeFinalise(
|
||||
dry_run=False,
|
||||
non_interactive=True,
|
||||
user_youtube_credentials=youtube_service.get_credentials_dict(),
|
||||
)
|
||||
success = finalise.delete_youtube_video(req.youtube_video_id)
|
||||
results["youtube"] = {
|
||||
"status": "success" if success else "failed",
|
||||
"video_id": req.youtube_video_id,
|
||||
}
|
||||
else:
|
||||
results["youtube"] = {"status": "failed", "reason": "YouTube credentials not configured"}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting orphaned YouTube video {req.youtube_video_id}: {e}", exc_info=True)
|
||||
results["youtube"] = {"status": "error", "error": str(e)}
|
||||
|
||||
if req.dropbox_folder_path:
|
||||
try:
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
|
||||
dropbox = get_dropbox_service()
|
||||
if dropbox.is_configured:
|
||||
success = dropbox.delete_folder(req.dropbox_folder_path)
|
||||
results["dropbox"] = {
|
||||
"status": "success" if success else "failed",
|
||||
"path": req.dropbox_folder_path,
|
||||
}
|
||||
else:
|
||||
results["dropbox"] = {"status": "failed", "reason": "Dropbox credentials not configured"}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting orphaned Dropbox folder {req.dropbox_folder_path}: {e}", exc_info=True)
|
||||
results["dropbox"] = {"status": "error", "error": str(e)}
|
||||
|
||||
if req.gdrive_file_ids:
|
||||
try:
|
||||
from backend.services.gdrive_service import get_gdrive_service
|
||||
|
||||
gdrive = get_gdrive_service()
|
||||
if gdrive.is_configured:
|
||||
delete_results = gdrive.delete_files(req.gdrive_file_ids)
|
||||
all_success = all(delete_results.values())
|
||||
results["gdrive"] = {
|
||||
"status": "success" if all_success else "partial",
|
||||
"files": delete_results,
|
||||
}
|
||||
else:
|
||||
results["gdrive"] = {"status": "failed", "reason": "Google Drive credentials not configured"}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting orphaned GDrive files {req.gdrive_file_ids}: {e}", exc_info=True)
|
||||
results["gdrive"] = {"status": "error", "error": str(e)}
|
||||
|
||||
if req.mirror_filename_prefix:
|
||||
try:
|
||||
from backend.services.nomad_master_mirror import NomadMasterMirror
|
||||
|
||||
counts = NomadMasterMirror().delete_track_objects_by_filename_prefix(req.mirror_filename_prefix)
|
||||
results["mirror"] = {"status": "success", **counts}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting orphaned mirror objects for {req.mirror_filename_prefix}: {e}", exc_info=True)
|
||||
results["mirror"] = {"status": "error", "error": str(e)}
|
||||
|
||||
logger.info(f"Orphaned-outputs cleanup by {admin_email} complete: {results}")
|
||||
return {"status": "complete", "results": results}
|
||||
|
||||
|
||||
@router.get("/jobs/{job_id}/completion-message", response_model=CompletionMessageResponse)
|
||||
async def get_job_completion_message(
|
||||
job_id: str,
|
||||
|
||||
@@ -143,6 +143,10 @@ class AudioSearchRequest(BaseModel):
|
||||
# Non-interactive mode
|
||||
non_interactive: bool = Field(False, description="Skip interactive steps (lyrics review, instrumental selection)")
|
||||
|
||||
# Review autonomy + backing-vocals preference (full-auto review, workstream C)
|
||||
review_mode: str = Field("auto", description="'auto' (skip review when confident) or 'always_review'")
|
||||
backing_preference: str = Field("auto", description="'auto' (retain backing where safe), 'clean', or 'review'")
|
||||
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
|
||||
|
||||
@@ -803,6 +807,8 @@ async def search_audio(
|
||||
auto_download=body.auto_download,
|
||||
request_metadata=request_metadata,
|
||||
non_interactive=body.non_interactive,
|
||||
review_mode=body.review_mode,
|
||||
backing_preference=body.backing_preference,
|
||||
is_private=body.is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
|
||||
@@ -258,6 +258,9 @@ class BulkSettings(BaseModel):
|
||||
is_private: bool = False
|
||||
skip_audio_edit: bool = True
|
||||
skip_customization: bool = True
|
||||
# Full-auto review (workstream C): batch default autonomy + backing preference.
|
||||
review_mode: str = "auto"
|
||||
backing_preference: str = "auto"
|
||||
|
||||
|
||||
class BulkSubmitRequest(BaseModel):
|
||||
@@ -342,6 +345,8 @@ async def bulk_submit(
|
||||
audio_search_title=song.title.strip(),
|
||||
auto_download=False,
|
||||
is_private=body.settings.is_private,
|
||||
review_mode=body.settings.review_mode,
|
||||
backing_preference=body.settings.backing_preference,
|
||||
brand_prefix=settings.default_brand_prefix,
|
||||
enable_youtube_upload=settings.default_enable_youtube_upload,
|
||||
youtube_description=settings.default_youtube_description,
|
||||
|
||||
@@ -185,6 +185,10 @@ class CreateJobFromUrlRequest(BaseModel):
|
||||
# Audio editing
|
||||
requires_audio_edit: bool = Field(False, description="Pause after download for user to edit input audio")
|
||||
|
||||
# Review autonomy + backing-vocals preference (full-auto review, workstream C)
|
||||
review_mode: str = Field("auto", description="'auto' (skip review when confident) or 'always_review'")
|
||||
backing_preference: str = Field("auto", description="'auto' (retain backing where safe), 'clean', or 'review'")
|
||||
|
||||
|
||||
class CreateJobFromUrlResponse(BaseModel):
|
||||
"""Response from creating a job from URL."""
|
||||
@@ -243,6 +247,10 @@ class CreateJobWithUploadUrlsRequest(BaseModel):
|
||||
prep_only: bool = Field(False, description="Stop after review phase, don't run finalisation")
|
||||
keep_brand_code: Optional[str] = Field(None, description="Preserve existing brand code instead of generating new one")
|
||||
|
||||
# Review autonomy + backing-vocals preference (full-auto review, workstream C)
|
||||
review_mode: str = Field("auto", description="'auto' (skip review when confident) or 'always_review'")
|
||||
backing_preference: str = Field("auto", description="'auto' (retain backing where safe), 'clean', or 'review'")
|
||||
|
||||
# Non-interactive mode
|
||||
non_interactive: bool = Field(False, description="Skip interactive steps (lyrics review, instrumental selection)")
|
||||
|
||||
@@ -466,6 +474,9 @@ async def upload_and_create_job(
|
||||
other_stems_models: Optional[str] = Form(None, description="Comma-separated list of models for other stems (bass, drums, guitar, etc.)"),
|
||||
# Non-interactive mode
|
||||
non_interactive: bool = Form(False, description="Skip interactive steps (lyrics review, instrumental selection)"),
|
||||
# Review autonomy + backing-vocals preference (full-auto review, workstream C)
|
||||
review_mode: str = Form("auto", description="'auto' (skip review when confident) or 'always_review'"),
|
||||
backing_preference: str = Form("auto", description="'auto' (retain backing where safe), 'clean', or 'review'"),
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = Form(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive"),
|
||||
# Audio editing
|
||||
@@ -694,6 +705,9 @@ async def upload_and_create_job(
|
||||
request_metadata=request_metadata,
|
||||
# Non-interactive mode
|
||||
non_interactive=non_interactive,
|
||||
# Review autonomy + backing-vocals preference (full-auto review)
|
||||
review_mode=review_mode,
|
||||
backing_preference=backing_preference,
|
||||
# Private (non-published) track mode
|
||||
is_private=is_private,
|
||||
# Tenant scoping
|
||||
@@ -1283,6 +1297,8 @@ async def create_job_with_upload_urls(
|
||||
other_stems_models=body.other_stems_models,
|
||||
request_metadata=request_metadata,
|
||||
non_interactive=body.non_interactive,
|
||||
review_mode=body.review_mode,
|
||||
backing_preference=body.backing_preference,
|
||||
is_private=effective_is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
@@ -1941,6 +1957,8 @@ async def create_job_from_url(
|
||||
other_stems_models=body.other_stems_models,
|
||||
request_metadata=request_metadata,
|
||||
non_interactive=body.non_interactive,
|
||||
review_mode=body.review_mode,
|
||||
backing_preference=body.backing_preference,
|
||||
is_private=body.is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
|
||||
@@ -901,10 +901,41 @@ async def recover_stuck_jobs(
|
||||
if _repark_stalled_render(job_manager, job_id):
|
||||
reparked.append(job_id)
|
||||
|
||||
# --- REVIEW_COMPLETE with no render started: lost render trigger ---
|
||||
# Both the human complete-review endpoint (fire-and-forget task) and the
|
||||
# auto-approval executor can lose the render trigger (e.g. Cloud Tasks
|
||||
# enqueue failure). Without this, the job sits at review_complete forever
|
||||
# with no error and no Retry button. Re-trigger is idempotent (worker
|
||||
# generation fence + status validation).
|
||||
# REVIEW_COMPLETE is a transient state (render normally starts in seconds),
|
||||
# so the population is tiny — scan it all (no limit, which could otherwise
|
||||
# return only fresh jobs and starve stalled ones) and cap re-triggers per
|
||||
# tick to bound the blast radius.
|
||||
render_retriggered = []
|
||||
rc_query = jobs_ref.where(
|
||||
filter=FieldFilter("status", "==", JobStatus.REVIEW_COMPLETE.value)
|
||||
).stream()
|
||||
for doc in rc_query:
|
||||
if len(render_retriggered) >= RENDER_RETRIGGERS_PER_TICK:
|
||||
break
|
||||
job_id = (doc.to_dict() or {}).get("job_id", doc.id)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
continue
|
||||
if not _review_complete_stalled(job):
|
||||
continue
|
||||
logger.warning(f"[job:{job_id}] REVIEW_COMPLETE stalled >10 min with no render — re-triggering")
|
||||
try:
|
||||
if await worker_service.trigger_render_video_worker(job_id):
|
||||
render_retriggered.append(job_id)
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] render re-trigger failed: {e}")
|
||||
|
||||
logger.info(
|
||||
f"RECOVER_STUCK_JOBS complete: recovered={len(recovered)} "
|
||||
f"download_parked={len(download_parked)} download_retried={len(download_retried)} "
|
||||
f"download_timed_out={len(download_timed_out)} reparked={len(reparked)}"
|
||||
f"download_timed_out={len(download_timed_out)} reparked={len(reparked)} "
|
||||
f"render_retriggered={len(render_retriggered)}"
|
||||
)
|
||||
add_span_event("recovery_complete", {
|
||||
"recovered_count": len(recovered),
|
||||
@@ -923,9 +954,38 @@ async def recover_stuck_jobs(
|
||||
"download_timed_out_jobs": download_timed_out,
|
||||
"reparked_render_jobs": reparked,
|
||||
"reparked_render_count": len(reparked),
|
||||
"render_retriggered_jobs": render_retriggered,
|
||||
"render_retriggered_count": len(render_retriggered),
|
||||
}
|
||||
|
||||
|
||||
REVIEW_COMPLETE_STALL_SECONDS = 10 * 60 # render normally starts within seconds
|
||||
RENDER_RETRIGGERS_PER_TICK = 10 # bound the blast radius per 5-min tick
|
||||
|
||||
|
||||
def _review_complete_stalled(job) -> bool:
|
||||
"""True when a REVIEW_COMPLETE job has sat >10 min with no render underway.
|
||||
|
||||
``render_progress`` is cleared on review completion and (re)written by the
|
||||
render worker — its absence plus a stale ``updated_at`` means the trigger
|
||||
was lost.
|
||||
"""
|
||||
if (job.state_data or {}).get("render_progress"):
|
||||
return False
|
||||
updated_at = getattr(job, "updated_at", None)
|
||||
if updated_at is None:
|
||||
return False
|
||||
from datetime import datetime, timezone as _tz
|
||||
now = datetime.now(_tz.utc)
|
||||
if updated_at.tzinfo is None:
|
||||
now = datetime.utcnow()
|
||||
try:
|
||||
age = (now - updated_at).total_seconds()
|
||||
except TypeError:
|
||||
return False
|
||||
return age > REVIEW_COMPLETE_STALL_SECONDS
|
||||
|
||||
|
||||
# Torrent sources whose downloads are worth auto-retrying over a long window —
|
||||
# they fail transiently when a rare release has few/intermittent seeders or the
|
||||
# private tracker is briefly unreachable. Non-torrent sources (YouTube/Spotify/
|
||||
|
||||
+88
-41
@@ -813,27 +813,53 @@ async def delete_job(
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionDelete"))
|
||||
|
||||
# Recycle any unreturned brand code before deleting the job record
|
||||
# If the job still has published outputs (brand code allocated, outputs never
|
||||
# cleaned up), delete the distributed files BEFORE deleting the job record.
|
||||
# The brand code is recycled inside the cleanup only once Dropbox + GDrive are
|
||||
# confirmed clean: recycling while files remain in the public share hands the
|
||||
# same NOMAD-#### to a future job and creates duplicate brand codes (NOMAD-1583
|
||||
# incident, 2026-08-29). If cleanup fails, the code stays allocated — a sequence
|
||||
# gap the GDrive validator surfaces, which is safe and recoverable.
|
||||
state_data = job.state_data or {}
|
||||
brand_code = state_data.get('brand_code')
|
||||
if brand_code:
|
||||
if not job.outputs_deleted_at:
|
||||
logger.warning(
|
||||
f"Deleting job {job_id} with brand_code {brand_code} whose outputs "
|
||||
f"were not cleaned up first. Brand code will be recycled but "
|
||||
f"distributed files (GDrive/Dropbox/YouTube) may be orphaned."
|
||||
distribution_cleanup = None
|
||||
if brand_code and not job.outputs_deleted_at:
|
||||
if not delete_files:
|
||||
# Published outputs cannot be preserved when their job record is
|
||||
# deleted — the record holds the only file IDs/paths needed to ever
|
||||
# clean them up or reconcile the brand code.
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=t(locale, "jobs.deletePublishedRequiresFiles"),
|
||||
)
|
||||
logger.warning(
|
||||
f"Deleting job {job_id} with brand_code {brand_code} whose outputs "
|
||||
f"were not cleaned up first — running distribution cleanup before delete."
|
||||
)
|
||||
distribution_cleanup = _run_distribution_cleanup(job_id, job)
|
||||
incomplete = [
|
||||
svc for svc in ("youtube", "dropbox", "gdrive")
|
||||
if distribution_cleanup.get(svc, {}).get("status") in ("failed", "partial", "error")
|
||||
]
|
||||
if incomplete:
|
||||
# Keep the job record: it holds the file IDs/paths needed to retry.
|
||||
# Deleting it anyway would orphan the remaining published files with
|
||||
# no way to resolve them later (NOMAD-1583 incident).
|
||||
logger.error(
|
||||
f"Aborting delete of job {job_id}: distribution cleanup incomplete "
|
||||
f"for {incomplete} — {distribution_cleanup}"
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail=t(locale, "jobs.cleanupFailed", services=", ".join(incomplete)),
|
||||
)
|
||||
try:
|
||||
from backend.services.brand_code_service import BrandCodeService, get_brand_code_service
|
||||
prefix, number = BrandCodeService.parse_brand_code(brand_code)
|
||||
get_brand_code_service().recycle_brand_code(prefix, number)
|
||||
logger.info(f"Recycled brand code {brand_code} before deleting job {job_id}")
|
||||
except (ValueError, Exception) as e:
|
||||
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
|
||||
|
||||
job_manager.delete_job(job_id, delete_files=delete_files)
|
||||
|
||||
return {"status": "success", "message": f"Job {job_id} deleted"}
|
||||
response = {"status": "success", "message": f"Job {job_id} deleted"}
|
||||
if distribution_cleanup is not None:
|
||||
response["distribution_cleanup"] = distribution_cleanup
|
||||
return response
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
@@ -2165,41 +2191,23 @@ async def get_worker_logs(
|
||||
}
|
||||
|
||||
|
||||
@router.post("/{job_id}/cleanup-distribution")
|
||||
async def cleanup_distribution(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
delete_job: bool = True,
|
||||
auth_result: AuthResult = Depends(require_admin)
|
||||
) -> dict:
|
||||
def _run_distribution_cleanup(job_id: str, job) -> dict:
|
||||
"""
|
||||
Clean up all distributed content for a job (YouTube, Dropbox, Google Drive).
|
||||
Delete a job's distributed outputs (YouTube video, Dropbox folder, Google Drive
|
||||
files, kjbox GCS mirror objects) and recycle its brand code once Dropbox AND
|
||||
GDrive are confirmed clean.
|
||||
|
||||
This admin-only endpoint is designed for E2E test cleanup. It:
|
||||
1. Deletes YouTube video (if uploaded)
|
||||
2. Deletes Dropbox folder (if uploaded)
|
||||
3. Deletes Google Drive files (if uploaded)
|
||||
4. Optionally deletes the job itself
|
||||
|
||||
Args:
|
||||
job_id: Job ID to clean up
|
||||
delete_job: If True, also delete the job after cleaning up distribution
|
||||
|
||||
Returns:
|
||||
Cleanup results for each service
|
||||
Shared by the admin cleanup-distribution endpoint and job deletion. Deleting a
|
||||
job whose outputs are still published MUST run this first: recycling the brand
|
||||
code while the files remain in the public share hands the same NOMAD-#### to a
|
||||
future job and creates duplicate brand codes (NOMAD-1583 incident, 2026-08-29).
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
state_data = job.state_data or {}
|
||||
results = {
|
||||
"job_id": job_id,
|
||||
"youtube": {"status": "skipped", "reason": "no youtube_url in state_data"},
|
||||
"dropbox": {"status": "skipped", "reason": "no brand_code or dropbox_path"},
|
||||
"gdrive": {"status": "skipped", "reason": "no gdrive_files in state_data"},
|
||||
"job_deleted": False
|
||||
}
|
||||
|
||||
# Clean up YouTube
|
||||
@@ -2358,6 +2366,41 @@ async def cleanup_distribution(
|
||||
f"collisions with leftover GDrive files."
|
||||
)
|
||||
|
||||
|
||||
return results
|
||||
|
||||
|
||||
@router.post("/{job_id}/cleanup-distribution")
|
||||
async def cleanup_distribution(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
delete_job: bool = True,
|
||||
auth_result: AuthResult = Depends(require_admin)
|
||||
) -> dict:
|
||||
"""
|
||||
Clean up all distributed content for a job (YouTube, Dropbox, Google Drive).
|
||||
|
||||
This admin-only endpoint is designed for E2E test cleanup. It:
|
||||
1. Deletes YouTube video (if uploaded)
|
||||
2. Deletes Dropbox folder (if uploaded)
|
||||
3. Deletes Google Drive files (if uploaded)
|
||||
4. Optionally deletes the job itself
|
||||
|
||||
Args:
|
||||
job_id: Job ID to clean up
|
||||
delete_job: If True, also delete the job after cleaning up distribution
|
||||
|
||||
Returns:
|
||||
Cleanup results for each service
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
results = _run_distribution_cleanup(job_id, job)
|
||||
results["job_deleted"] = False
|
||||
|
||||
# Delete the job if requested
|
||||
if delete_job:
|
||||
try:
|
||||
@@ -2386,6 +2429,8 @@ class CreateFromSearchRequest(BaseModel):
|
||||
display_title: Optional[str] = Field(None, description="Display title override for title screens/filenames")
|
||||
is_private: bool = Field(False, description="Private track: Dropbox only, no YouTube/GDrive")
|
||||
requires_audio_edit: bool = Field(False, description="Pause after download for user to edit input audio")
|
||||
review_mode: str = Field("auto", description="'auto' (skip review when confident) or 'always_review'")
|
||||
backing_preference: str = Field("auto", description="'auto' (retain backing where safe), 'clean', or 'review'")
|
||||
|
||||
@validator('display_artist', 'display_title')
|
||||
def strip_whitespace(cls, v):
|
||||
@@ -2541,6 +2586,8 @@ async def create_job_from_search(
|
||||
audio_search_title=session_title,
|
||||
request_metadata=request_metadata,
|
||||
is_private=body.is_private,
|
||||
review_mode=body.review_mode,
|
||||
backing_preference=body.backing_preference,
|
||||
tenant_id=tenant_id,
|
||||
locale=get_full_locale_from_request(request),
|
||||
)
|
||||
|
||||
+605
-145
@@ -210,6 +210,156 @@ def _get_audio_hash(job_id: str) -> str:
|
||||
return hashlib.md5(job_id.encode()).hexdigest()
|
||||
|
||||
|
||||
def _preview_error_marker_path(job_id: str, preview_hash: str) -> str:
|
||||
"""GCS marker written when a background preview encode fails permanently.
|
||||
|
||||
The status-poll endpoint reports it so the review UI can stop polling and
|
||||
show a real error. GCS (not memory) because polls may hit a different
|
||||
Cloud Run instance than the one running the encode task.
|
||||
"""
|
||||
return f"jobs/{job_id}/previews/{preview_hash}.error.json"
|
||||
|
||||
|
||||
def _record_preview_video(job_id: str, preview_hash: str, gcs_path: str) -> None:
|
||||
if job_id not in _preview_videos:
|
||||
_preview_videos[job_id] = {}
|
||||
_preview_videos[job_id][preview_hash] = gcs_path
|
||||
|
||||
|
||||
def _prepare_preview_inputs(job, temp_dir: str, storage, is_duet: bool):
|
||||
"""Download corrections/audio/styles for a preview render into temp_dir.
|
||||
|
||||
Returns (correction_result, audio_path, output_config). Blocking (GCS
|
||||
downloads) — shared by the preview endpoint and the local-encode fallback.
|
||||
"""
|
||||
job_id = job.job_id
|
||||
with create_span("download-corrections-and-audio") as download_span:
|
||||
corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
corrections_path = os.path.join(temp_dir, "corrections.json")
|
||||
storage.download_file(corrections_gcs, corrections_path)
|
||||
|
||||
with open(corrections_path, 'r', encoding='utf-8') as f:
|
||||
original_data = json.load(f)
|
||||
|
||||
audio_path = os.path.join(temp_dir, "audio.flac")
|
||||
storage.download_file(job.input_media_gcs_path, audio_path)
|
||||
download_span.set_attribute("audio_gcs_path", job.input_media_gcs_path)
|
||||
|
||||
correction_result = CorrectionResult.from_dict(original_data)
|
||||
add_span_event("corrections_loaded")
|
||||
|
||||
with create_span("load-styles") as styles_span:
|
||||
styles_path, _ = load_styles_from_gcs(
|
||||
style_params_gcs_path=job.style_params_gcs_path,
|
||||
style_assets=job.style_assets,
|
||||
temp_dir=temp_dir,
|
||||
download_func=storage.download_file,
|
||||
logger=logger,
|
||||
)
|
||||
styles_span.set_attribute("styles_path", styles_path)
|
||||
|
||||
output_dir = os.path.join(temp_dir, "output")
|
||||
cache_dir = os.path.join(temp_dir, "cache")
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
os.makedirs(cache_dir, exist_ok=True)
|
||||
|
||||
output_config = OutputConfig(
|
||||
output_styles_json=styles_path,
|
||||
output_dir=output_dir,
|
||||
cache_dir=cache_dir,
|
||||
video_resolution="360p",
|
||||
is_duet=is_duet,
|
||||
)
|
||||
return correction_result, audio_path, output_config
|
||||
|
||||
|
||||
def _render_preview_locally(job, updated_data: Dict[str, Any], is_duet: bool) -> str:
|
||||
"""Render the full 360p preview locally and upload it to GCS.
|
||||
|
||||
Blocking (downloads + ffmpeg) — call via asyncio.to_thread. Used when GCE
|
||||
preview encoding is disabled and as the fallback when it fails.
|
||||
"""
|
||||
job_id = job.job_id
|
||||
storage = StorageService()
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
correction_result, audio_path, output_config = _prepare_preview_inputs(
|
||||
job=job, temp_dir=temp_dir, storage=storage, is_duet=is_duet
|
||||
)
|
||||
|
||||
with create_span("render-preview-video-local") as render_span:
|
||||
render_span.set_attribute("resolution", "360p")
|
||||
result = CorrectionOperations.generate_preview_video(
|
||||
correction_result=correction_result,
|
||||
updated_data=updated_data,
|
||||
output_config=output_config,
|
||||
audio_filepath=audio_path,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
logger=logger,
|
||||
ass_only=False,
|
||||
)
|
||||
preview_hash = result["preview_hash"]
|
||||
video_path = result["video_path"]
|
||||
add_span_event("render_complete")
|
||||
|
||||
with create_span("upload-preview-video") as upload_span:
|
||||
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
|
||||
storage.upload_file(video_path, preview_gcs_path)
|
||||
upload_span.set_attribute("gcs_path", preview_gcs_path)
|
||||
|
||||
_record_preview_video(job_id, preview_hash, preview_gcs_path)
|
||||
return preview_hash
|
||||
|
||||
|
||||
async def _encode_preview_in_background(
|
||||
job,
|
||||
preview_hash: str,
|
||||
encode_kwargs: Dict[str, Any],
|
||||
updated_data: Dict[str, Any],
|
||||
is_duet: bool,
|
||||
) -> None:
|
||||
"""Run the GCE preview encode without holding the HTTP request open.
|
||||
|
||||
Cold-starting a fallback encoder VM can take 2-3 minutes — longer than
|
||||
Cloudflare's ~100s edge timeout — so POST /preview-video returns as soon
|
||||
as the ASS is uploaded and the browser polls the /status endpoint, which
|
||||
reports ready once the mp4 exists in GCS. On GCE failure this falls back
|
||||
to a local render; if that also fails an error marker is written so the
|
||||
poll can surface the failure instead of spinning until its timeout.
|
||||
"""
|
||||
job_id = job.job_id
|
||||
storage = StorageService()
|
||||
encoding_service = get_encoding_service()
|
||||
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
|
||||
|
||||
with job_log_context(job_id, worker="preview"):
|
||||
try:
|
||||
with create_span("gce-preview-encoding", {"job_id": job_id, "preview_hash": preview_hash}) as gce_span:
|
||||
gce_result = await encoding_service.encode_preview_video(**encode_kwargs)
|
||||
gce_span.set_attribute("gce_status", gce_result.get("status"))
|
||||
_record_preview_video(job_id, preview_hash, preview_gcs_path)
|
||||
logger.info(f"Job {job_id}: Preview generated via GCE: {preview_hash}")
|
||||
return
|
||||
except Exception as gce_error:
|
||||
logger.warning(f"Job {job_id}: GCE preview encoding failed, falling back to local: {gce_error}")
|
||||
|
||||
try:
|
||||
await asyncio.to_thread(_render_preview_locally, job, updated_data, is_duet)
|
||||
logger.info(f"Job {job_id}: Preview generated locally after GCE failure: {preview_hash}")
|
||||
except Exception as local_error:
|
||||
logger.error(
|
||||
f"Job {job_id}: Preview generation failed (GCE and local fallback): {local_error}",
|
||||
exc_info=True,
|
||||
)
|
||||
try:
|
||||
storage.upload_json(
|
||||
_preview_error_marker_path(job_id, preview_hash),
|
||||
{"error": str(local_error)},
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(f"Job {job_id}: Failed to write preview error marker")
|
||||
|
||||
|
||||
# Cross-job search endpoint MUST be registered before {job_id} routes
|
||||
# to avoid FastAPI matching "sessions" as a job_id path parameter.
|
||||
@router.get("/sessions/search")
|
||||
@@ -237,9 +387,159 @@ async def ping(job_id: str):
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
def _dev_audio_proxy_enabled() -> bool:
|
||||
"""True when the backend should proxy review audio bytes instead of returning
|
||||
GCS signed URLs. Enabled via ``REVIEW_AUDIO_PROXY=1`` on a LOCAL dev backend
|
||||
that lacks URL-signing credentials (plain user ADC can't sign). Never set in
|
||||
prod — prod keeps the lighter signed-URL/redirect path.
|
||||
"""
|
||||
return os.environ.get("REVIEW_AUDIO_PROXY", "").lower() in ("1", "true", "yes")
|
||||
|
||||
|
||||
def _dev_audio_url(job_id: str, gcs_path: Optional[str], base_url: str = "") -> Optional[str]:
|
||||
"""Build an ABSOLUTE dev-proxy URL for a review audio/image artifact.
|
||||
|
||||
The URL is used directly as an ``<audio>``/``<img>`` src by the frontend, which
|
||||
resolves relative URLs against the page origin (localhost:3000), not the API host.
|
||||
So we must return the full backend URL (``request.base_url``, e.g. http://127.0.0.1:8000/).
|
||||
"""
|
||||
if not gcs_path:
|
||||
return None
|
||||
from urllib.parse import quote
|
||||
return f"{base_url.rstrip('/')}/api/review/{job_id}/dev-audio?path={quote(gcs_path, safe='')}"
|
||||
|
||||
|
||||
def _reconstruct_post_ai_segments(
|
||||
raw_segments: List[Dict[str, Any]],
|
||||
edit_log: Optional[Dict[str, Any]],
|
||||
) -> Optional[List[Dict[str, Any]]]:
|
||||
"""Reconstruct the "post-AI, pre-human" lyrics state for replay.
|
||||
|
||||
Forward-replays the reviewer's edit log onto the RAW transcription
|
||||
(``corrections.json`` corrected_segments), applying only the accepted AI
|
||||
suggestion ops and STOPPING at the first manual op. The result is what the
|
||||
reviewer saw right after the AI auto-corrections were applied but before they
|
||||
made any manual edits — so a "Post-AI" toggle vs the final state makes the
|
||||
human's manual edits obvious (e.g. cleaning up an AI self-conflict that inserted
|
||||
a duplicate word).
|
||||
|
||||
Best-effort: ops that can't be applied are skipped rather than raising. Returns
|
||||
None if there's no edit log (nothing to reconstruct) or no manual edits at all
|
||||
(post-AI == final, so a toggle would be pointless).
|
||||
"""
|
||||
import copy
|
||||
|
||||
if not edit_log:
|
||||
return None
|
||||
entries = edit_log.get("entries") or []
|
||||
if not any(e.get("operation") and not str(e["operation"]).startswith("ai_suggestion") for e in entries):
|
||||
return None # no manual edits → nothing to distinguish
|
||||
|
||||
segments = copy.deepcopy(raw_segments)
|
||||
|
||||
def _find(word_id):
|
||||
for seg in segments:
|
||||
words = seg.get("words") or []
|
||||
for i, w in enumerate(words):
|
||||
if w.get("id") == word_id:
|
||||
return seg, words, i
|
||||
return None, None, None
|
||||
|
||||
_new_id = [0]
|
||||
|
||||
def _gen_id():
|
||||
_new_id[0] += 1
|
||||
return f"postai_{_new_id[0]}"
|
||||
|
||||
for e in entries:
|
||||
op = e.get("operation") or ""
|
||||
if not op.startswith("ai_suggestion"):
|
||||
break # reached the human's manual edits — stop
|
||||
if op != "ai_suggestion_accept":
|
||||
continue # run/reject/undo: not an applied change
|
||||
details = e.get("details") or {}
|
||||
sub_op = details.get("op") or "replace"
|
||||
before_ids = e.get("word_ids_before") or []
|
||||
text_after = (e.get("text_after") or "").strip()
|
||||
anchor_id = before_ids[0] if before_ids else None
|
||||
seg, words, idx = (_find(anchor_id) if anchor_id else (None, None, None))
|
||||
|
||||
def _make_words(text, start, end):
|
||||
# Split the replacement/insertion text into individual words, distributing
|
||||
# the [start, end] span evenly so multi-word replacements get distinct
|
||||
# timestamps (not all crammed into one slot with identical timing).
|
||||
toks = text.split()
|
||||
n = len(toks) or 1
|
||||
if end is None or start is None or end < start:
|
||||
end = start
|
||||
step = (end - start) / n
|
||||
out = []
|
||||
for i, tok in enumerate(toks):
|
||||
ws = start + i * step
|
||||
we = start + (i + 1) * step
|
||||
out.append({"id": _gen_id(), "text": tok, "start_time": ws, "end_time": we,
|
||||
"ai_corrected": True, "original_text": ""})
|
||||
return out
|
||||
|
||||
try:
|
||||
if sub_op == "replace":
|
||||
if words is not None:
|
||||
# word_ids_before may span MULTIPLE words (e.g.
|
||||
# 'quite a picket fence' -> 'white picket fences'). Replace the
|
||||
# whole contiguous span with the space-split replacement text,
|
||||
# spreading the original span's [start,end] across the new words.
|
||||
id_set = set(before_ids)
|
||||
span = [k for k, w in enumerate(words) if w.get("id") in id_set]
|
||||
if span:
|
||||
lo, hi = min(span), max(span)
|
||||
s0 = words[lo].get("start_time", 0.0)
|
||||
e0 = words[hi].get("end_time", s0)
|
||||
words[lo:hi + 1] = _make_words(text_after, s0, e0) if text_after else []
|
||||
elif sub_op in ("insert_after", "insert_before", "insert"):
|
||||
if words is not None:
|
||||
at = idx if sub_op == "insert_before" else idx + 1
|
||||
anchor = words[idx]
|
||||
a_s = anchor.get("start_time", 0.0)
|
||||
a_e = anchor.get("end_time", a_s)
|
||||
words[at:at] = _make_words(text_after, a_s, a_e)
|
||||
elif sub_op in ("delete", "remove", "adlib_removal"):
|
||||
if words is not None:
|
||||
id_set = set(before_ids)
|
||||
seg["words"] = [w for w in words if w.get("id") not in id_set]
|
||||
except Exception:
|
||||
continue # best-effort
|
||||
|
||||
# Refresh each segment's joined text for display.
|
||||
for seg in segments:
|
||||
seg["text"] = " ".join((w.get("text") or "") for w in (seg.get("words") or [])).strip()
|
||||
return segments
|
||||
|
||||
|
||||
def _load_edit_log(job, storage) -> Optional[Dict[str, Any]]:
|
||||
"""Load the reviewer's persisted edit log for replay, or None if absent.
|
||||
|
||||
Prefers the ``state_data.last_edit_log_path`` pointer written by the
|
||||
submit-edit-log endpoint; the file lives at
|
||||
``jobs/{job_id}/lyrics/edit_log_{session_id}.json`` and holds ordered,
|
||||
typed ops (``ai_suggestion_accept/reject`` vs manual ``word_*``/``timing_change``).
|
||||
"""
|
||||
try:
|
||||
path = (job.state_data or {}).get('last_edit_log_path')
|
||||
if not path:
|
||||
return None
|
||||
if not storage.file_exists(path):
|
||||
return None
|
||||
return storage.download_json(path)
|
||||
except Exception as e: # never let replay fail on a missing/corrupt log
|
||||
logger.warning(f"Job {job.job_id}: could not load edit_log for replay: {e}")
|
||||
return None
|
||||
|
||||
|
||||
@router.get("/{job_id}/correction-data")
|
||||
async def get_correction_data(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
replay: bool = False,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
@@ -252,6 +552,15 @@ async def get_correction_data(
|
||||
- All lyrics correction data (segments, reference lyrics, anchors, etc.)
|
||||
- instrumental_options: List of available instrumental tracks with audio URLs
|
||||
- backing_vocals_analysis: Analysis data to help users choose instrumental
|
||||
|
||||
Replay mode (``?replay=true``, requires full auth — admin/owner, not a
|
||||
review-token link): serves the SAME payload for a job in ANY status so the
|
||||
review UI can be re-opened read-only for a completed job. It skips the
|
||||
AWAITING_REVIEW/IN_REVIEW status gate and the AWAITING_REVIEW→IN_REVIEW
|
||||
transition side-effect, and additionally attaches the reviewer's ordered
|
||||
``edit_log`` (AI-accept/reject/manual ops) under ``replay``. Purely read-only;
|
||||
used for the fully-automated-review recording program. See
|
||||
docs/archive/2026-08-25-full-auto-review-design.md.
|
||||
"""
|
||||
job_manager = JobManager()
|
||||
storage = StorageService()
|
||||
@@ -260,12 +569,29 @@ async def get_correction_data(
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
|
||||
if replay and auth_info[1] != "full":
|
||||
# Replay reopens completed jobs; restrict to authenticated admin/owner,
|
||||
# never anonymous review-token links.
|
||||
raise HTTPException(status_code=403, detail="Replay mode requires admin/owner authentication")
|
||||
|
||||
if not replay and job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=t("en", "review.reviewNotReady", status=job.status)
|
||||
)
|
||||
|
||||
# Server-side pre-apply ON LOAD (C2 completeness): jobs processed before the
|
||||
# screens_worker pre-apply shipped (or whose cache landed after that gate) reach
|
||||
# this endpoint without a pre_applied marker, so the review UI would still run its
|
||||
# on-load client-side apply (the visible ~4s "uncorrected -> corrected" flicker).
|
||||
# Apply here from an EXISTING cache only (generate_on_miss=False so the page never
|
||||
# blocks on a multi-model LLM call). Best-effort + idempotent: a no-op when the
|
||||
# job was already pre-applied, already human-edited, or has no cache. The direct
|
||||
# corrections_updated path below then serves the freshly-written corrected state.
|
||||
if not replay:
|
||||
from backend.services.auto_approval.pre_apply import ensure_and_pre_apply
|
||||
await ensure_and_pre_apply(job_id, generate_on_miss=False)
|
||||
|
||||
# Check for updated corrections first (from previous review sessions where user edited lyrics)
|
||||
# This mirrors the logic in render_video_worker.py to ensure consistency
|
||||
corrections_updated_gcs = job.file_urls.get('lyrics', {}).get('corrections_updated')
|
||||
@@ -314,18 +640,25 @@ async def get_correction_data(
|
||||
clean_url = stems.get('instrumental_clean')
|
||||
backing_url = stems.get('instrumental_with_backing')
|
||||
|
||||
# Build instrumental options with transcoded signed URLs (OGG Opus)
|
||||
# Build instrumental options with transcoded signed URLs (OGG Opus).
|
||||
# In local dev without signing creds, use same-origin byte-proxy URLs.
|
||||
instrumental_options = []
|
||||
url_tasks = {}
|
||||
if clean_url:
|
||||
url_tasks['clean'] = transcoding.get_review_audio_url_async(clean_url, expiration_minutes=120)
|
||||
if backing_url:
|
||||
url_tasks['with_backing'] = transcoding.get_review_audio_url_async(backing_url, expiration_minutes=120)
|
||||
|
||||
signed_urls = {}
|
||||
if url_tasks:
|
||||
results = await asyncio.gather(*url_tasks.values())
|
||||
signed_urls = dict(zip(url_tasks.keys(), results))
|
||||
if _dev_audio_proxy_enabled():
|
||||
_base = str(request.base_url)
|
||||
if clean_url:
|
||||
signed_urls['clean'] = _dev_audio_url(job_id, clean_url, _base)
|
||||
if backing_url:
|
||||
signed_urls['with_backing'] = _dev_audio_url(job_id, backing_url, _base)
|
||||
else:
|
||||
url_tasks = {}
|
||||
if clean_url:
|
||||
url_tasks['clean'] = transcoding.get_review_audio_url_async(clean_url, expiration_minutes=120)
|
||||
if backing_url:
|
||||
url_tasks['with_backing'] = transcoding.get_review_audio_url_async(backing_url, expiration_minutes=120)
|
||||
if url_tasks:
|
||||
results = await asyncio.gather(*url_tasks.values())
|
||||
signed_urls = dict(zip(url_tasks.keys(), results))
|
||||
|
||||
if clean_url:
|
||||
instrumental_options.append({
|
||||
@@ -348,23 +681,55 @@ async def get_correction_data(
|
||||
backing_vocals_analysis = job.state_data.get('backing_vocals_analysis', {})
|
||||
corrections_data['backing_vocals_analysis'] = backing_vocals_analysis
|
||||
|
||||
# Per-screen skip (C1): tell the frontend whether each review half is
|
||||
# confidently auto-resolved, so it can skip the instrumental screen (or the
|
||||
# lyrics screen). Derived from the stored auto-approval verdict + the job's
|
||||
# backing_preference — the same decision the executor / complete endpoint use.
|
||||
from backend.config import get_settings as _get_settings
|
||||
from backend.services.auto_approval.instrumental import auto_approval_summary
|
||||
corrections_data['auto_approval'] = auto_approval_summary(job, _get_settings())
|
||||
|
||||
# Get waveform URL if available
|
||||
analysis_files = job.file_urls.get('analysis', {})
|
||||
waveform_url = analysis_files.get('backing_vocals_waveform')
|
||||
if waveform_url:
|
||||
corrections_data['backing_vocals_waveform_url'] = storage.generate_signed_url(
|
||||
waveform_url, expiration_minutes=120
|
||||
corrections_data['backing_vocals_waveform_url'] = (
|
||||
_dev_audio_url(job_id, waveform_url, str(request.base_url)) if _dev_audio_proxy_enabled()
|
||||
else storage.generate_signed_url(waveform_url, expiration_minutes=120)
|
||||
)
|
||||
|
||||
# Transition to IN_REVIEW if not already
|
||||
if job.status == JobStatus.AWAITING_REVIEW:
|
||||
# Transition to IN_REVIEW if not already (never in replay — read-only)
|
||||
if not replay and job.status == JobStatus.AWAITING_REVIEW:
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.IN_REVIEW,
|
||||
message="User opened combined review interface"
|
||||
)
|
||||
|
||||
logger.info(f"Job {job_id}: Serving correction data with instrumental options for combined review")
|
||||
# Replay: attach the reviewer's ordered edit_log so the UI can show the
|
||||
# sequence of actions (AI-accept/reject/manual/timing) beside the final state.
|
||||
if replay:
|
||||
edit_log = _load_edit_log(job, storage)
|
||||
post_ai_segments = None
|
||||
try:
|
||||
raw_data = storage.download_json(f"jobs/{job_id}/lyrics/corrections.json")
|
||||
post_ai_segments = _reconstruct_post_ai_segments(
|
||||
raw_data.get('corrected_segments', []), edit_log
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {job_id}: could not reconstruct post-AI segments: {e}")
|
||||
corrections_data['replay'] = {
|
||||
'is_replay': True,
|
||||
'job_status': str(job.status),
|
||||
'instrumental_selection': job.state_data.get('instrumental_selection'),
|
||||
'edit_log': edit_log,
|
||||
# Present only when the reviewer made manual edits — lets the UI offer a
|
||||
# "Post-AI (pre-human)" toggle vs the final state.
|
||||
'post_ai_segments': post_ai_segments,
|
||||
'has_manual_edits': post_ai_segments is not None,
|
||||
}
|
||||
|
||||
logger.info(f"Job {job_id}: Serving correction data (replay={replay}) for combined review")
|
||||
return corrections_data
|
||||
|
||||
except Exception as e:
|
||||
@@ -460,6 +825,13 @@ async def _stream_audio(job_id: str, stem: Literal["input"] | Literal["vocals"]
|
||||
logger.info(f"Job {job_id}: Proxying {len(audio_bytes)}B vocals audio for waveform")
|
||||
return Response(content=audio_bytes, media_type=content_type)
|
||||
|
||||
if _dev_audio_proxy_enabled():
|
||||
# Local dev (no GCS URL-signing creds): proxy the bytes instead of
|
||||
# 302-redirecting to a signed URL. Prod (flag unset) is unchanged.
|
||||
audio_bytes, content_type = await transcoding.get_review_audio_bytes_async(audio_gcs_path)
|
||||
logger.info(f"Job {job_id}: [dev-proxy] streaming {len(audio_bytes)}B input audio")
|
||||
return Response(content=audio_bytes, media_type=content_type)
|
||||
|
||||
signed_url = await transcoding.get_review_audio_url_async(audio_gcs_path, expiration_minutes=120)
|
||||
logger.info(f"Job {job_id}: Redirecting to signed URL for audio review")
|
||||
return RedirectResponse(url=signed_url, status_code=302)
|
||||
@@ -469,6 +841,68 @@ async def _stream_audio(job_id: str, stem: Literal["input"] | Literal["vocals"]
|
||||
raise HTTPException(status_code=500, detail=t("en", "review.audioServeError", error=str(e)))
|
||||
|
||||
|
||||
# In-memory cache of already-fetched/transcoded dev-audio bytes so HTTP Range
|
||||
# requests (seeking) don't re-transcode the whole file each time. Dev-only.
|
||||
_DEV_AUDIO_CACHE: Dict[str, Tuple[bytes, str]] = {}
|
||||
|
||||
|
||||
def _ranged_response(request: Request, data: bytes, content_type: str) -> Response:
|
||||
"""Serve ``data`` honoring an HTTP Range header (206) so <audio> can seek."""
|
||||
total = len(data)
|
||||
range_header = request.headers.get("range")
|
||||
headers = {"Accept-Ranges": "bytes"}
|
||||
if range_header and range_header.startswith("bytes="):
|
||||
try:
|
||||
spec = range_header.split("=", 1)[1].split(",")[0].strip()
|
||||
start_s, _, end_s = spec.partition("-")
|
||||
start = int(start_s) if start_s else 0
|
||||
end = int(end_s) if end_s else total - 1
|
||||
end = min(end, total - 1)
|
||||
if start > end or start >= total:
|
||||
return Response(status_code=416, headers={"Content-Range": f"bytes */{total}"})
|
||||
chunk = data[start:end + 1]
|
||||
headers["Content-Range"] = f"bytes {start}-{end}/{total}"
|
||||
headers["Content-Length"] = str(len(chunk))
|
||||
return Response(content=chunk, status_code=206, media_type=content_type, headers=headers)
|
||||
except Exception:
|
||||
pass # fall through to full 200
|
||||
headers["Content-Length"] = str(total)
|
||||
return Response(content=data, media_type=content_type, headers=headers)
|
||||
|
||||
|
||||
@router.get("/{job_id}/dev-audio")
|
||||
async def get_dev_audio(job_id: str, path: str, request: Request):
|
||||
"""LOCAL-DEV ONLY audio/image byte proxy for replay when signing creds are absent.
|
||||
|
||||
Returns 404 unless ``REVIEW_AUDIO_PROXY`` is enabled, so it is inert in prod.
|
||||
No auth dependency (dev backend binds to localhost); it only ever serves bytes
|
||||
under ``jobs/{job_id}/`` so it can't be used to read arbitrary blobs. Supports
|
||||
HTTP Range so audio elements can seek.
|
||||
"""
|
||||
if not _dev_audio_proxy_enabled():
|
||||
raise HTTPException(status_code=404, detail="Not found")
|
||||
# Scope guard: only this job's own artifacts (path anchored under the job's
|
||||
# prefix), and no traversal. Localhost-dev-only, so this is belt-and-braces.
|
||||
if not path.startswith(f"jobs/{job_id}/") or ".." in path:
|
||||
raise HTTPException(status_code=400, detail="Invalid path")
|
||||
|
||||
try:
|
||||
cached = _DEV_AUDIO_CACHE.get(path)
|
||||
if cached is None:
|
||||
storage = StorageService()
|
||||
if path.lower().endswith(".png"):
|
||||
cached = (storage.download_bytes(path), "image/png")
|
||||
else:
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
cached = await AudioTranscodingService().get_review_audio_bytes_async(path)
|
||||
_DEV_AUDIO_CACHE[path] = cached
|
||||
data, content_type = cached
|
||||
return _ranged_response(request, data, content_type)
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: [dev-proxy] error serving {path}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail="dev-audio proxy error")
|
||||
|
||||
|
||||
@router.post("/{job_id}/complete")
|
||||
async def complete_review(
|
||||
job_id: str,
|
||||
@@ -506,6 +940,21 @@ async def complete_review(
|
||||
detail=t("en", "review.instrumentalSelectionRequired")
|
||||
)
|
||||
|
||||
# Per-screen skip (C1): a client that skipped the instrumental screen because
|
||||
# the backing decision was confidently auto-resolved sends "auto"; resolve it
|
||||
# from the stored verdict here so CLI/tenant clients get the skip for free.
|
||||
if instrumental_selection == "auto":
|
||||
from backend.config import get_settings as _get_settings
|
||||
from backend.services.auto_approval.instrumental import resolve_auto_instrumental
|
||||
resolved = resolve_auto_instrumental(job, _get_settings())
|
||||
if not resolved:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=t("en", "review.instrumentalSelectionRequired"),
|
||||
)
|
||||
logger.info(f"Job {job_id}: Resolved instrumental_selection='auto' -> '{resolved}'")
|
||||
instrumental_selection = resolved
|
||||
|
||||
valid_selections = ["clean", "with_backing"]
|
||||
# Allow "custom" for mute-region instrumentals or user-uploaded instrumentals
|
||||
stems = job.file_urls.get("stems", {}) if job.file_urls else {}
|
||||
@@ -1131,59 +1580,26 @@ async def generate_preview_video(
|
||||
with create_span("generate-preview-video", {"job_id": job_id, "use_gce": use_gce_preview}) as span:
|
||||
with job_log_context(job_id, worker="preview"):
|
||||
try:
|
||||
# Create temp directory for this preview operation
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# 1. Download original corrections.json (has full structure)
|
||||
with create_span("download-corrections-and-audio") as download_span:
|
||||
corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
corrections_path = os.path.join(temp_dir, "corrections.json")
|
||||
storage.download_file(corrections_gcs, corrections_path)
|
||||
|
||||
with open(corrections_path, 'r', encoding='utf-8') as f:
|
||||
original_data = json.load(f)
|
||||
|
||||
# 2. Download input audio
|
||||
audio_path = os.path.join(temp_dir, "audio.flac")
|
||||
storage.download_file(job.input_media_gcs_path, audio_path)
|
||||
download_span.set_attribute("audio_gcs_path", job.input_media_gcs_path)
|
||||
|
||||
# 3. Load original as CorrectionResult
|
||||
correction_result = CorrectionResult.from_dict(original_data)
|
||||
add_span_event("corrections_loaded")
|
||||
|
||||
# 4. Get or create styles file for preview using unified style loader
|
||||
with create_span("load-styles") as styles_span:
|
||||
styles_path, _ = load_styles_from_gcs(
|
||||
style_params_gcs_path=job.style_params_gcs_path,
|
||||
style_assets=job.style_assets,
|
||||
temp_dir=temp_dir,
|
||||
download_func=storage.download_file,
|
||||
logger=logger,
|
||||
if use_gce_preview:
|
||||
# GCE path: prepare inputs and generate ASS subtitles inline
|
||||
# (fast), then hand the video encode to a background task and
|
||||
# return immediately. Encoding can take minutes when a worker
|
||||
# VM cold-starts — longer than Cloudflare's ~100s edge timeout
|
||||
# — so the request must not wait for it; the frontend polls
|
||||
# the /status endpoint until the mp4 lands in GCS.
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# Blocking work (GCS downloads, ASS generation) runs in a
|
||||
# worker thread so other requests on this instance don't
|
||||
# stall behind it.
|
||||
correction_result, audio_path, output_config = await asyncio.to_thread(
|
||||
_prepare_preview_inputs,
|
||||
job=job, temp_dir=temp_dir, storage=storage, is_duet=is_duet,
|
||||
)
|
||||
styles_span.set_attribute("styles_path", styles_path)
|
||||
|
||||
# 5. Set up output config for preview
|
||||
output_dir = os.path.join(temp_dir, "output")
|
||||
cache_dir = os.path.join(temp_dir, "cache")
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
os.makedirs(cache_dir, exist_ok=True)
|
||||
|
||||
output_config = OutputConfig(
|
||||
output_styles_json=styles_path,
|
||||
output_dir=output_dir,
|
||||
cache_dir=cache_dir,
|
||||
video_resolution="360p",
|
||||
is_duet=is_duet,
|
||||
)
|
||||
|
||||
# 6. Generate preview (ASS-only if using GCE, or full video if local)
|
||||
preview_gcs_path = None
|
||||
|
||||
if use_gce_preview:
|
||||
# GCE path: Generate ASS only, then offload encoding to GCE
|
||||
try:
|
||||
with create_span("generate-ass-subtitles") as ass_span:
|
||||
result = CorrectionOperations.generate_preview_video(
|
||||
result = await asyncio.to_thread(
|
||||
CorrectionOperations.generate_preview_video,
|
||||
correction_result=correction_result,
|
||||
updated_data=updated_data,
|
||||
output_config=output_config,
|
||||
@@ -1198,94 +1614,95 @@ async def generate_preview_video(
|
||||
ass_span.set_attribute("ass_path", ass_path)
|
||||
add_span_event("ass_generated")
|
||||
|
||||
span.set_attribute("preview_hash", preview_hash)
|
||||
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
|
||||
|
||||
# The hash is deterministic over the correction data, so
|
||||
# if this exact preview already exists (e.g. the user
|
||||
# retried after a dropped connection) skip encoding.
|
||||
if storage.file_exists(preview_gcs_path):
|
||||
_record_preview_video(job_id, preview_hash, preview_gcs_path)
|
||||
span.set_attribute("preview_cache_hit", True)
|
||||
logger.info(f"Job {job_id}: Preview cache hit: {preview_hash}")
|
||||
return {"status": "success", "preview_hash": preview_hash}
|
||||
|
||||
# Upload ASS to GCS
|
||||
with create_span("upload-ass-to-gcs") as upload_ass_span:
|
||||
ass_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.ass"
|
||||
storage.upload_file(ass_path, ass_gcs_path)
|
||||
upload_ass_span.set_attribute("ass_gcs_path", ass_gcs_path)
|
||||
|
||||
# Call GCE encoding service
|
||||
with create_span("gce-preview-encoding") as gce_span:
|
||||
bucket_name = settings.gcs_bucket_name
|
||||
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
|
||||
# A stale error marker from an earlier failed attempt at
|
||||
# this same hash would make the status poll fail instantly.
|
||||
storage.delete_file(
|
||||
_preview_error_marker_path(job_id, preview_hash),
|
||||
ignore_missing=True,
|
||||
)
|
||||
|
||||
# Get background image and font from style assets if available
|
||||
style_assets = job.style_assets or {}
|
||||
bucket_name = settings.gcs_bucket_name
|
||||
style_assets = job.style_assets or {}
|
||||
|
||||
# Only use background image if user explicitly requested it
|
||||
# Default is black background for faster preview generation (~10s vs ~30-60s)
|
||||
background_image_gcs_path = None
|
||||
if use_background_image:
|
||||
for key in ["karaoke_background", "style_karaoke_background"]:
|
||||
if key in style_assets:
|
||||
background_image_gcs_path = f"gs://{bucket_name}/{style_assets[key]}"
|
||||
gce_span.set_attribute("background_image", background_image_gcs_path)
|
||||
break
|
||||
gce_span.set_attribute("use_background_image", use_background_image)
|
||||
|
||||
font_gcs_path = None
|
||||
for key in ["font", "style_font"]:
|
||||
# Only use background image if user explicitly requested it.
|
||||
# Default is black background for faster preview generation.
|
||||
background_image_gcs_path = None
|
||||
if use_background_image:
|
||||
for key in ["karaoke_background", "style_karaoke_background"]:
|
||||
if key in style_assets:
|
||||
font_gcs_path = f"gs://{bucket_name}/{style_assets[key]}"
|
||||
gce_span.set_attribute("font", font_gcs_path)
|
||||
background_image_gcs_path = f"gs://{bucket_name}/{style_assets[key]}"
|
||||
break
|
||||
span.set_attribute("use_background_image", use_background_image)
|
||||
|
||||
gce_result = await encoding_service.encode_preview_video(
|
||||
job_id=f"preview_{job_id}_{preview_hash}",
|
||||
ass_gcs_path=f"gs://{bucket_name}/{ass_gcs_path}",
|
||||
audio_gcs_path=f"gs://{bucket_name}/{job.input_media_gcs_path}",
|
||||
output_gcs_path=f"gs://{bucket_name}/{preview_gcs_path}",
|
||||
background_color="black",
|
||||
background_image_gcs_path=background_image_gcs_path,
|
||||
font_gcs_path=font_gcs_path,
|
||||
font_gcs_path = None
|
||||
for key in ["font", "style_font"]:
|
||||
if key in style_assets:
|
||||
font_gcs_path = f"gs://{bucket_name}/{style_assets[key]}"
|
||||
break
|
||||
|
||||
encode_kwargs = {
|
||||
"job_id": f"preview_{job_id}_{preview_hash}",
|
||||
"ass_gcs_path": f"gs://{bucket_name}/{ass_gcs_path}",
|
||||
"audio_gcs_path": f"gs://{bucket_name}/{job.input_media_gcs_path}",
|
||||
"output_gcs_path": f"gs://{bucket_name}/{preview_gcs_path}",
|
||||
"background_color": "black",
|
||||
"background_image_gcs_path": background_image_gcs_path,
|
||||
"font_gcs_path": font_gcs_path,
|
||||
}
|
||||
task = asyncio.create_task(
|
||||
_encode_preview_in_background(
|
||||
job=job,
|
||||
preview_hash=preview_hash,
|
||||
encode_kwargs=encode_kwargs,
|
||||
updated_data=updated_data,
|
||||
is_duet=is_duet,
|
||||
)
|
||||
gce_span.set_attribute("gce_status", gce_result.get("status"))
|
||||
add_span_event("gce_encoding_complete")
|
||||
)
|
||||
_background_tasks.add(task)
|
||||
task.add_done_callback(_background_tasks.discard)
|
||||
|
||||
logger.info(f"Job {job_id}: Preview generated via GCE: {preview_hash}")
|
||||
logger.info(f"Job {job_id}: Preview encode running in background: {preview_hash}")
|
||||
return {"status": "generating", "preview_hash": preview_hash}
|
||||
|
||||
except LyricsTimingError:
|
||||
raise
|
||||
except Exception as gce_error:
|
||||
# Fall back to local encoding if GCE fails
|
||||
# Fall back to synchronous local encoding if GCE setup fails
|
||||
logger.warning(
|
||||
f"Job {job_id}: GCE preview encoding failed, falling back to local: {gce_error}"
|
||||
f"Job {job_id}: GCE preview setup failed, falling back to local: {gce_error}"
|
||||
)
|
||||
span.set_attribute("gce_fallback", True)
|
||||
use_gce_preview = False # Fall through to local encoding below
|
||||
|
||||
if not use_gce_preview:
|
||||
# Local path: Generate full preview video locally
|
||||
with create_span("render-preview-video-local") as render_span:
|
||||
render_span.set_attribute("resolution", "360p")
|
||||
result = CorrectionOperations.generate_preview_video(
|
||||
correction_result=correction_result,
|
||||
updated_data=updated_data,
|
||||
output_config=output_config,
|
||||
audio_filepath=audio_path,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
logger=logger,
|
||||
ass_only=False, # Generate full video locally
|
||||
)
|
||||
preview_hash = result["preview_hash"]
|
||||
video_path = result["video_path"]
|
||||
add_span_event("render_complete")
|
||||
# Local path (GCE preview disabled, or GCE setup failed): render
|
||||
# the full preview synchronously — no cold-start problem, but slow.
|
||||
preview_hash = await asyncio.to_thread(
|
||||
_render_preview_locally, job, updated_data, is_duet
|
||||
)
|
||||
|
||||
# Upload preview video to GCS
|
||||
with create_span("upload-preview-video") as upload_span:
|
||||
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
|
||||
storage.upload_file(video_path, preview_gcs_path)
|
||||
upload_span.set_attribute("gcs_path", preview_gcs_path)
|
||||
logger.info(f"Job {job_id}: Preview video generated: {preview_hash}")
|
||||
span.set_attribute("preview_hash", preview_hash)
|
||||
span.set_attribute("success", True)
|
||||
|
||||
# Store the GCS path for serving
|
||||
if job_id not in _preview_videos:
|
||||
_preview_videos[job_id] = {}
|
||||
_preview_videos[job_id][preview_hash] = preview_gcs_path
|
||||
|
||||
logger.info(f"Job {job_id}: Preview video generated: {preview_hash}")
|
||||
span.set_attribute("preview_hash", preview_hash)
|
||||
span.set_attribute("success", True)
|
||||
|
||||
return {"status": "success", "preview_hash": preview_hash}
|
||||
return {"status": "success", "preview_hash": preview_hash}
|
||||
|
||||
except LyricsTimingError as timing_err:
|
||||
# Untimed lyrics (e.g. custom lyrics not yet tap-synced) — this is a
|
||||
@@ -1342,6 +1759,41 @@ async def get_preview_video(
|
||||
raise HTTPException(status_code=500, detail=t("en", "review.previewVideoStreamError", error=str(e)))
|
||||
|
||||
|
||||
@router.get("/{job_id}/preview-video/{preview_hash}/status")
|
||||
async def get_preview_video_status(
|
||||
job_id: str,
|
||||
preview_hash: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Poll the state of a background preview encode.
|
||||
|
||||
POST /preview-video returns {"status": "generating"} immediately and the
|
||||
encode runs in a background task (_encode_preview_in_background). The
|
||||
browser polls this endpoint until the mp4 appears in GCS. GCS is the
|
||||
source of truth so polls work regardless of which Cloud Run instance
|
||||
they hit.
|
||||
"""
|
||||
storage = StorageService()
|
||||
|
||||
if storage.file_exists(f"jobs/{job_id}/previews/{preview_hash}.mp4"):
|
||||
return {"status": "ready", "preview_hash": preview_hash}
|
||||
|
||||
marker_path = _preview_error_marker_path(job_id, preview_hash)
|
||||
if storage.file_exists(marker_path):
|
||||
message = None
|
||||
try:
|
||||
message = storage.download_json(marker_path).get("error")
|
||||
except Exception:
|
||||
logger.warning(f"Job {job_id}: Unreadable preview error marker {marker_path}")
|
||||
return {
|
||||
"status": "error",
|
||||
"preview_hash": preview_hash,
|
||||
"message": message or t("en", "review.previewVideoGenerationError", error="encoding failed"),
|
||||
}
|
||||
|
||||
return {"status": "generating", "preview_hash": preview_hash}
|
||||
|
||||
|
||||
@router.post("/{job_id}/v1/annotations")
|
||||
async def submit_annotation(
|
||||
job_id: str,
|
||||
@@ -1405,6 +1857,7 @@ async def get_annotation_stats(
|
||||
@router.get("/{job_id}/instrumental-analysis")
|
||||
async def get_instrumental_analysis(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
@@ -1434,21 +1887,28 @@ async def get_instrumental_analysis(
|
||||
backing_url = stems.get('instrumental_with_backing')
|
||||
backing_vocals_path = stems.get('backing_vocals')
|
||||
|
||||
# Build audio URLs with transcoded signed access (OGG Opus, parallel)
|
||||
url_tasks = {}
|
||||
if clean_url:
|
||||
url_tasks['clean'] = transcoding.get_review_audio_url_async(clean_url, expiration_minutes=120)
|
||||
if backing_url:
|
||||
url_tasks['with_backing'] = transcoding.get_review_audio_url_async(backing_url, expiration_minutes=120)
|
||||
if job.input_media_gcs_path:
|
||||
url_tasks['original'] = transcoding.get_review_audio_url_async(job.input_media_gcs_path, expiration_minutes=120)
|
||||
if backing_vocals_path:
|
||||
url_tasks['backing_vocals'] = transcoding.get_review_audio_url_async(backing_vocals_path, expiration_minutes=120)
|
||||
|
||||
# Build audio URLs with transcoded signed access (OGG Opus, parallel).
|
||||
# In local dev without signing creds, use same-origin byte-proxy URLs.
|
||||
audio_url_sources = {
|
||||
'clean': clean_url,
|
||||
'with_backing': backing_url,
|
||||
'original': job.input_media_gcs_path,
|
||||
'backing_vocals': backing_vocals_path,
|
||||
}
|
||||
audio_urls = {}
|
||||
if url_tasks:
|
||||
results = await asyncio.gather(*url_tasks.values())
|
||||
audio_urls = dict(zip(url_tasks.keys(), results))
|
||||
if _dev_audio_proxy_enabled():
|
||||
_base = str(request.base_url)
|
||||
for key, src in audio_url_sources.items():
|
||||
if src:
|
||||
audio_urls[key] = _dev_audio_url(job_id, src, _base)
|
||||
else:
|
||||
url_tasks = {
|
||||
key: transcoding.get_review_audio_url_async(src, expiration_minutes=120)
|
||||
for key, src in audio_url_sources.items() if src
|
||||
}
|
||||
if url_tasks:
|
||||
results = await asyncio.gather(*url_tasks.values())
|
||||
audio_urls = dict(zip(url_tasks.keys(), results))
|
||||
|
||||
# Format response to match InstrumentalAnalysis type
|
||||
return {
|
||||
|
||||
@@ -123,6 +123,29 @@ class Settings(BaseSettings):
|
||||
"AUTO_CORRECT_PROACTIVE_ENABLED", "false"
|
||||
).lower() in ("true", "1", "yes")
|
||||
|
||||
# Auto-approval ENFORCEMENT: when the auto-approval scorer is fully confident
|
||||
# (see backend/services/auto_approval/), skip the combined review screens and
|
||||
# go straight to render. Scoring + verdict recording happen on every job
|
||||
# regardless of this flag; it only gates actually skipping the human.
|
||||
# Per-job opt-out via Job.review_mode="always_review". Kill switch: false.
|
||||
auto_approval_enforce_enabled: bool = os.getenv(
|
||||
"AUTO_APPROVAL_ENFORCE_ENABLED", "true"
|
||||
).lower() in ("true", "1", "yes")
|
||||
|
||||
# Backing decider ENFORCEMENT (Phase 2B): allow a confident WITH_BACKING
|
||||
# verdict from the 3-stem decider to auto-select the with-backing
|
||||
# instrumental. Shadow-validated 2026-08-28/29 (20-job corpus + live
|
||||
# batteries + human review pass: 10/11 pick agreement, the one
|
||||
# auto-eligible job shipped identically to the human) -> default ON.
|
||||
# Default lives HERE, not per-environment env vars, because the executor
|
||||
# runs in BOTH the backend service and the audio-separation Cloud Run Job
|
||||
# (independent env; a service-only env flip left the audio_worker trigger
|
||||
# reading false). Kill switch: set false in ci.yml backend deploy env
|
||||
# AND infrastructure audio-separation-job envs (or revert this default).
|
||||
auto_approval_backing_keep_enabled: bool = os.getenv(
|
||||
"AUTO_APPROVAL_BACKING_KEEP_ENABLED", "true"
|
||||
).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.
|
||||
@@ -154,6 +177,11 @@ class Settings(BaseSettings):
|
||||
# When disabled (default), workers are triggered via direct HTTP (for development)
|
||||
enable_cloud_tasks: bool = os.getenv("ENABLE_CLOUD_TASKS", "false").lower() in ("true", "1", "yes")
|
||||
gcp_region: str = os.getenv("GCP_REGION", "us-central1")
|
||||
# ALL Cloud Tasks queues live in us-central1, but workers running in other
|
||||
# regions (the GPU audio-separation-job sets GCP_REGION to its GPU region)
|
||||
# must still enqueue to the real queue location — building queue paths from
|
||||
# gcp_region 404s from those workers ("Queue does not exist").
|
||||
cloud_tasks_region: str = os.getenv("CLOUD_TASKS_REGION", "us-central1")
|
||||
|
||||
# Cloud Run Jobs (for long-running video encoding)
|
||||
# When enabled AND enable_cloud_tasks is true, video worker uses Cloud Run Jobs
|
||||
|
||||
+39
-2
@@ -144,7 +144,10 @@ STATE_TRANSITIONS = {
|
||||
JobStatus.LYRICS_COMPLETE: [JobStatus.GENERATING_SCREENS, JobStatus.FAILED],
|
||||
|
||||
# Post-parallel processing (screens + backing vocals analysis)
|
||||
JobStatus.GENERATING_SCREENS: [JobStatus.APPLYING_PADDING, JobStatus.AWAITING_REVIEW, JobStatus.FAILED],
|
||||
# GENERATING_SCREENS -> REVIEW_COMPLETE is the auto-approval path: when the
|
||||
# scorer is fully confident the review screens are skipped entirely (no
|
||||
# review token / "ready for review" notification is ever issued).
|
||||
JobStatus.GENERATING_SCREENS: [JobStatus.APPLYING_PADDING, JobStatus.AWAITING_REVIEW, JobStatus.REVIEW_COMPLETE, JobStatus.FAILED],
|
||||
JobStatus.APPLYING_PADDING: [JobStatus.AWAITING_REVIEW, JobStatus.FAILED],
|
||||
|
||||
# Combined human review flow (lyrics + instrumental selection)
|
||||
@@ -272,6 +275,20 @@ class Job(BaseModel):
|
||||
user_email: Optional[str] = None # Email for notifications
|
||||
non_interactive: bool = False # Skip interactive steps (lyrics review, instrumental selection)
|
||||
|
||||
# Review autonomy level. "auto" (default): skip the combined review screens
|
||||
# whenever the auto-approval scorer is fully confident, falling back to human
|
||||
# review otherwise. "always_review": every job stops at the review screens.
|
||||
# (Distinct from legacy non_interactive, which is CLI packaging/upload
|
||||
# semantics and never gated the cloud review flow.)
|
||||
review_mode: str = "auto"
|
||||
|
||||
# Backing-vocals preference chosen up-front at submission. "auto" (default):
|
||||
# retain backing vocals wherever the 3-stem decider is confident it's safe,
|
||||
# else fall through to human review. "clean": always use the clean
|
||||
# instrumental (never retain backing). "review": always let a human pick the
|
||||
# instrumental. Consumed by the auto-approval instrumental decision.
|
||||
backing_preference: str = "auto"
|
||||
|
||||
# Multi-tenant support ("" = consumer portal, "vocalstar"/etc = tenant portal)
|
||||
tenant_id: str = "" # Tenant ID for white-label portal scoping
|
||||
|
||||
@@ -557,7 +574,13 @@ class JobCreate(BaseModel):
|
||||
webhook_url: Optional[str] = None
|
||||
user_email: Optional[str] = None
|
||||
non_interactive: bool = False # Skip interactive steps (lyrics review, instrumental selection)
|
||||
|
||||
# "auto" (default) = skip review screens when the auto-approval scorer is
|
||||
# fully confident; "always_review" = always stop at the review screens.
|
||||
review_mode: str = "auto"
|
||||
# "auto" (default) = retain backing vocals where confidently safe; "clean" =
|
||||
# always strip backing vocals; "review" = always let a human pick the instrumental.
|
||||
backing_preference: str = "auto"
|
||||
|
||||
# Theme configuration (pre-made themes from GCS)
|
||||
theme_id: Optional[str] = None # Theme identifier (e.g., "nomad", "default")
|
||||
color_overrides: Dict[str, str] = Field(default_factory=dict)
|
||||
@@ -648,6 +671,20 @@ class JobCreate(BaseModel):
|
||||
raise ValueError("Field cannot be empty string")
|
||||
return v.strip() if isinstance(v, str) else v
|
||||
|
||||
@validator('review_mode')
|
||||
def _normalize_review_mode(cls, v):
|
||||
"""Coerce an out-of-set value to the fail-safe default (always_review =
|
||||
more human oversight), so a typo can never silently skip review. The
|
||||
executor already treats any non-"auto" value as an enforcement blocker."""
|
||||
return v if v in ("auto", "always_review") else "always_review"
|
||||
|
||||
@validator('backing_preference')
|
||||
def _normalize_backing_preference(cls, v):
|
||||
"""Coerce an out-of-set value to the default. Every creation route passes
|
||||
the client value straight through, so this is the single choke point that
|
||||
keeps a typo from reaching the instrumental decision as an unknown value."""
|
||||
return v if v in ("auto", "clean", "review") else "auto"
|
||||
|
||||
@validator('artist', 'title')
|
||||
def normalize_artist_title(cls, v):
|
||||
"""Normalize artist/title text to standardize Unicode characters.
|
||||
|
||||
@@ -101,35 +101,43 @@ class AudioAnalysisService:
|
||||
gcs_audio_path: str,
|
||||
job_id: str,
|
||||
gcs_waveform_destination: str,
|
||||
) -> tuple[AnalysisResult, str]:
|
||||
gcs_lead_vocals_path: Optional[str] = None,
|
||||
gcs_vocals_path: Optional[str] = None,
|
||||
) -> tuple[AnalysisResult, str, Optional[dict]]:
|
||||
"""
|
||||
Analyze backing vocals and generate a waveform image.
|
||||
|
||||
Analyze backing vocals, generate a waveform image, and (when the lead
|
||||
and full-vocals stems are provided) compute the 3-stem comparison
|
||||
signals for the backing-vocals decider.
|
||||
|
||||
This method:
|
||||
1. Downloads the audio file from GCS
|
||||
2. Runs analysis using AudioAnalyzer
|
||||
3. Generates waveform image using WaveformGenerator
|
||||
4. Uploads the waveform image to GCS
|
||||
5. Returns analysis result and waveform GCS path
|
||||
|
||||
5. Optionally downloads lead_vocals + vocals stems and runs
|
||||
compare_stems (best-effort — a failure yields a comparison dict
|
||||
with ``error`` set, never an exception)
|
||||
|
||||
Args:
|
||||
gcs_audio_path: Path to the audio file in GCS
|
||||
gcs_audio_path: Path to the backing-vocals audio file in GCS
|
||||
job_id: Job ID for logging
|
||||
gcs_waveform_destination: Where to upload the waveform image in GCS
|
||||
|
||||
gcs_lead_vocals_path: Optional GCS path of the lead_vocals stem
|
||||
gcs_vocals_path: Optional GCS path of the full vocals stem
|
||||
|
||||
Returns:
|
||||
Tuple of (AnalysisResult, waveform_gcs_path)
|
||||
Tuple of (AnalysisResult, waveform_gcs_path, stem_comparison dict or None)
|
||||
"""
|
||||
logger.info(f"[{job_id}] Analyzing and generating waveform: {gcs_audio_path}")
|
||||
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# Download audio file
|
||||
local_audio_path = os.path.join(temp_dir, "backing_vocals.flac")
|
||||
self.storage_service.download_file(gcs_audio_path, local_audio_path)
|
||||
|
||||
|
||||
# Run analysis
|
||||
result = self.analyzer.analyze(local_audio_path)
|
||||
|
||||
|
||||
# Generate waveform
|
||||
local_waveform_path = os.path.join(temp_dir, "waveform.png")
|
||||
self.waveform_generator.generate(
|
||||
@@ -139,19 +147,64 @@ class AudioAnalysisService:
|
||||
show_time_axis=True,
|
||||
silence_threshold_db=self.analyzer.silence_threshold_db,
|
||||
)
|
||||
|
||||
|
||||
# Upload waveform to GCS
|
||||
self.storage_service.upload_file(
|
||||
local_waveform_path,
|
||||
gcs_waveform_destination
|
||||
)
|
||||
|
||||
|
||||
comparison: Optional[dict] = None
|
||||
if gcs_lead_vocals_path and gcs_vocals_path:
|
||||
comparison = self._compare_stems(
|
||||
job_id, temp_dir, local_audio_path,
|
||||
gcs_lead_vocals_path, gcs_vocals_path,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"[{job_id}] Analysis and waveform generation complete. "
|
||||
f"Waveform uploaded to: {gcs_waveform_destination}"
|
||||
)
|
||||
|
||||
return result, gcs_waveform_destination
|
||||
|
||||
return result, gcs_waveform_destination, comparison
|
||||
|
||||
def _compare_stems(
|
||||
self,
|
||||
job_id: str,
|
||||
temp_dir: str,
|
||||
local_backing_path: str,
|
||||
gcs_lead_vocals_path: str,
|
||||
gcs_vocals_path: str,
|
||||
) -> Optional[dict]:
|
||||
"""Download lead + vocals stems and run the 3-stem comparison.
|
||||
|
||||
Best-effort: returns None when the extra stems can't even be
|
||||
downloaded; compare_stems itself reports internal failures via the
|
||||
``error`` field rather than raising.
|
||||
"""
|
||||
from karaoke_gen.instrumental_review.stem_comparison import compare_stems
|
||||
|
||||
try:
|
||||
local_lead = os.path.join(temp_dir, "lead_vocals.flac")
|
||||
local_vocals = os.path.join(temp_dir, "vocals.flac")
|
||||
self.storage_service.download_file(gcs_lead_vocals_path, local_lead)
|
||||
self.storage_service.download_file(gcs_vocals_path, local_vocals)
|
||||
except Exception as e:
|
||||
logger.warning(f"[{job_id}] stem comparison skipped (download failed): {e}")
|
||||
return None
|
||||
comparison = compare_stems(
|
||||
local_backing_path,
|
||||
local_lead,
|
||||
local_vocals,
|
||||
silence_threshold_db=self.analyzer.silence_threshold_db,
|
||||
)
|
||||
logger.info(
|
||||
f"[{job_id}] Stem comparison: coverage_ratio={comparison.coverage_ratio}, "
|
||||
f"corr_backing_vocals={comparison.corr_backing_vocals}, "
|
||||
f"lead_overlap={comparison.lead_overlap_fraction}, "
|
||||
f"flat_fraction={comparison.flat_fraction}, error={comparison.error}"
|
||||
)
|
||||
return comparison.to_dict()
|
||||
|
||||
def get_waveform_data(
|
||||
self,
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Auto-approvability scoring + review-diff analysis.
|
||||
|
||||
Shared, pure building blocks for the "fully-automated review" program:
|
||||
- ``scorer`` — decide whether a job's lyrics/backing decisions are safe to
|
||||
auto-approve (used in shadow mode first, then as the real gate).
|
||||
- ``lyrics_diff`` — reconstruct exactly what a human changed during review by
|
||||
diffing ``corrections.json`` against ``corrections_updated.json``.
|
||||
|
||||
See ``docs/archive/2026-08-25-full-auto-review-design.md``.
|
||||
"""
|
||||
|
||||
from backend.services.auto_approval.models import (
|
||||
AutoApprovabilityVerdict,
|
||||
BackingResult,
|
||||
BackingVerdict,
|
||||
LyricsResult,
|
||||
LyricsVerdict,
|
||||
)
|
||||
from backend.services.auto_approval.scorer import (
|
||||
SCORER_VERSION,
|
||||
score_backing,
|
||||
score_job,
|
||||
score_lyrics,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"AutoApprovabilityVerdict",
|
||||
"BackingResult",
|
||||
"BackingVerdict",
|
||||
"LyricsResult",
|
||||
"LyricsVerdict",
|
||||
"SCORER_VERSION",
|
||||
"score_backing",
|
||||
"score_job",
|
||||
"score_lyrics",
|
||||
]
|
||||
@@ -0,0 +1,296 @@
|
||||
"""Server-side application of AI auto-correct suggestions.
|
||||
|
||||
Faithful port of the review UI's auto-apply (frontend
|
||||
``lib/lyrics-review/utils/autoCorrectApply.ts`` + ``autoCorrectConflicts.ts`` +
|
||||
``useAutoCorrect.acceptAll``): the UI auto-applies every pending suggestion on
|
||||
load (conflict groups resolved by consensus → confidence), so a human reviewer
|
||||
always starts from the post-AI state. When a job is auto-approved without a
|
||||
human, this module produces that same post-AI state server-side.
|
||||
|
||||
Everything here is pure (dict in, dict out); any anomaly is reported so the
|
||||
caller can fall back to human review rather than ship a suspect result.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import uuid
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
Segment = Dict[str, Any]
|
||||
Suggestion = Dict[str, Any]
|
||||
|
||||
_WORD_SPLIT_RE = re.compile(r"\s+")
|
||||
_TOKEN_NORM_RE = re.compile(r"^[^\w]+|[^\w]+$")
|
||||
|
||||
|
||||
def _new_word_id() -> str:
|
||||
return uuid.uuid4().hex[:8]
|
||||
|
||||
|
||||
def _rebuild_text(words: List[Dict[str, Any]]) -> str:
|
||||
return " ".join(w.get("text", "") for w in words)
|
||||
|
||||
|
||||
def pick_accept_all_winners(suggestions: List[Suggestion]) -> List[str]:
|
||||
"""Winner ids for accept-all: one per conflict group (highest consensus,
|
||||
then confidence); non-conflicting suggestions all win. Original order."""
|
||||
best_of_group: Dict[str, Suggestion] = {}
|
||||
for s in suggestions:
|
||||
group = s.get("conflict_group")
|
||||
if not group:
|
||||
continue
|
||||
current = best_of_group.get(group)
|
||||
if (
|
||||
current is None
|
||||
or (s.get("consensus") or 0) > (current.get("consensus") or 0)
|
||||
or (
|
||||
(s.get("consensus") or 0) == (current.get("consensus") or 0)
|
||||
and (s.get("confidence") or 0) > (current.get("confidence") or 0)
|
||||
)
|
||||
):
|
||||
best_of_group[group] = s
|
||||
return [
|
||||
s["id"]
|
||||
for s in suggestions
|
||||
if not s.get("conflict_group")
|
||||
or best_of_group.get(s["conflict_group"], {}).get("id") == s.get("id")
|
||||
]
|
||||
|
||||
|
||||
def _find_segment_with_words(
|
||||
segments: List[Segment], word_ids: List[str]
|
||||
) -> Optional[Tuple[int, List[int]]]:
|
||||
if not word_ids:
|
||||
# all([]) is vacuously True — an empty/missing word_ids must read as
|
||||
# not-found, not as "matches the first segment".
|
||||
return None
|
||||
for i, seg in enumerate(segments):
|
||||
words = seg.get("words") or []
|
||||
indices = []
|
||||
for wid in word_ids:
|
||||
idx = next((j for j, w in enumerate(words) if w.get("id") == wid), -1)
|
||||
indices.append(idx)
|
||||
if all(x >= 0 for x in indices):
|
||||
return i, indices
|
||||
return None
|
||||
|
||||
|
||||
def is_suggestion_stale(segments: List[Segment], suggestion: Suggestion) -> bool:
|
||||
"""Stale when the target words no longer exist in one segment, contiguously."""
|
||||
found = _find_segment_with_words(segments, suggestion.get("word_ids") or [])
|
||||
if not found:
|
||||
return True
|
||||
_, indices = found
|
||||
s = sorted(indices)
|
||||
return any(s[i] != s[i - 1] + 1 for i in range(1, len(s)))
|
||||
|
||||
|
||||
def _distribute_timings(
|
||||
n: int, start: Optional[float], end: Optional[float]
|
||||
) -> List[Tuple[Optional[float], Optional[float]]]:
|
||||
if n <= 0:
|
||||
return []
|
||||
if start is None or end is None or end <= start:
|
||||
return [(start, end)] * n
|
||||
step = (end - start) / n
|
||||
return [(start + i * step, start + (i + 1) * step) for i in range(n)]
|
||||
|
||||
|
||||
def _copy_segments(segments: List[Segment]) -> List[Segment]:
|
||||
return [{**s, "words": [dict(w) for w in (s.get("words") or [])]} for s in segments]
|
||||
|
||||
|
||||
def apply_suggestion(
|
||||
segments: List[Segment], suggestion: Suggestion
|
||||
) -> Optional[List[Segment]]:
|
||||
"""Apply one suggestion; returns new segments or None when stale."""
|
||||
if is_suggestion_stale(segments, suggestion):
|
||||
return None
|
||||
found = _find_segment_with_words(segments, suggestion.get("word_ids") or [])
|
||||
if not found:
|
||||
return None
|
||||
seg_index, word_indices = found
|
||||
span_start = min(word_indices)
|
||||
span_end = max(word_indices)
|
||||
|
||||
result = _copy_segments(segments)
|
||||
seg = result[seg_index]
|
||||
words = seg["words"]
|
||||
op = suggestion.get("op")
|
||||
new_text = suggestion.get("new_text") or ""
|
||||
|
||||
if op == "insert_after":
|
||||
anchor = words[span_end]
|
||||
nxt = words[span_end + 1] if span_end + 1 < len(words) else None
|
||||
new_texts = [t for t in _WORD_SPLIT_RE.split(new_text) if t]
|
||||
window_start = anchor.get("end_time")
|
||||
if (
|
||||
nxt is not None
|
||||
and nxt.get("start_time") is not None
|
||||
and window_start is not None
|
||||
and nxt["start_time"] > window_start
|
||||
):
|
||||
window_end: Optional[float] = nxt["start_time"]
|
||||
elif window_start is not None:
|
||||
window_end = window_start + 0.5 * len(new_texts)
|
||||
else:
|
||||
window_end = None
|
||||
timings = _distribute_timings(len(new_texts), window_start, window_end)
|
||||
new_words = [
|
||||
{
|
||||
"id": _new_word_id(),
|
||||
"text": text,
|
||||
"start_time": t[0],
|
||||
"end_time": t[1],
|
||||
"confidence": 1,
|
||||
"created_during_correction": True,
|
||||
"ai_corrected": True,
|
||||
# Inserted words have no source transcription -> synthetic timing.
|
||||
"timing_estimated": True,
|
||||
"correction_span_id": suggestion.get("id"),
|
||||
}
|
||||
for text, t in zip(new_texts, timings)
|
||||
]
|
||||
words[span_end + 1 : span_end + 1] = new_words
|
||||
seg["text"] = _rebuild_text(words)
|
||||
return result
|
||||
|
||||
removed = words[span_start : span_end + 1]
|
||||
|
||||
if op == "delete":
|
||||
del words[span_start : span_start + len(removed)]
|
||||
if not words:
|
||||
del result[seg_index]
|
||||
else:
|
||||
seg["text"] = _rebuild_text(words)
|
||||
seg["start_time"] = words[0].get("start_time")
|
||||
seg["end_time"] = words[-1].get("end_time")
|
||||
return result
|
||||
|
||||
# replace
|
||||
new_texts = [t for t in _WORD_SPLIT_RE.split(new_text) if t]
|
||||
timings = _distribute_timings(
|
||||
len(new_texts),
|
||||
removed[0].get("start_time") if removed else None,
|
||||
removed[-1].get("end_time") if removed else None,
|
||||
)
|
||||
# >1 replacement word forces an even split of one range -> estimated timing.
|
||||
timing_estimated = len(new_texts) > 1
|
||||
original_span_text = suggestion.get("original_text") or _rebuild_text(removed)
|
||||
new_words = []
|
||||
for i, (text, t) in enumerate(zip(new_texts, timings)):
|
||||
w = {
|
||||
"id": _new_word_id(),
|
||||
"text": text,
|
||||
"start_time": t[0],
|
||||
"end_time": t[1],
|
||||
"confidence": 1,
|
||||
"created_during_correction": True,
|
||||
"ai_corrected": True,
|
||||
"timing_estimated": timing_estimated,
|
||||
"correction_span_id": suggestion.get("id"),
|
||||
}
|
||||
if i == 0:
|
||||
w["original_text"] = original_span_text
|
||||
new_words.append(w)
|
||||
words[span_start : span_start + len(removed)] = new_words
|
||||
seg["text"] = _rebuild_text(words)
|
||||
return result
|
||||
|
||||
|
||||
def apply_all_suggestions(
|
||||
segments: List[Segment], suggestions: List[Suggestion]
|
||||
) -> Dict[str, Any]:
|
||||
"""Accept-all with conflict resolution, mirroring the UI's on-load auto-apply.
|
||||
|
||||
Returns ``{"segments", "applied_ids", "rejected_ids", "stale_ids"}``.
|
||||
"""
|
||||
winners = set(pick_accept_all_winners(suggestions))
|
||||
current = segments
|
||||
applied: List[str] = []
|
||||
rejected: List[str] = []
|
||||
stale: List[str] = []
|
||||
for s in suggestions:
|
||||
sid = s.get("id") or ""
|
||||
if sid not in winners:
|
||||
rejected.append(sid)
|
||||
continue
|
||||
result = apply_suggestion(current, s)
|
||||
if result is None:
|
||||
stale.append(sid)
|
||||
continue
|
||||
current = result
|
||||
applied.append(sid)
|
||||
return {
|
||||
"segments": current,
|
||||
"applied_ids": applied,
|
||||
"rejected_ids": rejected,
|
||||
"stale_ids": stale,
|
||||
}
|
||||
|
||||
|
||||
def build_applied_segments(
|
||||
corrections: Dict[str, Any], ai_suggestions: Optional[List[Suggestion]]
|
||||
) -> Dict[str, Any]:
|
||||
"""Apply the AI suggestions to a corrections payload with the safety gates.
|
||||
|
||||
Shared by the executor (auto-complete) and the review-gate pre-apply. Returns
|
||||
``{"aborted": <reason>}`` on any anomaly (caller falls back to human review /
|
||||
client-side apply), else ``{"segments", "applied_ids", "rejected_ids"}``.
|
||||
"""
|
||||
segments = corrections.get("corrected_segments") or []
|
||||
if not segments:
|
||||
return {"aborted": "no_segments"}
|
||||
|
||||
result = apply_all_suggestions(segments, ai_suggestions or [])
|
||||
if result["stale_ids"]:
|
||||
# Nothing edits segments between generation and now, so staleness means
|
||||
# the cache doesn't match this corrections.json -> don't trust the apply.
|
||||
return {"aborted": f"stale_suggestions:{len(result['stale_ids'])}"}
|
||||
|
||||
new_segments = result["segments"]
|
||||
if not new_segments or any(not (s.get("words") or []) for s in new_segments):
|
||||
return {"aborted": "empty_segments_after_apply"}
|
||||
|
||||
duplicates = find_suspicious_duplicates(new_segments, corrections.get("reference_lyrics"))
|
||||
if duplicates:
|
||||
# P1 signature: overlapping suggestions doubled a word ("you're you're").
|
||||
return {"aborted": f"duplicate_words:{','.join(duplicates[:5])}"}
|
||||
|
||||
return {
|
||||
"segments": new_segments,
|
||||
"applied_ids": result["applied_ids"],
|
||||
"rejected_ids": result["rejected_ids"],
|
||||
}
|
||||
|
||||
|
||||
def _norm_token(text: str) -> str:
|
||||
return _TOKEN_NORM_RE.sub("", (text or "").lower())
|
||||
|
||||
|
||||
def find_suspicious_duplicates(
|
||||
segments: List[Segment], reference_lyrics: Optional[Dict[str, Any]] = None
|
||||
) -> List[str]:
|
||||
"""Adjacent identical words that no reference supports (P1 self-conflict
|
||||
signature — e.g. two overlapping suggestions both adding "you're" produced
|
||||
"fire, you're you're gasoline"). Returns the offending tokens."""
|
||||
ref_texts: List[str] = []
|
||||
for ref in (reference_lyrics or {}).values():
|
||||
for ref_seg in ref.get("segments") or []:
|
||||
ref_texts.append(" ".join(
|
||||
_norm_token(t) for t in _WORD_SPLIT_RE.split(ref_seg.get("text") or "") if t
|
||||
))
|
||||
ref_blob = "\n".join(ref_texts)
|
||||
|
||||
offenders: List[str] = []
|
||||
for seg in segments:
|
||||
words = seg.get("words") or []
|
||||
for i in range(1, len(words)):
|
||||
a = _norm_token(words[i - 1].get("text") or "")
|
||||
b = _norm_token(words[i].get("text") or "")
|
||||
if a and a == b:
|
||||
# A doubled word is fine when a reference genuinely repeats it.
|
||||
if f"{a} {a}" in ref_blob:
|
||||
continue
|
||||
offenders.append(a)
|
||||
return offenders
|
||||
@@ -0,0 +1,333 @@
|
||||
"""Auto-approval executor: complete the combined review without a human when safe.
|
||||
|
||||
Called from two places (covering both orderings of audio vs lyrics completion):
|
||||
- ``screens_worker`` just before it would transition to AWAITING_REVIEW
|
||||
(trigger="screens_worker", job still GENERATING_SCREENS), and
|
||||
- ``audio_worker`` after stems + backing analysis land, when the job is already
|
||||
sitting in AWAITING_REVIEW (trigger="audio_worker").
|
||||
|
||||
Every call scores the job and records the verdict in
|
||||
``processing_metadata.auto_approval`` (so shadow data accumulates on every job).
|
||||
Enforcement — actually skipping the review screens — happens only when ALL of:
|
||||
- the feature flag is on and the job's ``review_mode`` is "auto" (the default);
|
||||
- the job is not a made-for-you order (the human QC pass is part of that
|
||||
product);
|
||||
- the job is ELIGIBLE: with a user-supplied instrumental (tenant bulk uploads,
|
||||
the existing-instrumental upload option, mute-region edits) there is no
|
||||
instrumental decision to make, so confident lyrics alone qualify and the
|
||||
selection is "custom" — mirroring the human tenant complete-review flow.
|
||||
Otherwise the scorer's ``overall_auto`` must be True (confident lyrics AND a
|
||||
non-subjective backing decision);
|
||||
- audio separation is complete and the required instrumental exists (clean or
|
||||
with-backing stem; the video worker validates custom sources itself).
|
||||
|
||||
The enforce path replicates exactly what a human clicking "Complete Review"
|
||||
does after the UI's on-load auto-apply: apply the cached AI suggestions
|
||||
(conflict groups resolved identically), save ``corrections_updated.json``,
|
||||
store the instrumental selection, clear worker progress keys, transition to
|
||||
REVIEW_COMPLETE and trigger the render worker.
|
||||
|
||||
FAIL-SAFE: any anomaly (stale suggestions, duplicate-word artifacts, missing
|
||||
data, exceptions) aborts enforcement and the job proceeds to normal human
|
||||
review. Auto-approval must never be the reason a job fails.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.auto_approval.instrumental import (
|
||||
backing_decision,
|
||||
has_custom_instrumental,
|
||||
)
|
||||
from backend.services.auto_approval.models import LyricsVerdict
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
CORRECTIONS_PATH = "jobs/{job_id}/lyrics/corrections.json"
|
||||
CORRECTIONS_UPDATED_PATH = "jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
AUTO_CORRECT_CACHE_PREFIX = "jobs/{job_id}/lyrics/auto_correct_cache/"
|
||||
|
||||
REVIEW_MODE_AUTO = "auto"
|
||||
REVIEW_MODE_ALWAYS_REVIEW = "always_review"
|
||||
|
||||
|
||||
def _load_ai_suggestions(storage, job_id: str) -> Optional[List[Dict[str, Any]]]:
|
||||
"""The proactive auto-correct cache the review UI would auto-apply on load."""
|
||||
try:
|
||||
prefix = AUTO_CORRECT_CACHE_PREFIX.format(job_id=job_id)
|
||||
for cache_path in sorted(storage.list_files(prefix)):
|
||||
cached = storage.download_json(cache_path)
|
||||
suggestions = cached.get("suggestions")
|
||||
if isinstance(suggestions, list):
|
||||
return suggestions
|
||||
except Exception as e:
|
||||
logger.info(f"[job:{job_id}] auto-approval: no auto-correct cache readable ({e})")
|
||||
return None
|
||||
|
||||
|
||||
def _enforcement_blockers(job, settings) -> List[str]:
|
||||
"""Why this job may not be ENFORCED (shadow scoring still happens)."""
|
||||
blockers: List[str] = []
|
||||
if not settings.auto_approval_enforce_enabled:
|
||||
blockers.append("flag_disabled")
|
||||
review_mode = getattr(job, "review_mode", REVIEW_MODE_AUTO) or REVIEW_MODE_AUTO
|
||||
if review_mode != REVIEW_MODE_AUTO:
|
||||
blockers.append(f"review_mode:{review_mode}")
|
||||
if getattr(job, "made_for_you", False):
|
||||
blockers.append("made_for_you")
|
||||
return blockers
|
||||
|
||||
|
||||
async def maybe_auto_complete_review(job_id: str, trigger: str) -> Dict[str, Any]:
|
||||
"""Score the job, record the verdict, and auto-complete the review if safe.
|
||||
|
||||
Returns a small status dict; ``{"outcome": "auto_completed"}`` means the
|
||||
review screens were skipped and the render worker has been triggered.
|
||||
Never raises.
|
||||
"""
|
||||
from backend.config import get_settings
|
||||
from backend.services.auto_approval.scorer import score_job
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
outcome: Dict[str, Any] = {"outcome": "skipped"}
|
||||
try:
|
||||
settings = get_settings()
|
||||
job_manager = JobManager()
|
||||
storage = StorageService()
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
return {"outcome": "no_job"}
|
||||
|
||||
# Only act on the two known launch points; a human already in the
|
||||
# editor (IN_REVIEW) or any other state is out of scope.
|
||||
if trigger == "screens_worker":
|
||||
expected_statuses = (JobStatus.GENERATING_SCREENS,)
|
||||
else:
|
||||
expected_statuses = (JobStatus.AWAITING_REVIEW,)
|
||||
if job.status not in expected_statuses:
|
||||
return {"outcome": "wrong_status", "status": str(job.status)}
|
||||
if job.state_data.get("instrumental_selection"):
|
||||
return {"outcome": "already_selected"}
|
||||
|
||||
corrections_path = CORRECTIONS_PATH.format(job_id=job_id)
|
||||
if not storage.file_exists(corrections_path):
|
||||
return {"outcome": "no_corrections"}
|
||||
corrections = storage.download_json(corrections_path)
|
||||
|
||||
ai_suggestions = _load_ai_suggestions(storage, job_id)
|
||||
state_data = job.state_data or {}
|
||||
backing_analysis = state_data.get("backing_vocals_analysis")
|
||||
audio_complete = bool(state_data.get("audio_complete", False))
|
||||
stems = (job.file_urls or {}).get("stems", {}) if job.file_urls else {}
|
||||
|
||||
verdict = score_job(corrections, backing_analysis, ai_suggestions)
|
||||
blockers = _enforcement_blockers(job, settings)
|
||||
custom_instrumental = has_custom_instrumental(job)
|
||||
backing_preference = getattr(job, "backing_preference", "auto") or "auto"
|
||||
backing_keep_enabled = getattr(settings, "auto_approval_backing_keep_enabled", False)
|
||||
# Single source of truth for the instrumental decision (shared with the
|
||||
# complete-review "auto" resolver and the per-screen-skip UI summary).
|
||||
decision = backing_decision(
|
||||
backing_verdict=verdict.backing.verdict.value,
|
||||
backing_non_subjective=verdict.backing.non_subjective,
|
||||
backing_preference=backing_preference,
|
||||
backing_keep_enabled=backing_keep_enabled,
|
||||
custom_instrumental=custom_instrumental,
|
||||
)
|
||||
keep_backing = decision["keep_backing"]
|
||||
|
||||
# Eligibility: confident lyrics AND a resolvable instrumental decision.
|
||||
# With a user-supplied instrumental the backing decision is moot, so
|
||||
# confident lyrics alone qualify (selection="custom").
|
||||
lyrics_auto = verdict.lyrics.verdict == LyricsVerdict.AUTO
|
||||
if custom_instrumental:
|
||||
eligible = lyrics_auto
|
||||
enforcement_basis = "lyrics_only_custom_instrumental"
|
||||
else:
|
||||
eligible = lyrics_auto and decision["ok"]
|
||||
enforcement_basis = (
|
||||
"overall_auto"
|
||||
if backing_preference == "auto"
|
||||
else f"lyrics_auto_backing_pref:{backing_preference}"
|
||||
)
|
||||
|
||||
# Stem / audio blockers (the instrumental the selection needs must exist).
|
||||
if not audio_complete:
|
||||
blockers.append("audio_incomplete")
|
||||
elif custom_instrumental:
|
||||
# User-supplied instrumental -> "custom"; the video worker validates
|
||||
# the custom source itself, no separated-stem requirements.
|
||||
pass
|
||||
elif keep_backing:
|
||||
# Confident-keep (3-stem decider) selects the with-backing
|
||||
# instrumental — gated shadow-first behind its own flag.
|
||||
if not backing_keep_enabled:
|
||||
blockers.append("backing_keep_disabled")
|
||||
if not stems.get("instrumental_with_backing"):
|
||||
blockers.append("no_with_backing_stem")
|
||||
elif not stems.get("instrumental_clean"):
|
||||
# Clean selection (auto-clean verdict OR backing_preference="clean").
|
||||
blockers.append("no_clean_stem")
|
||||
|
||||
payload = verdict.to_dict()
|
||||
payload.update({
|
||||
"mode": "shadow", # flipped to "enforce" only when we actually enforce
|
||||
"enforcement_eligible": eligible and not blockers,
|
||||
"enforcement_basis": enforcement_basis,
|
||||
"custom_instrumental": custom_instrumental,
|
||||
"backing_preference": backing_preference,
|
||||
"resolved_instrumental_selection": decision["selection"],
|
||||
"trigger": trigger,
|
||||
"enforcement_blockers": blockers,
|
||||
"audio_complete_at_scoring": audio_complete,
|
||||
"backing_analysis_available": backing_analysis is not None,
|
||||
"ai_suggestions_available": ai_suggestions is not None,
|
||||
"scored_at": datetime.now(timezone.utc).isoformat(),
|
||||
})
|
||||
|
||||
summary = (
|
||||
f"auto-approval [{trigger}]: eligible={eligible} ({enforcement_basis}) "
|
||||
f"lyrics={verdict.lyrics.verdict.value}/{verdict.lyrics.tier} "
|
||||
f"backing={verdict.backing.verdict.value} blockers={blockers or 'none'} "
|
||||
f"(scorer v{verdict.scorer_version})"
|
||||
)
|
||||
logger.info(f"[job:{job_id}] {summary}")
|
||||
|
||||
if not eligible or blockers:
|
||||
payload["outcome"] = "review"
|
||||
job_manager.update_processing_metadata(job_id, "auto_approval", payload)
|
||||
return {"outcome": "review", "overall_auto": verdict.overall_auto,
|
||||
"blockers": blockers}
|
||||
|
||||
# ---- ENFORCE: complete the review exactly like a human would ----
|
||||
# The status gate above used a snapshot read. Re-read now so a human who
|
||||
# opened the editor in the meantime (AWAITING_REVIEW -> IN_REVIEW) is not
|
||||
# overwritten — IN_REVIEW -> REVIEW_COMPLETE is a legal transition and
|
||||
# would otherwise pass validation mid-edit.
|
||||
fresh = job_manager.get_job(job_id)
|
||||
if (
|
||||
not fresh
|
||||
or fresh.status not in expected_statuses
|
||||
or (fresh.state_data or {}).get("instrumental_selection")
|
||||
):
|
||||
payload["outcome"] = "aborted"
|
||||
payload["abort_reason"] = "state_changed_during_enforce"
|
||||
job_manager.update_processing_metadata(job_id, "auto_approval", payload)
|
||||
return {"outcome": "aborted", "reason": "state_changed_during_enforce"}
|
||||
|
||||
applied_info = _build_auto_corrections(
|
||||
job_id, corrections, ai_suggestions or [], storage
|
||||
)
|
||||
if applied_info.get("aborted"):
|
||||
payload["outcome"] = "aborted"
|
||||
payload["abort_reason"] = applied_info["aborted"]
|
||||
job_manager.update_processing_metadata(job_id, "auto_approval", payload)
|
||||
logger.warning(
|
||||
f"[job:{job_id}] auto-approval aborted -> human review "
|
||||
f"({applied_info['aborted']})"
|
||||
)
|
||||
return {"outcome": "aborted", "reason": applied_info["aborted"]}
|
||||
|
||||
# Instrumental selection resolved by the shared decision: user-supplied
|
||||
# instrumental -> "custom"; otherwise the non-subjective backing verdict
|
||||
# (or the user's backing_preference) picks the separated stem.
|
||||
selection = decision["selection"] or ("with_backing" if keep_backing else "clean")
|
||||
job_manager.update_state_data(job_id, "instrumental_selection", selection)
|
||||
|
||||
# Clear worker progress keys so downstream workers run fresh (mirrors
|
||||
# complete_review — idempotency keys would otherwise skip re-runs).
|
||||
progress_keys = ["render_progress", "video_progress", "encoding_progress"]
|
||||
job_manager.delete_state_data_keys(job_id, progress_keys)
|
||||
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.REVIEW_COMPLETE,
|
||||
progress=70,
|
||||
message=(
|
||||
"Auto-approved: lyrics verified against synced references and "
|
||||
+ (
|
||||
"using your provided instrumental"
|
||||
if custom_instrumental
|
||||
else (
|
||||
"clear backing vocals retained"
|
||||
if keep_backing
|
||||
else "no audible backing vocals"
|
||||
)
|
||||
)
|
||||
+ " — skipping review, rendering video"
|
||||
),
|
||||
)
|
||||
|
||||
# Record the verdict AFTER the transition so the metadata never claims
|
||||
# auto-completion for a job that in fact fell back to human review.
|
||||
payload["mode"] = "enforce"
|
||||
payload["outcome"] = "auto_completed"
|
||||
payload["applied_suggestions"] = len(applied_info.get("applied_ids") or [])
|
||||
job_manager.update_processing_metadata(job_id, "auto_approval", payload)
|
||||
|
||||
from backend.services.worker_service import get_worker_service
|
||||
await get_worker_service().trigger_render_video_worker(job_id)
|
||||
|
||||
logger.info(f"[job:{job_id}] auto-approval COMPLETED review "
|
||||
f"(applied {payload['applied_suggestions']} AI suggestions)")
|
||||
return {"outcome": "auto_completed"}
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] auto-approval failed non-fatally: {e}", exc_info=True)
|
||||
try:
|
||||
from backend.services.job_manager import JobManager
|
||||
JobManager().update_processing_metadata(job_id, "auto_approval", {
|
||||
"outcome": "error",
|
||||
"error": str(e),
|
||||
"trigger": trigger,
|
||||
"scored_at": datetime.now(timezone.utc).isoformat(),
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
return {"outcome": "error", "error": str(e)}
|
||||
|
||||
|
||||
def _build_auto_corrections(
|
||||
job_id: str,
|
||||
corrections: Dict[str, Any],
|
||||
ai_suggestions: List[Dict[str, Any]],
|
||||
storage,
|
||||
) -> Dict[str, Any]:
|
||||
"""Apply the AI suggestions and save corrections_updated.json.
|
||||
|
||||
Returns ``{"aborted": <reason>}`` on any anomaly (caller falls back to
|
||||
human review), else ``{"applied_ids": [...]}``.
|
||||
"""
|
||||
from backend.services.auto_approval.apply import build_applied_segments
|
||||
|
||||
result = build_applied_segments(corrections, ai_suggestions)
|
||||
if result.get("aborted"):
|
||||
return {"aborted": result["aborted"]}
|
||||
|
||||
updated = dict(corrections)
|
||||
updated["corrected_segments"] = result["segments"]
|
||||
metadata = dict(updated.get("metadata") or {})
|
||||
metadata["auto_approval"] = {
|
||||
"auto_approved": True,
|
||||
"applied_suggestion_ids": result["applied_ids"],
|
||||
"rejected_suggestion_ids": result["rejected_ids"],
|
||||
"applied_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
updated["metadata"] = metadata
|
||||
|
||||
updated_path = CORRECTIONS_UPDATED_PATH.format(job_id=job_id)
|
||||
storage.upload_json(updated_path, updated)
|
||||
|
||||
from backend.services.job_manager import JobManager
|
||||
JobManager().update_file_url(job_id, "lyrics", "corrections_updated", updated_path)
|
||||
logger.info(
|
||||
f"[job:{job_id}] auto-approval saved corrections_updated.json "
|
||||
f"({len(result['applied_ids'])} suggestions applied, "
|
||||
f"{len(result['rejected_ids'])} conflict-losers rejected)"
|
||||
)
|
||||
return {"applied_ids": result["applied_ids"]}
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Single source of truth for the auto instrumental-selection decision.
|
||||
|
||||
The backing decision is derived in three places that MUST agree:
|
||||
- the executor, when auto-completing a job (live verdict object);
|
||||
- ``POST /review/{id}/complete`` when a client sends ``instrumental_selection="auto"``
|
||||
(reads the stored ``processing_metadata.auto_approval`` verdict);
|
||||
- the ``/correction-data`` response summary the frontend uses to decide whether to
|
||||
show the instrumental screen at all (per-screen skip, C1).
|
||||
|
||||
``backing_decision`` is a pure function over primitives so all three can call it with
|
||||
either the live verdict or the persisted dict. It also folds in the user's up-front
|
||||
``backing_preference`` (C3): ``clean`` forces a clean instrumental, ``review`` suppresses
|
||||
the auto backing decision so a human always picks.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
BACKING_PREFERENCE_AUTO = "auto" # retain backing vocals where confidently safe (default)
|
||||
BACKING_PREFERENCE_CLEAN = "clean" # always use the clean instrumental
|
||||
BACKING_PREFERENCE_REVIEW = "review" # always let a human pick the instrumental
|
||||
VALID_BACKING_PREFERENCES = (
|
||||
BACKING_PREFERENCE_AUTO,
|
||||
BACKING_PREFERENCE_CLEAN,
|
||||
BACKING_PREFERENCE_REVIEW,
|
||||
)
|
||||
|
||||
|
||||
def has_custom_instrumental(job) -> bool:
|
||||
"""True when the user supplied their own instrumental (tenant bulk uploads,
|
||||
the upload flow's existing-instrumental option, or a mute-region edit).
|
||||
|
||||
For these jobs there is NO instrumental decision to make — the human
|
||||
complete-review flow submits ``instrumental_selection="custom"``.
|
||||
"""
|
||||
stems = (job.file_urls or {}).get("stems", {}) if job.file_urls else {}
|
||||
return bool(
|
||||
getattr(job, "existing_instrumental_gcs_path", None)
|
||||
or stems.get("custom_instrumental")
|
||||
)
|
||||
|
||||
|
||||
def backing_decision(
|
||||
*,
|
||||
backing_verdict: Optional[str],
|
||||
backing_non_subjective: bool,
|
||||
backing_preference: Optional[str],
|
||||
backing_keep_enabled: bool,
|
||||
custom_instrumental: bool,
|
||||
) -> Dict[str, Any]:
|
||||
"""Resolve the instrumental decision from a (live or stored) backing verdict.
|
||||
|
||||
Returns ``{"ok": bool, "selection": Optional[str], "keep_backing": bool}``:
|
||||
- ``ok`` — the instrumental can be auto-selected (no human needed for this half).
|
||||
- ``selection`` — "custom" | "clean" | "with_backing" | None (None ⇒ human must pick).
|
||||
- ``keep_backing`` — informational: the confident verdict is a with-backing keep
|
||||
(used by the executor to require the with-backing stem).
|
||||
"""
|
||||
if custom_instrumental:
|
||||
return {"ok": True, "selection": "custom", "keep_backing": False}
|
||||
|
||||
pref = backing_preference or BACKING_PREFERENCE_AUTO
|
||||
if pref == BACKING_PREFERENCE_CLEAN:
|
||||
# User asked to always strip backing vocals.
|
||||
return {"ok": True, "selection": "clean", "keep_backing": False}
|
||||
if pref == BACKING_PREFERENCE_REVIEW:
|
||||
# User asked to always decide the instrumental themselves.
|
||||
return {"ok": False, "selection": None, "keep_backing": False}
|
||||
|
||||
# pref == auto: rely on the non-subjective backing verdict.
|
||||
if not backing_non_subjective:
|
||||
return {"ok": False, "selection": None, "keep_backing": False}
|
||||
if backing_verdict == "with_backing":
|
||||
# Confident 3-stem keep — gated shadow-first behind its own flag.
|
||||
if not backing_keep_enabled:
|
||||
return {"ok": False, "selection": None, "keep_backing": True}
|
||||
return {"ok": True, "selection": "with_backing", "keep_backing": True}
|
||||
# Confident CLEAN ("no audible backing").
|
||||
return {"ok": True, "selection": "clean", "keep_backing": False}
|
||||
|
||||
|
||||
def auto_approval_summary(job, settings) -> Dict[str, Any]:
|
||||
"""Compact block for the ``/correction-data`` response (C1 per-screen skip).
|
||||
|
||||
Reads the stored ``processing_metadata.auto_approval`` verdict + the job's
|
||||
``backing_preference`` and tells the frontend whether each review half is
|
||||
confidently resolved (so it can skip that screen).
|
||||
"""
|
||||
aa = (getattr(job, "processing_metadata", None) or {}).get("auto_approval") or {}
|
||||
backing = aa.get("backing") or {}
|
||||
lyrics = aa.get("lyrics") or {}
|
||||
custom = has_custom_instrumental(job)
|
||||
|
||||
# ``always_review`` (or any non-"auto" review_mode) means the user asked to
|
||||
# see every screen — no half is ever "confident" enough to skip.
|
||||
review_mode = getattr(job, "review_mode", "auto") or "auto"
|
||||
if review_mode != "auto":
|
||||
return {
|
||||
"backing": {"verdict": backing.get("verdict"), "confident": False, "resolved_selection": None},
|
||||
"lyrics": {"verdict": lyrics.get("verdict"), "confident": False},
|
||||
"custom_instrumental": custom,
|
||||
"verdict_present": bool(aa),
|
||||
}
|
||||
|
||||
decision = backing_decision(
|
||||
backing_verdict=backing.get("verdict"),
|
||||
backing_non_subjective=bool(backing.get("non_subjective")),
|
||||
backing_preference=getattr(job, "backing_preference", BACKING_PREFERENCE_AUTO),
|
||||
backing_keep_enabled=bool(getattr(settings, "auto_approval_backing_keep_enabled", False)),
|
||||
custom_instrumental=custom,
|
||||
)
|
||||
selection = _selection_with_stem_check(job, decision["selection"])
|
||||
return {
|
||||
"backing": {
|
||||
"verdict": backing.get("verdict"),
|
||||
"confident": selection is not None,
|
||||
"resolved_selection": selection,
|
||||
},
|
||||
"lyrics": {
|
||||
"verdict": lyrics.get("verdict"),
|
||||
"confident": lyrics.get("verdict") == "auto",
|
||||
},
|
||||
"custom_instrumental": custom,
|
||||
"verdict_present": bool(aa),
|
||||
}
|
||||
|
||||
|
||||
def _selection_with_stem_check(job, selection: Optional[str]) -> Optional[str]:
|
||||
"""None out a separated-stem selection when that stem isn't present, so the
|
||||
complete endpoint never persists an instrumental the render worker can't use
|
||||
(mirrors the executor's no_*_stem blockers). "custom" is validated elsewhere."""
|
||||
if selection in ("clean", "with_backing"):
|
||||
stems = (job.file_urls or {}).get("stems", {}) if job.file_urls else {}
|
||||
stem_key = "instrumental_with_backing" if selection == "with_backing" else "instrumental_clean"
|
||||
if not stems.get(stem_key):
|
||||
return None
|
||||
return selection
|
||||
|
||||
|
||||
def resolve_auto_instrumental(job, settings) -> Optional[str]:
|
||||
"""Map a client's ``instrumental_selection="auto"`` to a concrete selection
|
||||
from the stored verdict, or None when it isn't confidently resolvable."""
|
||||
return auto_approval_summary(job, settings)["backing"]["resolved_selection"]
|
||||
@@ -0,0 +1,250 @@
|
||||
"""Reconstruct exactly what a human changed during lyrics review.
|
||||
|
||||
Diffs the raw transcription (``corrections.json`` -> ``corrected_segments``) against
|
||||
the reviewer's final result (``corrections_updated.json`` -> ``corrected_segments``).
|
||||
Because production runs with auto-correction disabled, the original ``corrected_segments``
|
||||
IS the raw AudioShake transcription, so this diff is *exactly* the set of manual edits
|
||||
Andrew made — the ground truth the recording corpus is built on.
|
||||
|
||||
Words carry stable ``id``s, BUT the review UI assigns a NEW id when a word's text is
|
||||
replaced (rather than mutating in place). It preserves the word's start/end time and line,
|
||||
though — so a text correction shows up as a delete+insert at the *same timing*. We recover
|
||||
those as ``replacements`` by pairing a deletion with an insertion sharing (line, start, end).
|
||||
|
||||
The diff is keyed on word id and yields:
|
||||
- ``replacements`` — a word swapped for another at the same time/line (`Carl` → `Karl`);
|
||||
the common case for mis-transcribed words
|
||||
- ``text_edits`` — same id, changed text (in-place edit; rare)
|
||||
- ``timing_changes`` — same id, moved start/end (a sync nudge)
|
||||
- ``deletions`` — a word removed with no same-timing replacement (adlib/dupe/etc.)
|
||||
- ``insertions`` — a word added with no same-timing original
|
||||
- ``segmentation`` — line count changed or a word moved between lines (split/merge/rewrap)
|
||||
|
||||
See ``docs/archive/2026-08-25-full-auto-review-design.md``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
# Minimum start/end move (seconds) to count as a deliberate timing change, not float noise.
|
||||
TIMING_EPSILON = 0.005
|
||||
# Max start/end difference (seconds) to treat a delete+insert as an in-place replacement.
|
||||
REPLACE_TIMING_EPSILON = 0.02
|
||||
|
||||
|
||||
@dataclass
|
||||
class TextEdit:
|
||||
word_id: str
|
||||
original_text: str
|
||||
final_text: str
|
||||
segment_index: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class TimingChange:
|
||||
word_id: str
|
||||
text: str
|
||||
original_start: Optional[float]
|
||||
original_end: Optional[float]
|
||||
final_start: Optional[float]
|
||||
final_end: Optional[float]
|
||||
start_delta: Optional[float]
|
||||
end_delta: Optional[float]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Replacement:
|
||||
"""A word swapped for another at the same time/line (mis-transcription fix)."""
|
||||
|
||||
original_word_id: str
|
||||
final_word_id: str
|
||||
original_text: str
|
||||
final_text: str
|
||||
segment_index: int
|
||||
start_time: Optional[float]
|
||||
|
||||
|
||||
@dataclass
|
||||
class WordRef:
|
||||
word_id: str
|
||||
text: str
|
||||
segment_index: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class SegmentMove:
|
||||
"""A word that stayed but moved to a different line (split/merge/rewrap)."""
|
||||
|
||||
word_id: str
|
||||
text: str
|
||||
original_segment_index: int
|
||||
final_segment_index: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class LyricsDiff:
|
||||
has_changes: bool = False
|
||||
total_changes: int = 0
|
||||
original_segment_count: int = 0
|
||||
final_segment_count: int = 0
|
||||
original_word_count: int = 0
|
||||
final_word_count: int = 0
|
||||
segmentation_changed: bool = False
|
||||
replacements: List[Replacement] = field(default_factory=list)
|
||||
text_edits: List[TextEdit] = field(default_factory=list)
|
||||
timing_changes: List[TimingChange] = field(default_factory=list)
|
||||
deletions: List[WordRef] = field(default_factory=list)
|
||||
insertions: List[WordRef] = field(default_factory=list)
|
||||
segment_moves: List[SegmentMove] = field(default_factory=list)
|
||||
# The UI-recorded WordCorrection list from corrections_updated.json (supplementary).
|
||||
ui_recorded_corrections: int = 0
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
def _index_words(segments: List[Dict[str, Any]]) -> Tuple[Dict[str, Dict[str, Any]], int]:
|
||||
"""Return {word_id: {text,start,end,segment_index}} and total word count."""
|
||||
by_id: Dict[str, Dict[str, Any]] = {}
|
||||
count = 0
|
||||
for seg_index, seg in enumerate(segments or []):
|
||||
for word in seg.get("words") or []:
|
||||
wid = word.get("id")
|
||||
count += 1
|
||||
if not wid:
|
||||
continue
|
||||
by_id[wid] = {
|
||||
"text": (word.get("text") or "").strip(),
|
||||
"start": word.get("start_time"),
|
||||
"end": word.get("end_time"),
|
||||
"segment_index": seg_index,
|
||||
}
|
||||
return by_id, count
|
||||
|
||||
|
||||
def _delta(a: Optional[float], b: Optional[float]) -> Optional[float]:
|
||||
if a is None or b is None:
|
||||
return None
|
||||
return round(b - a, 4)
|
||||
|
||||
|
||||
def compute_lyrics_diff(
|
||||
original_data: Dict[str, Any],
|
||||
updated_data: Optional[Dict[str, Any]],
|
||||
) -> LyricsDiff:
|
||||
"""Diff raw transcription against the reviewer's final result.
|
||||
|
||||
``original_data``: parsed ``corrections.json``.
|
||||
``updated_data``: parsed ``corrections_updated.json`` (or ``None`` if the job was
|
||||
never edited — yields an empty diff).
|
||||
"""
|
||||
orig_segments = original_data.get("corrected_segments") or []
|
||||
orig_by_id, orig_count = _index_words(orig_segments)
|
||||
|
||||
diff = LyricsDiff(
|
||||
original_segment_count=len(orig_segments),
|
||||
original_word_count=orig_count,
|
||||
)
|
||||
|
||||
if not updated_data or "corrected_segments" not in updated_data:
|
||||
# No human edits recorded — final == raw transcription.
|
||||
diff.final_segment_count = len(orig_segments)
|
||||
diff.final_word_count = orig_count
|
||||
return diff
|
||||
|
||||
final_segments = updated_data.get("corrected_segments") or []
|
||||
final_by_id, final_count = _index_words(final_segments)
|
||||
diff.final_segment_count = len(final_segments)
|
||||
diff.final_word_count = final_count
|
||||
diff.ui_recorded_corrections = len(updated_data.get("corrections") or [])
|
||||
|
||||
orig_ids = set(orig_by_id)
|
||||
final_ids = set(final_by_id)
|
||||
|
||||
deleted_ids = sorted(orig_ids - final_ids)
|
||||
inserted_ids = sorted(final_ids - orig_ids)
|
||||
|
||||
# Pair delete+insert at the same line & timing into replacements (mis-transcription
|
||||
# fixes: the UI re-keys the word but keeps its slot). One-to-one, greedy.
|
||||
unmatched_inserts = list(inserted_ids)
|
||||
for did in deleted_ids:
|
||||
o = orig_by_id[did]
|
||||
match = None
|
||||
for iid in unmatched_inserts:
|
||||
f = final_by_id[iid]
|
||||
if (
|
||||
o["segment_index"] == f["segment_index"]
|
||||
and o["start"] is not None and f["start"] is not None
|
||||
and abs((o["start"] or 0) - (f["start"] or 0)) <= REPLACE_TIMING_EPSILON
|
||||
and abs((o["end"] or 0) - (f["end"] or 0)) <= REPLACE_TIMING_EPSILON
|
||||
):
|
||||
match = iid
|
||||
break
|
||||
if match is not None:
|
||||
f = final_by_id[match]
|
||||
unmatched_inserts.remove(match)
|
||||
diff.replacements.append(
|
||||
Replacement(
|
||||
original_word_id=did,
|
||||
final_word_id=match,
|
||||
original_text=o["text"],
|
||||
final_text=f["text"],
|
||||
segment_index=f["segment_index"],
|
||||
start_time=f["start"],
|
||||
)
|
||||
)
|
||||
else:
|
||||
diff.deletions.append(WordRef(did, o["text"], o["segment_index"]))
|
||||
|
||||
for iid in unmatched_inserts:
|
||||
w = final_by_id[iid]
|
||||
diff.insertions.append(WordRef(iid, w["text"], w["segment_index"]))
|
||||
|
||||
for wid in sorted(orig_ids & final_ids):
|
||||
o = orig_by_id[wid]
|
||||
f = final_by_id[wid]
|
||||
|
||||
if o["text"] != f["text"]:
|
||||
diff.text_edits.append(
|
||||
TextEdit(wid, o["text"], f["text"], f["segment_index"])
|
||||
)
|
||||
|
||||
start_d = _delta(o["start"], f["start"])
|
||||
end_d = _delta(o["end"], f["end"])
|
||||
if (start_d is not None and abs(start_d) > TIMING_EPSILON) or (
|
||||
end_d is not None and abs(end_d) > TIMING_EPSILON
|
||||
):
|
||||
diff.timing_changes.append(
|
||||
TimingChange(
|
||||
word_id=wid,
|
||||
text=f["text"],
|
||||
original_start=o["start"],
|
||||
original_end=o["end"],
|
||||
final_start=f["start"],
|
||||
final_end=f["end"],
|
||||
start_delta=start_d,
|
||||
end_delta=end_d,
|
||||
)
|
||||
)
|
||||
|
||||
if o["segment_index"] != f["segment_index"]:
|
||||
diff.segment_moves.append(
|
||||
SegmentMove(wid, f["text"], o["segment_index"], f["segment_index"])
|
||||
)
|
||||
|
||||
diff.segmentation_changed = bool(
|
||||
diff.segment_moves
|
||||
or diff.original_segment_count != diff.final_segment_count
|
||||
)
|
||||
diff.total_changes = (
|
||||
len(diff.replacements)
|
||||
+ len(diff.text_edits)
|
||||
+ len(diff.timing_changes)
|
||||
+ len(diff.deletions)
|
||||
+ len(diff.insertions)
|
||||
+ len(diff.segment_moves)
|
||||
)
|
||||
diff.has_changes = diff.total_changes > 0
|
||||
return diff
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Data models for the auto-approvability scorer.
|
||||
|
||||
These are plain dataclasses (JSON-serializable via ``asdict``) so the verdict can
|
||||
be logged into ``processing_metadata`` and written into the offline recording
|
||||
corpus without pulling in extra dependencies.
|
||||
|
||||
See ``docs/archive/2026-08-25-full-auto-review-design.md`` for the design.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from enum import Enum
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
|
||||
class LyricsVerdict(str, Enum):
|
||||
"""Whether the lyrics look safe to auto-approve without human review."""
|
||||
|
||||
AUTO = "auto" # confident the synced lyrics are already correct
|
||||
REVIEW = "review" # needs a human
|
||||
|
||||
|
||||
class BackingVerdict(str, Enum):
|
||||
"""Backing-vocals decision confidence."""
|
||||
|
||||
CLEAN = "clean" # non-subjective: no backing vocals to retain -> clean
|
||||
WITH_BACKING = "with_backing" # (reserved) confidently retain
|
||||
REVIEW = "review" # subjective -> needs a human listen
|
||||
|
||||
|
||||
@dataclass
|
||||
class LyricsSignals:
|
||||
"""The quantitative signals extracted from ``corrections.json``."""
|
||||
|
||||
total_words: int = 0
|
||||
anchor_word_count: int = 0
|
||||
gap_word_count: int = 0
|
||||
anchor_word_fraction: float = 0.0
|
||||
uncorrected_gap_fraction: float = 0.0
|
||||
corrections_made: int = 0
|
||||
anchor_sequences_count: int = 0
|
||||
gap_sequences_count: int = 0
|
||||
# Reference-lyrics agreement
|
||||
accepted_reference_sources: List[str] = field(default_factory=list)
|
||||
best_reference_relevance: float = 0.0
|
||||
strong_reference_sources: int = 0
|
||||
has_synced_reference: bool = False
|
||||
# Guards
|
||||
correction_actually_ran: bool = False
|
||||
# AI auto-correct suggestions (auto-applied on review load — see corpus SYNTHESIS):
|
||||
# gap words COVERED by a suggestion get fixed before a human would ever look,
|
||||
# so post-AI confidence keys off the UNCOVERED remainder, not the raw gap count.
|
||||
ai_suggestions_available: bool = False
|
||||
ai_suggestion_count: int = 0
|
||||
ai_full_consensus_count: int = 0
|
||||
gap_words_covered_by_ai: int = 0
|
||||
uncovered_gap_word_count: int = 0
|
||||
uncovered_gap_fraction: float = 0.0
|
||||
# Gating class: non-lexical vocalization sections (Pattern 3 — never fully auto)
|
||||
vocalization_word_count: int = 0
|
||||
vocalization_max_run: int = 0
|
||||
long_vocalization_word_count: int = 0
|
||||
has_vocalization_section: bool = False
|
||||
# Gating class: phantom/hallucinated lines with absurd durations (Pattern 8)
|
||||
max_word_duration_s: float = 0.0
|
||||
absurd_duration_word_count: int = 0
|
||||
suspicious_parenthetical_count: int = 0
|
||||
has_phantom_signature: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class BackingSignals:
|
||||
"""The quantitative signals extracted from ``backing_vocals_analysis``."""
|
||||
|
||||
analysis_present: bool = False
|
||||
has_audible_content: bool = True
|
||||
audible_percentage: float = 0.0
|
||||
segment_count: int = 0
|
||||
loud_segment_count: int = 0
|
||||
peak_amplitude_db: Optional[float] = None
|
||||
recommended_selection: Optional[str] = None
|
||||
# 3-stem comparison (backing vs lead vs full vocals) — present on jobs
|
||||
# analyzed since the Phase-2B backing decider; absent before that.
|
||||
comparison_present: bool = False
|
||||
coverage_ratio: float = 0.0
|
||||
corr_backing_vocals: float = 0.0
|
||||
corr_backing_lead: float = 0.0
|
||||
lead_overlap_fraction: float = 0.0
|
||||
lead_audible_fraction: float = 0.0
|
||||
backing_audible_fraction: float = 0.0
|
||||
backing_median_db: Optional[float] = None
|
||||
lead_median_db: Optional[float] = None
|
||||
backing_db_std: float = 0.0
|
||||
flat_fraction: float = 0.0
|
||||
|
||||
|
||||
@dataclass
|
||||
class LyricsResult:
|
||||
verdict: LyricsVerdict
|
||||
tier: str # short label, e.g. "synced-perfect", "high-anchor", "needs-review"
|
||||
signals: LyricsSignals
|
||||
reasons: List[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class BackingResult:
|
||||
verdict: BackingVerdict
|
||||
non_subjective: bool # True only when the decision has no taste component
|
||||
signals: BackingSignals
|
||||
reasons: List[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class AutoApprovabilityVerdict:
|
||||
"""Combined shadow verdict for a job.
|
||||
|
||||
``overall_auto`` is intentionally the *conjunction* of a confident lyrics
|
||||
verdict and a non-subjective backing decision — the narrow, safe intersection
|
||||
Andrew asked to start with. Anything less stays in human review.
|
||||
"""
|
||||
|
||||
lyrics: LyricsResult
|
||||
backing: BackingResult
|
||||
overall_auto: bool
|
||||
scorer_version: str
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
# Convert Enum members to their plain string values so the dict is safe
|
||||
# for both json.dumps and Firestore writes.
|
||||
return asdict(
|
||||
self,
|
||||
dict_factory=lambda pairs: {
|
||||
k: (v.value if isinstance(v, Enum) else v) for k, v in pairs
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Server-side pre-apply of AI corrections BEFORE the review-ready notification.
|
||||
|
||||
Andrew's directive (2026-08-29): *"apply the ai-generated lyrics corrections and any
|
||||
post-ai heuristic fixes before the user ever sees the notification/button saying the
|
||||
lyrics review is ready ... it should all be done server-side and loaded as a single
|
||||
load event when the lyrics review page launches."*
|
||||
|
||||
Called from ``screens_worker`` for review-bound jobs (i.e. when the executor did NOT
|
||||
auto-complete the whole job), just before the AWAITING_REVIEW transition. It applies
|
||||
the same cached suggestions the review UI would auto-apply on load, using the same
|
||||
machinery the executor uses (``apply.build_applied_segments``), and writes
|
||||
``corrections_updated.json`` with a ``pre_applied`` marker so the ``/correction-data``
|
||||
endpoint serves the already-corrected state in a single load — eliminating the
|
||||
in-browser auto-apply race.
|
||||
|
||||
BEST-EFFORT: never raises, bounded. On any miss (proactive disabled, cache absent,
|
||||
LLM outage, sanity-check abort) it simply does nothing and the review UI falls back to
|
||||
its existing client-side on-load auto-apply. Auto-approval must never strand a job.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
CORRECTIONS_PATH = "jobs/{job_id}/lyrics/corrections.json"
|
||||
CORRECTIONS_UPDATED_PATH = "jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
|
||||
|
||||
async def ensure_and_pre_apply(job_id: str, *, generate_on_miss: bool = True) -> Dict[str, Any]:
|
||||
"""Ensure the suggestion cache exists, apply it, and persist the pre-applied
|
||||
corrections with a ``pre_applied`` marker. Returns a small status dict; never
|
||||
raises.
|
||||
|
||||
``generate_on_miss`` (default True, the screens_worker path): when the proactive
|
||||
cache is absent, generate it synchronously (bounded) before applying. The
|
||||
``/correction-data`` load path passes False — it only applies an EXISTING cache
|
||||
so a review page never blocks on a multi-model LLM call; a cache-miss there
|
||||
falls through to the UI's own client-side apply.
|
||||
"""
|
||||
try:
|
||||
from backend.config import get_settings
|
||||
from backend.services.auto_approval.apply import build_applied_segments
|
||||
from backend.services.auto_approval.executor import _load_ai_suggestions
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
settings = get_settings()
|
||||
storage = StorageService()
|
||||
|
||||
corrections_path = CORRECTIONS_PATH.format(job_id=job_id)
|
||||
if not storage.file_exists(corrections_path):
|
||||
return {"outcome": "skipped", "reason": "no_corrections"}
|
||||
|
||||
updated_path = CORRECTIONS_UPDATED_PATH.format(job_id=job_id)
|
||||
if storage.file_exists(updated_path):
|
||||
# Already applied once (executor auto-complete, a prior pre-apply run,
|
||||
# or a human edit). Never clobber existing corrections_updated.json.
|
||||
try:
|
||||
existing = storage.download_json(updated_path)
|
||||
if ((existing.get("metadata") or {}).get("auto_approval")):
|
||||
return {"outcome": "skipped", "reason": "already_applied"}
|
||||
except Exception:
|
||||
pass
|
||||
return {"outcome": "skipped", "reason": "corrections_updated_exists"}
|
||||
|
||||
corrections = storage.download_json(corrections_path)
|
||||
|
||||
# 1) Ensure the proactive suggestion cache exists (generate on miss, unless
|
||||
# the caller — e.g. the load-time path — asked to only apply an existing
|
||||
# cache so the request doesn't block on an LLM call).
|
||||
ai_suggestions = _load_ai_suggestions(storage, job_id)
|
||||
if ai_suggestions is None and generate_on_miss and settings.auto_correct_proactive_enabled:
|
||||
logger.info(f"[job:{job_id}] pre-apply: cache miss, generating suggestions synchronously")
|
||||
from backend.workers.auto_correct_worker import process_proactive_auto_correct
|
||||
await process_proactive_auto_correct(job_id) # bounded (180s) + best-effort
|
||||
ai_suggestions = _load_ai_suggestions(storage, job_id)
|
||||
|
||||
if ai_suggestions is None:
|
||||
# Unknown suggestion set (proactive disabled or generation failed) —
|
||||
# do NOT mark pre_applied; let the UI run its client-side apply.
|
||||
return {"outcome": "skipped", "reason": "no_suggestions_cache"}
|
||||
|
||||
# 2) Apply with the executor's sanity gates.
|
||||
result = build_applied_segments(corrections, ai_suggestions)
|
||||
if result.get("aborted"):
|
||||
logger.info(f"[job:{job_id}] pre-apply aborted ({result['aborted']}) — UI will apply client-side")
|
||||
return {"outcome": "skipped", "reason": result["aborted"]}
|
||||
|
||||
# 3) Persist corrections_updated.json with the pre_applied marker + the
|
||||
# suggestions themselves (so the review panel renders applied state).
|
||||
updated = dict(corrections)
|
||||
updated["corrected_segments"] = result["segments"]
|
||||
metadata = dict(updated.get("metadata") or {})
|
||||
metadata["auto_approval"] = {
|
||||
"pre_applied": True,
|
||||
"applied_suggestion_ids": result["applied_ids"],
|
||||
"rejected_suggestion_ids": result["rejected_ids"],
|
||||
"suggestions": ai_suggestions,
|
||||
"applied_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
updated["metadata"] = metadata
|
||||
# Create-only write: we only reach here when corrections_updated.json was
|
||||
# absent at the check above, so if_generation_match=0 makes the write atomic —
|
||||
# a concurrent writer (executor auto-complete, or an edit submission) that
|
||||
# created it in the meantime wins and we don't clobber their (newer) state.
|
||||
try:
|
||||
from google.api_core.exceptions import PreconditionFailed
|
||||
except Exception: # pragma: no cover - google libs always present in prod
|
||||
PreconditionFailed = () # type: ignore[assignment]
|
||||
try:
|
||||
storage.upload_json(updated_path, updated, if_generation_match=0)
|
||||
except PreconditionFailed:
|
||||
logger.info(f"[job:{job_id}] pre-apply raced a concurrent write — theirs wins")
|
||||
return {"outcome": "skipped", "reason": "raced_concurrent_write"}
|
||||
JobManager().update_file_url(job_id, "lyrics", "corrections_updated", updated_path)
|
||||
|
||||
logger.info(
|
||||
f"[job:{job_id}] pre-apply saved corrections_updated.json "
|
||||
f"({len(result['applied_ids'])} applied, {len(result['rejected_ids'])} rejected) "
|
||||
"before review notification"
|
||||
)
|
||||
return {"outcome": "pre_applied", "applied": len(result["applied_ids"])}
|
||||
|
||||
except Exception as e: # noqa: BLE001 — best-effort, never fatal
|
||||
logger.warning(f"[job:{job_id}] pre-apply failed non-fatally: {e}", exc_info=True)
|
||||
return {"outcome": "error", "error": str(e)}
|
||||
@@ -0,0 +1,600 @@
|
||||
"""Auto-approvability scorer.
|
||||
|
||||
Pure functions that decide, from signals that already exist on every job, whether
|
||||
a job's lyrics look safe to auto-approve without human review, and whether the
|
||||
backing-vocals decision is non-subjective.
|
||||
|
||||
This module runs **in shadow mode**: ``screens_worker`` computes + records the
|
||||
verdict in ``processing_metadata.auto_approval_shadow`` just before every job goes
|
||||
to human review, so verdicts can be validated against real review outcomes before
|
||||
the scorer is allowed to gate. See
|
||||
``docs/archive/2026-08-25-full-auto-review-design.md`` (+ session-4 update).
|
||||
|
||||
Design notes / traps handled here:
|
||||
- In production, auto-correction is DISABLED, so ``corrections.json`` always reports
|
||||
``corrections_made == 0`` and ``confidence == 1.0`` regardless of lyric quality
|
||||
(``controller.py`` uncorrected path). We therefore NEVER treat those two fields as
|
||||
positive evidence. Confidence comes from anchor coverage against reference lyrics,
|
||||
gap words left *uncovered* by the auto-applied AI suggestions, reference-source
|
||||
agreement, and the absence of the never-auto gating signatures.
|
||||
- ``anchor_sequences`` and ``gap_sequences`` are still computed when correction is
|
||||
disabled, so anchor/gap coverage is available on every prod job.
|
||||
- The review UI auto-applies the (pre-generated) AI suggestions on load, so a gap
|
||||
word covered by a suggestion is fixed before any human would look — raw gap
|
||||
counts alone do NOT separate AI-solved jobs from human-needed ones (2026-08-27
|
||||
20-job corpus calibration).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from backend.services.auto_approval.models import (
|
||||
AutoApprovabilityVerdict,
|
||||
BackingResult,
|
||||
BackingSignals,
|
||||
BackingVerdict,
|
||||
LyricsResult,
|
||||
LyricsSignals,
|
||||
LyricsVerdict,
|
||||
)
|
||||
|
||||
SCORER_VERSION = "0.3.0"
|
||||
|
||||
# --- Lyrics thresholds (deliberately conservative; the safe intersection first) ---
|
||||
# The AUTO tier requires a synced reference the transcription matches with ZERO
|
||||
# unresolved gaps. Empirically (job 79c4f60c "Clarity", 2026-08), a single gap word
|
||||
# on an otherwise 99.6%-anchored track was a genuine mis-transcription the reviewer
|
||||
# fixed ("I" -> "High"): a gap word is by definition a word with no confident reference
|
||||
# match, i.e. exactly where errors hide. So we do not tolerate any gaps for AUTO.
|
||||
MIN_TOTAL_WORDS = 10
|
||||
AUTO_MIN_ANCHOR_FRACTION = 0.99
|
||||
AUTO_MAX_GAP_FRACTION = 0.0
|
||||
# The "ai-resolved" AUTO tier accounts for the auto-applied AI corrections: raw gap
|
||||
# words that an AI suggestion covers get fixed on load before any human would look,
|
||||
# so confidence keys off the UNCOVERED remainder (corpus 2026-08-27: raw gap counts
|
||||
# do NOT separate AI-solved jobs from human-needed ones; uncovered gaps + the
|
||||
# never-auto gates + an anchor floor do).
|
||||
AI_RESOLVED_MIN_ANCHOR_FRACTION = 0.90
|
||||
AI_RESOLVED_MAX_UNCOVERED_FRACTION = 0.02
|
||||
AI_RESOLVED_MAX_UNCOVERED_WORDS = 6
|
||||
# A looser "near-miss" band, recorded for calibration but still sent to review.
|
||||
NEARMISS_MIN_ANCHOR_FRACTION = 0.95
|
||||
NEARMISS_MAX_GAP_FRACTION = 0.05
|
||||
|
||||
# --- Gating class: non-lexical vocalization sections (Pattern 3; never fully auto) ---
|
||||
# AudioShake mistimes da-da-dun / oh-oh / woo-woo sections badly (wrong count, rhythm,
|
||||
# segmentation); the correct grouping is a musical interpretation not recoverable from
|
||||
# its output (corpus jobs b5a7b8aa, a4dcaa21, 8f2305ee). Detect and route to a human.
|
||||
VOCALIZATION_TOKENS = frozenset({
|
||||
"da", "dun", "dum", "la", "na", "nah", "oh", "ooh", "oohs", "ah", "ahh", "aah",
|
||||
"woo", "whoa", "woah", "yeah", "hey", "ba", "bah", "doo", "dee", "di", "mm",
|
||||
"mmm", "hmm", "sha", "bop", "pa", "ra", "ta",
|
||||
})
|
||||
# A run of this many consecutive vocalization words = a vocalization section.
|
||||
VOCALIZATION_MIN_RUN = 5
|
||||
# A single sung vocalization rarely lasts this long; a multi-second "Ooh"/"da" almost
|
||||
# always means AudioShake lumped many short vocalizations into one (10.1s/4.0s examples).
|
||||
LONG_VOCALIZATION_DURATION_S = 3.5
|
||||
VERY_LONG_VOCALIZATION_DURATION_S = 6.0
|
||||
|
||||
# --- Gating class: phantom/hallucinated lines (Pattern 8) ---
|
||||
# Real sung words basically never span this long; corpus phantoms were 7.4s and 4.8s.
|
||||
ABSURD_WORD_DURATION_S = 5.0
|
||||
# Short parenthetical lines ("(I'm sorry)") stretched over multiple seconds are the
|
||||
# classic phantom signature.
|
||||
PHANTOM_PARENTHETICAL_DURATION_S = 4.0
|
||||
PHANTOM_PARENTHETICAL_MAX_WORDS = 4
|
||||
|
||||
# --- Backing thresholds ---
|
||||
# Only "there is literally no audible backing content" is treated as non-subjective.
|
||||
# A tiny non-zero floor absorbs separation noise but stays extremely conservative.
|
||||
NON_SUBJECTIVE_MAX_AUDIBLE_PCT = 0.5 # percent
|
||||
LOUD_SEGMENT_DB = -20.0
|
||||
|
||||
# --- 3-stem backing decider thresholds (Phase 2B) ---
|
||||
# Calibrated on the 20-job replay-review corpus signals (private
|
||||
# validate_backing_decider.py — rerun after ANY change here). Corpus rules:
|
||||
# pink present -> KEEP (the human under-keeps; every with_backing pick was
|
||||
# correct), EXCEPT the "pink but don't keep" modes below.
|
||||
#
|
||||
# Backing-stem-IS-the-lead (1d45b286 — catastrophic if kept): the backing stem
|
||||
# tracks the whole vocal line while the real lead stem is comparatively
|
||||
# sparse. Corpus values: covR 0.94 / corr 0.95 / backing 60% audible vs lead
|
||||
# 18%. The coverage comparison (backing > lead) is the decisive discriminator:
|
||||
# the nearest genuine keep (33453fa0) hits covR 0.77 / corr 0.86 but its
|
||||
# backing coverage (28%) sits well BELOW its lead coverage (34%).
|
||||
BACKING_IS_LEAD_MIN_COVERAGE_RATIO = 0.80
|
||||
BACKING_IS_LEAD_MIN_CORR = 0.80
|
||||
# Noise-floor pink (95d8e844, grungegaze): a fuzzy mix pushes the backing
|
||||
# stem's noise floor just above the -40 dB threshold, producing widespread
|
||||
# near-threshold "pink" that does not correlate with the vocal line (corpus:
|
||||
# median -38.6 dB over 30% of the track, corr -0.23). Genuine quiet harmonies
|
||||
# (d508adb6: -38.1 dB but only 1% audible; 44622ffa: -35.9 dB, 11%) are sparse.
|
||||
# Marginal either way per the corpus -> REVIEW, never a confident verdict.
|
||||
NOISE_FLOOR_MAX_MEDIAN_DB = -35.0
|
||||
NOISE_FLOOR_MIN_AUDIBLE_FRACTION = 0.15
|
||||
NOISE_FLOOR_MAX_CORR = 0.05
|
||||
# Lead bleed (ae0cd7e8): tiny audible content riding entirely on lead
|
||||
# activity. The corpus bleed case is already caught by the near-silent rule;
|
||||
# this catches slightly-larger blobs. Deliberately NARROW (overlap >= 0.95):
|
||||
# d508adb6's genuine harmonies overlap the lead 0.89 and must stay keepable.
|
||||
BLEED_MAX_AUDIBLE_PCT = 3.0
|
||||
BLEED_MIN_LEAD_OVERLAP = 0.95
|
||||
|
||||
_TOKEN_STRIP_RE = re.compile(r"^[^\w]+|[^\w]+$")
|
||||
|
||||
|
||||
def _count_ids(sequences: List[Dict[str, Any]]) -> int:
|
||||
total = 0
|
||||
for seq in sequences or []:
|
||||
ids = seq.get("transcribed_word_ids")
|
||||
if ids:
|
||||
total += len(ids)
|
||||
return total
|
||||
|
||||
|
||||
def _is_vocalization_token(text: str) -> bool:
|
||||
"""True if a word looks like a non-lexical vocalization ("Da-", "dun,", "Woo-woo")."""
|
||||
t = _TOKEN_STRIP_RE.sub("", (text or "").lower())
|
||||
if not t:
|
||||
return False
|
||||
parts = [p for p in t.split("-") if p]
|
||||
return bool(parts) and all(p in VOCALIZATION_TOKENS for p in parts)
|
||||
|
||||
|
||||
def _word_duration(word: Dict[str, Any]) -> float:
|
||||
start = word.get("start_time")
|
||||
end = word.get("end_time")
|
||||
if isinstance(start, (int, float)) and isinstance(end, (int, float)) and end > start:
|
||||
return float(end) - float(start)
|
||||
return 0.0
|
||||
|
||||
|
||||
def _extract_gating_signals(
|
||||
correction_data: Dict[str, Any],
|
||||
) -> Tuple[int, int, int, bool, float, int, int, bool]:
|
||||
"""Scan corrected_segments for the two never-auto gating classes.
|
||||
|
||||
Returns (vocalization_word_count, vocalization_max_run, long_vocalization_word_count,
|
||||
has_vocalization_section, max_word_duration_s, absurd_duration_word_count,
|
||||
suspicious_parenthetical_count, has_phantom_signature).
|
||||
"""
|
||||
voc_count = 0
|
||||
max_run = 0
|
||||
run = 0 # runs continue across segment boundaries (consecutive vocalization lines)
|
||||
long_voc = 0
|
||||
very_long_voc = 0
|
||||
max_duration = 0.0
|
||||
absurd = 0
|
||||
suspicious_paren = 0
|
||||
|
||||
for seg in correction_data.get("corrected_segments") or []:
|
||||
words = seg.get("words") or []
|
||||
for word in words:
|
||||
duration = _word_duration(word)
|
||||
max_duration = max(max_duration, duration)
|
||||
if duration > ABSURD_WORD_DURATION_S:
|
||||
absurd += 1
|
||||
if _is_vocalization_token(word.get("text") or ""):
|
||||
voc_count += 1
|
||||
run += 1
|
||||
max_run = max(max_run, run)
|
||||
if duration >= VERY_LONG_VOCALIZATION_DURATION_S:
|
||||
very_long_voc += 1
|
||||
long_voc += 1
|
||||
elif duration >= LONG_VOCALIZATION_DURATION_S:
|
||||
long_voc += 1
|
||||
else:
|
||||
run = 0
|
||||
|
||||
# Phantom signature: a short parenthetical line stretched over several seconds
|
||||
# (e.g. three "(I'm sorry)" lines, one 7.4s — corpus job 33453fa0).
|
||||
seg_text = (seg.get("text") or "").strip()
|
||||
if (
|
||||
seg_text.startswith("(")
|
||||
and seg_text.endswith(")")
|
||||
and 0 < len(words) <= PHANTOM_PARENTHETICAL_MAX_WORDS
|
||||
):
|
||||
seg_start, seg_end = seg.get("start_time"), seg.get("end_time")
|
||||
if (
|
||||
isinstance(seg_start, (int, float))
|
||||
and isinstance(seg_end, (int, float))
|
||||
and seg_end - seg_start >= PHANTOM_PARENTHETICAL_DURATION_S
|
||||
):
|
||||
suspicious_paren += 1
|
||||
|
||||
has_vocalization_section = (
|
||||
max_run >= VOCALIZATION_MIN_RUN or long_voc >= 2 or very_long_voc >= 1
|
||||
)
|
||||
has_phantom_signature = absurd >= 1 or suspicious_paren >= 1
|
||||
return (
|
||||
voc_count,
|
||||
max_run,
|
||||
long_voc,
|
||||
has_vocalization_section,
|
||||
round(max_duration, 3),
|
||||
absurd,
|
||||
suspicious_paren,
|
||||
has_phantom_signature,
|
||||
)
|
||||
|
||||
|
||||
def _total_words(correction_data: Dict[str, Any]) -> int:
|
||||
meta = correction_data.get("metadata") or {}
|
||||
if isinstance(meta.get("total_words"), int) and meta["total_words"] > 0:
|
||||
return meta["total_words"]
|
||||
# Fallback: count from corrected_segments
|
||||
total = 0
|
||||
for seg in correction_data.get("corrected_segments") or []:
|
||||
total += len(seg.get("words") or [])
|
||||
return total
|
||||
|
||||
|
||||
def _gap_word_ids(correction_data: Dict[str, Any]) -> set:
|
||||
ids: set = set()
|
||||
for seq in correction_data.get("gap_sequences") or []:
|
||||
ids.update(seq.get("transcribed_word_ids") or [])
|
||||
return ids
|
||||
|
||||
|
||||
def extract_lyrics_signals(
|
||||
correction_data: Dict[str, Any],
|
||||
ai_suggestions: Optional[List[Dict[str, Any]]] = None,
|
||||
) -> LyricsSignals:
|
||||
"""Pull the quantitative lyrics signals out of a ``corrections.json`` dict.
|
||||
|
||||
``ai_suggestions`` is the (pre-generated) auto-correct suggestion list — the
|
||||
ones the review UI auto-applies on load. When provided, gap coverage is
|
||||
computed against it: a gap word touched by a suggestion will be fixed before
|
||||
any human looks, so only the *uncovered* gaps carry residual risk.
|
||||
"""
|
||||
meta = correction_data.get("metadata") or {}
|
||||
total_words = _total_words(correction_data)
|
||||
|
||||
anchor_words = _count_ids(correction_data.get("anchor_sequences"))
|
||||
gap_words = _count_ids(correction_data.get("gap_sequences"))
|
||||
|
||||
suggestion_word_ids: set = set()
|
||||
full_consensus = 0
|
||||
for sug in ai_suggestions or []:
|
||||
suggestion_word_ids.update(sug.get("word_ids") or [])
|
||||
total_models = sug.get("total_models")
|
||||
if (
|
||||
isinstance(total_models, int)
|
||||
and total_models >= 2
|
||||
and sug.get("consensus") == total_models
|
||||
):
|
||||
full_consensus += 1
|
||||
gap_ids = _gap_word_ids(correction_data)
|
||||
covered = len(gap_ids & suggestion_word_ids)
|
||||
uncovered = max(0, gap_words - covered)
|
||||
uncovered_fraction = min(1.0, uncovered / total_words) if total_words else 1.0
|
||||
|
||||
anchor_fraction = min(1.0, anchor_words / total_words) if total_words else 0.0
|
||||
gap_fraction = min(1.0, gap_words / total_words) if total_words else 1.0
|
||||
|
||||
reference_lyrics = correction_data.get("reference_lyrics") or {}
|
||||
accepted_sources = list(reference_lyrics.keys())
|
||||
|
||||
has_synced = False
|
||||
for src in accepted_sources:
|
||||
src_meta = ((reference_lyrics.get(src) or {}).get("metadata")) or {}
|
||||
if src_meta.get("is_synced"):
|
||||
has_synced = True
|
||||
break
|
||||
|
||||
# Relevance of accepted sources isn't stored directly; rejected_sources carries it.
|
||||
# Use it only to compute a best-observed relevance for context, never as a gate.
|
||||
best_relevance = 0.0
|
||||
rejected = meta.get("rejected_sources") or {}
|
||||
for info in rejected.values():
|
||||
rel = info.get("relevance")
|
||||
if isinstance(rel, (int, float)):
|
||||
best_relevance = max(best_relevance, float(rel))
|
||||
|
||||
agentic_routing = meta.get("agentic_routing")
|
||||
correction_type = meta.get("correction_type")
|
||||
correction_actually_ran = (
|
||||
agentic_routing not in (None, "disabled") and correction_type != "none"
|
||||
)
|
||||
|
||||
(
|
||||
voc_count,
|
||||
voc_max_run,
|
||||
long_voc,
|
||||
has_voc_section,
|
||||
max_duration,
|
||||
absurd,
|
||||
suspicious_paren,
|
||||
has_phantom,
|
||||
) = _extract_gating_signals(correction_data)
|
||||
|
||||
return LyricsSignals(
|
||||
total_words=total_words,
|
||||
anchor_word_count=anchor_words,
|
||||
gap_word_count=gap_words,
|
||||
anchor_word_fraction=round(anchor_fraction, 4),
|
||||
uncorrected_gap_fraction=round(gap_fraction, 4),
|
||||
corrections_made=int(correction_data.get("corrections_made") or 0),
|
||||
anchor_sequences_count=len(correction_data.get("anchor_sequences") or []),
|
||||
gap_sequences_count=len(correction_data.get("gap_sequences") or []),
|
||||
accepted_reference_sources=accepted_sources,
|
||||
best_reference_relevance=round(best_relevance, 4),
|
||||
strong_reference_sources=len(accepted_sources),
|
||||
has_synced_reference=has_synced,
|
||||
correction_actually_ran=correction_actually_ran,
|
||||
ai_suggestions_available=ai_suggestions is not None,
|
||||
ai_suggestion_count=len(ai_suggestions or []),
|
||||
ai_full_consensus_count=full_consensus,
|
||||
gap_words_covered_by_ai=covered,
|
||||
uncovered_gap_word_count=uncovered,
|
||||
uncovered_gap_fraction=round(uncovered_fraction, 4),
|
||||
vocalization_word_count=voc_count,
|
||||
vocalization_max_run=voc_max_run,
|
||||
long_vocalization_word_count=long_voc,
|
||||
has_vocalization_section=has_voc_section,
|
||||
max_word_duration_s=max_duration,
|
||||
absurd_duration_word_count=absurd,
|
||||
suspicious_parenthetical_count=suspicious_paren,
|
||||
has_phantom_signature=has_phantom,
|
||||
)
|
||||
|
||||
|
||||
def score_lyrics(
|
||||
correction_data: Dict[str, Any],
|
||||
ai_suggestions: Optional[List[Dict[str, Any]]] = None,
|
||||
) -> LyricsResult:
|
||||
"""Decide whether the lyrics look safe to auto-approve."""
|
||||
s = extract_lyrics_signals(correction_data, ai_suggestions)
|
||||
reasons: List[str] = []
|
||||
|
||||
if s.total_words < MIN_TOTAL_WORDS:
|
||||
reasons.append(
|
||||
f"only {s.total_words} words (< {MIN_TOTAL_WORDS}); too little signal to trust"
|
||||
)
|
||||
return LyricsResult(LyricsVerdict.REVIEW, "too-few-words", s, reasons)
|
||||
|
||||
# Never-auto gating classes: these override everything, including a perfect
|
||||
# anchor/gap profile — the transcription can be "anchored" yet still wrong in
|
||||
# ways only a human can judge (Pattern 3) or plainly hallucinated (Pattern 8).
|
||||
if s.has_vocalization_section:
|
||||
reasons.append(
|
||||
f"non-lexical vocalization section detected ({s.vocalization_word_count} "
|
||||
f"vocalization words, longest run {s.vocalization_max_run}, "
|
||||
f"{s.long_vocalization_word_count} multi-second) — timing/grouping is a "
|
||||
"musical judgement; never fully auto"
|
||||
)
|
||||
return LyricsResult(LyricsVerdict.REVIEW, "vocalization-gate", s, reasons)
|
||||
|
||||
if s.has_phantom_signature:
|
||||
reasons.append(
|
||||
f"phantom-line signature: {s.absurd_duration_word_count} words > "
|
||||
f"{ABSURD_WORD_DURATION_S:.0f}s (max {s.max_word_duration_s:.1f}s), "
|
||||
f"{s.suspicious_parenthetical_count} multi-second short parenthetical lines"
|
||||
)
|
||||
return LyricsResult(LyricsVerdict.REVIEW, "phantom-gate", s, reasons)
|
||||
|
||||
if not s.accepted_reference_sources:
|
||||
reasons.append("no reference lyrics survived the relevance filter")
|
||||
return LyricsResult(LyricsVerdict.REVIEW, "no-reference", s, reasons)
|
||||
|
||||
auto_ok = (
|
||||
s.has_synced_reference
|
||||
and s.anchor_word_fraction >= AUTO_MIN_ANCHOR_FRACTION
|
||||
and s.uncorrected_gap_fraction <= AUTO_MAX_GAP_FRACTION
|
||||
)
|
||||
if auto_ok:
|
||||
reasons.append(
|
||||
f"synced reference present; anchor coverage {s.anchor_word_fraction:.1%} "
|
||||
f">= {AUTO_MIN_ANCHOR_FRACTION:.0%}; zero unresolved gap words"
|
||||
)
|
||||
return LyricsResult(LyricsVerdict.AUTO, "synced-perfect", s, reasons)
|
||||
|
||||
# AI-resolved tier: the auto-applied suggestions cover (almost) every gap word,
|
||||
# anchoring is high, and no never-auto gate fired. What remains uncovered is a
|
||||
# handful of words with no confident reference match — empirically adlib/benign.
|
||||
ai_resolved_ok = (
|
||||
s.ai_suggestions_available
|
||||
and s.has_synced_reference
|
||||
and s.anchor_word_fraction >= AI_RESOLVED_MIN_ANCHOR_FRACTION
|
||||
and s.uncovered_gap_fraction <= AI_RESOLVED_MAX_UNCOVERED_FRACTION
|
||||
and s.uncovered_gap_word_count <= AI_RESOLVED_MAX_UNCOVERED_WORDS
|
||||
)
|
||||
if ai_resolved_ok:
|
||||
reasons.append(
|
||||
f"synced reference; anchor {s.anchor_word_fraction:.1%} >= "
|
||||
f"{AI_RESOLVED_MIN_ANCHOR_FRACTION:.0%}; {s.gap_word_count} gap words of "
|
||||
f"which {s.gap_words_covered_by_ai} covered by auto-applied AI suggestions, "
|
||||
f"{s.uncovered_gap_word_count} uncovered ({s.uncovered_gap_fraction:.1%})"
|
||||
)
|
||||
return LyricsResult(LyricsVerdict.AUTO, "ai-resolved", s, reasons)
|
||||
|
||||
# Not auto — classify why, for calibration.
|
||||
if (
|
||||
s.anchor_word_fraction >= NEARMISS_MIN_ANCHOR_FRACTION
|
||||
and s.uncorrected_gap_fraction <= NEARMISS_MAX_GAP_FRACTION
|
||||
):
|
||||
tier = "near-miss"
|
||||
if not s.has_synced_reference:
|
||||
reasons.append("high anchor coverage but NO synced reference (unsynced only)")
|
||||
else:
|
||||
reasons.append(
|
||||
f"anchor coverage {s.anchor_word_fraction:.1%} / gap "
|
||||
f"{s.uncorrected_gap_fraction:.1%} close but below AUTO thresholds"
|
||||
)
|
||||
else:
|
||||
tier = "needs-review"
|
||||
reasons.append(
|
||||
f"anchor coverage {s.anchor_word_fraction:.1%}, unresolved-gap fraction "
|
||||
f"{s.uncorrected_gap_fraction:.1%} ({s.gap_sequences_count} gaps)"
|
||||
)
|
||||
return LyricsResult(LyricsVerdict.REVIEW, tier, s, reasons)
|
||||
|
||||
|
||||
def extract_backing_signals(backing_analysis: Optional[Dict[str, Any]]) -> BackingSignals:
|
||||
"""Pull backing-vocals signals out of ``state_data.backing_vocals_analysis``."""
|
||||
if not backing_analysis:
|
||||
return BackingSignals(analysis_present=False)
|
||||
# A FAILED analysis stores has_audible_content=None + analysis_error; that
|
||||
# must never read as "no audible content" (which would wrongly auto-select
|
||||
# clean). Treat it as no-analysis -> review.
|
||||
if backing_analysis.get("analysis_error") or backing_analysis.get("has_audible_content") is None:
|
||||
return BackingSignals(analysis_present=False)
|
||||
|
||||
segments = backing_analysis.get("audible_segments") or []
|
||||
loud = 0
|
||||
peak: Optional[float] = None
|
||||
for seg in segments:
|
||||
avg_db = seg.get("avg_amplitude_db")
|
||||
if isinstance(avg_db, (int, float)) and avg_db > LOUD_SEGMENT_DB:
|
||||
loud += 1
|
||||
pk = seg.get("peak_amplitude_db")
|
||||
if isinstance(pk, (int, float)):
|
||||
peak = pk if peak is None else max(peak, pk)
|
||||
|
||||
signals = BackingSignals(
|
||||
analysis_present=True,
|
||||
has_audible_content=bool(backing_analysis.get("has_audible_content", True)),
|
||||
audible_percentage=float(backing_analysis.get("audible_percentage", 0.0) or 0.0),
|
||||
segment_count=len(segments),
|
||||
loud_segment_count=loud,
|
||||
peak_amplitude_db=peak,
|
||||
recommended_selection=backing_analysis.get("recommended_selection"),
|
||||
)
|
||||
|
||||
# 3-stem comparison (Phase 2B). A comparison that errored is treated as
|
||||
# absent — never as evidence in either direction.
|
||||
comparison = backing_analysis.get("stem_comparison") or {}
|
||||
if comparison and not comparison.get("error"):
|
||||
def _num(key: str, default: float = 0.0) -> float:
|
||||
value = comparison.get(key)
|
||||
return float(value) if isinstance(value, (int, float)) else default
|
||||
|
||||
signals.comparison_present = True
|
||||
signals.coverage_ratio = _num("coverage_ratio")
|
||||
signals.corr_backing_vocals = _num("corr_backing_vocals")
|
||||
signals.corr_backing_lead = _num("corr_backing_lead")
|
||||
signals.lead_overlap_fraction = _num("lead_overlap_fraction")
|
||||
signals.lead_audible_fraction = _num("lead_audible_fraction")
|
||||
signals.backing_audible_fraction = _num("backing_audible_fraction")
|
||||
signals.backing_db_std = _num("backing_db_std")
|
||||
signals.flat_fraction = _num("flat_fraction")
|
||||
backing_median = comparison.get("backing_median_db")
|
||||
lead_median = comparison.get("lead_median_db")
|
||||
if isinstance(backing_median, (int, float)):
|
||||
signals.backing_median_db = float(backing_median)
|
||||
if isinstance(lead_median, (int, float)):
|
||||
signals.lead_median_db = float(lead_median)
|
||||
return signals
|
||||
|
||||
|
||||
def score_backing(backing_analysis: Optional[Dict[str, Any]]) -> BackingResult:
|
||||
"""Decide whether the backing-vocals call is non-subjective (no audible backing)."""
|
||||
s = extract_backing_signals(backing_analysis)
|
||||
reasons: List[str] = []
|
||||
|
||||
if not s.analysis_present:
|
||||
reasons.append("no backing-vocals analysis on the job")
|
||||
return BackingResult(BackingVerdict.REVIEW, False, s, reasons)
|
||||
|
||||
non_subjective_clean = (
|
||||
not s.has_audible_content
|
||||
or (s.audible_percentage <= NON_SUBJECTIVE_MAX_AUDIBLE_PCT and s.loud_segment_count == 0)
|
||||
)
|
||||
if non_subjective_clean:
|
||||
reasons.append(
|
||||
"no audible backing vocals detected"
|
||||
if not s.has_audible_content
|
||||
else f"near-silent backing ({s.audible_percentage:.2f}% audible, no loud segments)"
|
||||
)
|
||||
return BackingResult(BackingVerdict.CLEAN, True, s, reasons)
|
||||
|
||||
# Audible backing exists. Without the 3-stem comparison the clean-vs-with
|
||||
# call stays a human judgement (pre-Phase-2B jobs, or comparison failed).
|
||||
if not s.comparison_present:
|
||||
reasons.append(
|
||||
f"audible backing present ({s.audible_percentage:.1f}%, {s.segment_count} segments, "
|
||||
f"{s.loud_segment_count} loud) but no 3-stem comparison available — "
|
||||
"retain-or-not needs a human listen"
|
||||
)
|
||||
return BackingResult(BackingVerdict.REVIEW, False, s, reasons)
|
||||
|
||||
# -- "pink but don't keep" mode 1: the backing stem IS the lead --
|
||||
# (separation misclassified a quiet/reverby lead; keeping it would put the
|
||||
# lead vocal back into the karaoke track — the worst possible output.)
|
||||
if (
|
||||
s.coverage_ratio >= BACKING_IS_LEAD_MIN_COVERAGE_RATIO
|
||||
and s.corr_backing_vocals >= BACKING_IS_LEAD_MIN_CORR
|
||||
and s.backing_audible_fraction > s.lead_audible_fraction
|
||||
):
|
||||
reasons.append(
|
||||
f"backing stem appears to BE the lead vocal: covers "
|
||||
f"{s.coverage_ratio:.0%} of the vocal line with envelope correlation "
|
||||
f"{s.corr_backing_vocals:.2f}, and is more present than the lead stem "
|
||||
f"({s.backing_audible_fraction:.0%} vs {s.lead_audible_fraction:.0%} "
|
||||
"audible) — keeping it would re-insert the lead; needs a human listen"
|
||||
)
|
||||
return BackingResult(BackingVerdict.REVIEW, False, s, reasons)
|
||||
|
||||
# -- mode 2: noise-floor pink (lo-fi/fuzzy mix) --
|
||||
if (
|
||||
s.backing_median_db is not None
|
||||
and s.backing_median_db <= NOISE_FLOOR_MAX_MEDIAN_DB
|
||||
and s.backing_audible_fraction >= NOISE_FLOOR_MIN_AUDIBLE_FRACTION
|
||||
and s.corr_backing_vocals <= NOISE_FLOOR_MAX_CORR
|
||||
):
|
||||
reasons.append(
|
||||
f"widespread near-threshold backing (median "
|
||||
f"{s.backing_median_db:.1f} dB over {s.backing_audible_fraction:.0%} "
|
||||
f"of the track) uncorrelated with the vocal line "
|
||||
f"({s.corr_backing_vocals:.2f}) — noise-floor signature; marginal "
|
||||
"either way, needs a human listen"
|
||||
)
|
||||
return BackingResult(BackingVerdict.REVIEW, False, s, reasons)
|
||||
|
||||
# -- mode 3: lead bleed (small blobs riding entirely on lead activity) --
|
||||
if (
|
||||
s.audible_percentage <= BLEED_MAX_AUDIBLE_PCT
|
||||
and s.lead_overlap_fraction >= BLEED_MIN_LEAD_OVERLAP
|
||||
):
|
||||
reasons.append(
|
||||
f"sparse backing ({s.audible_percentage:.1f}%) almost entirely "
|
||||
f"overlapping lead activity ({s.lead_overlap_fraction:.0%}) — "
|
||||
"likely lead bleed, not harmony; needs a human listen"
|
||||
)
|
||||
return BackingResult(BackingVerdict.REVIEW, False, s, reasons)
|
||||
|
||||
# Real pink harmony remains -> KEEP. Corpus: the human under-keeps (every
|
||||
# with_backing pick was right, 2 of 8 clean picks were wrong); with the
|
||||
# three don't-keep modes carved out above, retaining is the non-subjective
|
||||
# default ("retain backing vocals where possible").
|
||||
reasons.append(
|
||||
f"clear backing-vocal content present ({s.audible_percentage:.1f}%, "
|
||||
f"{s.segment_count} segments, {s.loud_segment_count} loud; flat fraction "
|
||||
f"{s.flat_fraction:.0%}, vocal-line coverage {s.coverage_ratio:.0%}) with "
|
||||
"no lead-bleed / misclassified-lead / noise signature — retain"
|
||||
)
|
||||
return BackingResult(BackingVerdict.WITH_BACKING, True, s, reasons)
|
||||
|
||||
|
||||
def score_job(
|
||||
correction_data: Dict[str, Any],
|
||||
backing_analysis: Optional[Dict[str, Any]],
|
||||
ai_suggestions: Optional[List[Dict[str, Any]]] = None,
|
||||
) -> AutoApprovabilityVerdict:
|
||||
"""Produce the combined shadow verdict for a job.
|
||||
|
||||
``overall_auto`` is the narrow safe intersection: confident lyrics AND a
|
||||
non-subjective (no-audible-backing) backing decision.
|
||||
"""
|
||||
lyrics = score_lyrics(correction_data, ai_suggestions)
|
||||
backing = score_backing(backing_analysis)
|
||||
overall_auto = lyrics.verdict == LyricsVerdict.AUTO and backing.non_subjective
|
||||
return AutoApprovabilityVerdict(
|
||||
lyrics=lyrics,
|
||||
backing=backing,
|
||||
overall_auto=overall_auto,
|
||||
scorer_version=SCORER_VERSION,
|
||||
)
|
||||
@@ -0,0 +1,369 @@
|
||||
"""Deterministic auto-correct suggestion generators (no LLM).
|
||||
|
||||
Mechanical residual-edit classes from the 2026-08 20-job replay-review corpus,
|
||||
emitted as ordinary suggestions so they flow through the exact same paths as
|
||||
the LLM ones: shown in the review UI, auto-applied on load, applied server-side
|
||||
by the auto-approval executor, counted by the scorer's gap-coverage signal, and
|
||||
cached alongside the LLM output.
|
||||
|
||||
Pattern 4 — leading-connective over-insertion: AudioShake is too eager to
|
||||
insert a short connective ("And", "Oh", …) at a segment start. When that word
|
||||
is a gap word (no confident reference match) and no reference source's reading
|
||||
of the gap supports it, emit a delete (+ re-capitalize the next word).
|
||||
|
||||
Pattern 5 — reference-majority resolution: when a gap's transcription contains
|
||||
an implausible proper noun (capitalized mid-line token absent from every
|
||||
reference source) and >=2/3 of the reference sources agree on the same reading
|
||||
for that gap, replace the gap with the majority reading. The red-flag token is
|
||||
REQUIRED, not just preferred: the corpus shows plain 2/3-majority gaps that the
|
||||
human deliberately left alone (Miguel 6d0640fa "though"->"dog" and an
|
||||
explicit-lyrics rewrite), while the one edit he did make ("yo Mick," ->
|
||||
"Come here,") had the proper-noun signature.
|
||||
|
||||
Everything here is pure and conservative: no evidence -> no suggestion.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import difflib
|
||||
import logging
|
||||
import re
|
||||
import uuid
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from backend.services.auto_approval.scorer import _is_vocalization_token
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Short connectives/interjections AudioShake over-inserts at segment starts —
|
||||
# exactly the set documented in the corpus (Pattern 4: And / But / So / Oh / A).
|
||||
# Deliberately NOT the near-misses like "ah"/"yeah": those double as
|
||||
# vocalization tokens, where deleting the leading word is a musical judgement.
|
||||
# The reference check below does the real gating; this list only scopes
|
||||
# which leading words are candidates.
|
||||
LEADING_CONNECTIVES = frozenset({"and", "but", "so", "oh", "a"})
|
||||
|
||||
# P4/P5 confidences: high enough to auto-apply, below full LLM consensus so a
|
||||
# conflicting multi-model AI suggestion wins its conflict group.
|
||||
P4_CONFIDENCE = 0.9
|
||||
P5_CONFIDENCE = 0.85
|
||||
|
||||
# P5 size guards: never rewrite long spans deterministically.
|
||||
P5_MAX_GAP_WORDS = 6
|
||||
P5_MAX_READING_WORDS = 8
|
||||
# A red-flag token this similar to some reference token is a spelling/
|
||||
# transliteration variant ("Crick"~"Cricket", "Projectorinsky"~
|
||||
# "Projektorinski"), not an implausible name. The right fix there is the
|
||||
# LLM's (it handles proper-noun spelling well); the gap alignment is also
|
||||
# often skewed in exactly these cases, so the majority "reading" is junk
|
||||
# (corpus 507513ba aligned gap "Crick" to reference "and").
|
||||
P5_SPELLING_VARIANT_RATIO = 0.75
|
||||
|
||||
_TOKEN_NORM_RE = re.compile(r"^[^\w]+|[^\w]+$")
|
||||
|
||||
|
||||
def _norm(text: str) -> str:
|
||||
return _TOKEN_NORM_RE.sub("", (text or "").lower())
|
||||
|
||||
|
||||
def _norm_join(texts: List[str]) -> str:
|
||||
return " ".join(t for t in (_norm(x) for x in texts) if t)
|
||||
|
||||
|
||||
def _ref_word_streams(
|
||||
reference_lyrics: Dict[str, Any],
|
||||
) -> Dict[str, Tuple[List[str], Dict[str, int]]]:
|
||||
"""Per source: (ordered word texts, word_id -> position)."""
|
||||
streams: Dict[str, Tuple[List[str], Dict[str, int]]] = {}
|
||||
for source, ref in (reference_lyrics or {}).items():
|
||||
texts: List[str] = []
|
||||
index: Dict[str, int] = {}
|
||||
for seg in ref.get("segments") or []:
|
||||
for w in seg.get("words") or []:
|
||||
wid = w.get("id")
|
||||
if wid:
|
||||
index[wid] = len(texts)
|
||||
texts.append(w.get("text") or "")
|
||||
streams[source] = (texts, index)
|
||||
return streams
|
||||
|
||||
|
||||
def _gap_readings(
|
||||
gap: Dict[str, Any],
|
||||
anchors_by_id: Dict[str, Dict[str, Any]],
|
||||
streams: Dict[str, Tuple[List[str], Dict[str, int]]],
|
||||
) -> Dict[str, List[str]]:
|
||||
"""Each source's reading of the gap (raw word texts).
|
||||
|
||||
Prefer the gap's own per-source alignment. When a source aligned neither
|
||||
gap word (empty list — common), derive the reading from the reference
|
||||
stream around the surrounding anchors: the words strictly between the
|
||||
anchors when both aligned for that source, else the same-count window
|
||||
after the preceding (or before the following) anchor. A source with no
|
||||
usable anchor alignment contributes no reading.
|
||||
"""
|
||||
n = len(gap.get("transcribed_word_ids") or [])
|
||||
pre = anchors_by_id.get(gap.get("preceding_anchor_id") or "")
|
||||
fol = anchors_by_id.get(gap.get("following_anchor_id") or "")
|
||||
readings: Dict[str, List[str]] = {}
|
||||
for source, (texts, index) in streams.items():
|
||||
aligned_ids = (gap.get("reference_word_ids") or {}).get(source) or []
|
||||
aligned = [texts[index[i]] for i in aligned_ids if i in index]
|
||||
if aligned:
|
||||
readings[source] = aligned
|
||||
continue
|
||||
pre_ids = ((pre or {}).get("reference_word_ids") or {}).get(source) or []
|
||||
fol_ids = ((fol or {}).get("reference_word_ids") or {}).get(source) or []
|
||||
lo = index[pre_ids[-1]] + 1 if pre_ids and pre_ids[-1] in index else None
|
||||
hi = index[fol_ids[0]] if fol_ids and fol_ids[0] in index else None
|
||||
if lo is not None and hi is not None:
|
||||
if lo <= hi <= lo + n + 4:
|
||||
readings[source] = texts[lo:hi]
|
||||
elif lo is not None:
|
||||
readings[source] = texts[lo : lo + n]
|
||||
elif hi is not None:
|
||||
readings[source] = texts[max(0, hi - n) : hi]
|
||||
return readings
|
||||
|
||||
|
||||
def _word_maps(
|
||||
segments: List[Dict[str, Any]],
|
||||
) -> Tuple[Dict[str, Dict[str, Any]], Dict[str, str]]:
|
||||
"""(word_id -> word dict, word_id -> segment_id) from the CURRENT segments."""
|
||||
words: Dict[str, Dict[str, Any]] = {}
|
||||
seg_of: Dict[str, str] = {}
|
||||
for seg in segments or []:
|
||||
for w in seg.get("words") or []:
|
||||
wid = w.get("id")
|
||||
if wid:
|
||||
words[wid] = w
|
||||
seg_of[wid] = seg.get("id") or ""
|
||||
return words, seg_of
|
||||
|
||||
|
||||
def _make_suggestion(
|
||||
*,
|
||||
op: str,
|
||||
word_ids: List[str],
|
||||
segment_ids: List[str],
|
||||
original_text: str,
|
||||
new_text: str,
|
||||
reason: str,
|
||||
category: str,
|
||||
confidence: float,
|
||||
) -> Dict[str, Any]:
|
||||
"""A suggestion dict shaped exactly like the LLM ones after validation."""
|
||||
return {
|
||||
"id": str(uuid.uuid4()),
|
||||
"op": op,
|
||||
"word_ids": word_ids,
|
||||
"segment_ids": segment_ids,
|
||||
"original_text": original_text,
|
||||
"new_text": new_text,
|
||||
"reason": reason,
|
||||
"category": category,
|
||||
"confidence": confidence,
|
||||
"models": ["deterministic"],
|
||||
"consensus": 1,
|
||||
"total_models": 1,
|
||||
"conflict_group": None,
|
||||
}
|
||||
|
||||
|
||||
def _capitalize(text: str) -> str:
|
||||
for i, ch in enumerate(text):
|
||||
if ch.isalpha():
|
||||
return text[:i] + ch.upper() + text[i + 1 :]
|
||||
return text
|
||||
|
||||
|
||||
def leading_connective_suggestions(
|
||||
segments: List[Dict[str, Any]],
|
||||
correction_data: Dict[str, Any],
|
||||
streams: Dict[str, Tuple[List[str], Dict[str, int]]],
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""Pattern 4: delete an unsupported leading connective, re-capitalize next word."""
|
||||
gaps = correction_data.get("gap_sequences") or []
|
||||
anchors_by_id = {
|
||||
a.get("id"): a for a in correction_data.get("anchor_sequences") or [] if a.get("id")
|
||||
}
|
||||
gap_of_word: Dict[str, Dict[str, Any]] = {}
|
||||
for gap in gaps:
|
||||
for wid in gap.get("transcribed_word_ids") or []:
|
||||
gap_of_word[wid] = gap
|
||||
|
||||
out: List[Dict[str, Any]] = []
|
||||
for seg in segments or []:
|
||||
words = seg.get("words") or []
|
||||
if len(words) < 3:
|
||||
continue
|
||||
first = words[0]
|
||||
wid = first.get("id")
|
||||
token = _norm(first.get("text") or "")
|
||||
if not wid or token not in LEADING_CONNECTIVES:
|
||||
continue
|
||||
gap = gap_of_word.get(wid)
|
||||
if gap is None:
|
||||
# A confidently reference-anchored leading word is legitimate.
|
||||
continue
|
||||
if _is_vocalization_token(words[1].get("text") or ""):
|
||||
# "Oh- whoa, ..." — a vocalization run, not an over-inserted
|
||||
# connective before a sentence; grouping there is musical judgement.
|
||||
continue
|
||||
readings = _gap_readings(gap, anchors_by_id, streams)
|
||||
if not readings:
|
||||
continue # no reference evidence either way -> leave it alone
|
||||
if any(token in {_norm(t) for t in reading} for reading in readings.values()):
|
||||
continue # some source supports the connective at this position
|
||||
seg_id = seg.get("id") or ""
|
||||
out.append(
|
||||
_make_suggestion(
|
||||
op="delete",
|
||||
word_ids=[wid],
|
||||
segment_ids=[seg_id],
|
||||
original_text=first.get("text") or "",
|
||||
new_text="",
|
||||
reason=(
|
||||
f'Removed leading "{first.get("text", "").strip()}" — the '
|
||||
"transcription inserted it at the line start but no reference "
|
||||
"source has it at this position"
|
||||
),
|
||||
category="mishearing",
|
||||
confidence=P4_CONFIDENCE,
|
||||
)
|
||||
)
|
||||
nxt = words[1]
|
||||
nxt_text = nxt.get("text") or ""
|
||||
capitalized = _capitalize(nxt_text)
|
||||
if nxt.get("id") and capitalized != nxt_text:
|
||||
out.append(
|
||||
_make_suggestion(
|
||||
op="replace",
|
||||
word_ids=[nxt.get("id")],
|
||||
segment_ids=[seg_id],
|
||||
original_text=nxt_text,
|
||||
new_text=capitalized,
|
||||
reason="Capitalized the new first word of the line",
|
||||
category="formatting",
|
||||
confidence=P4_CONFIDENCE,
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def _majority_reading(
|
||||
readings: Dict[str, List[str]], total_sources: int
|
||||
) -> Optional[List[str]]:
|
||||
"""The reading >=2/3 of ALL sources agree on (>=2 absolute), else None."""
|
||||
votes: Dict[str, List[List[str]]] = {}
|
||||
for reading in readings.values():
|
||||
if reading:
|
||||
votes.setdefault(_norm_join(reading), []).append(reading)
|
||||
if not votes:
|
||||
return None
|
||||
key, group = max(votes.items(), key=lambda kv: len(kv[1]))
|
||||
if not key or len(group) < 2 or len(group) * 3 < total_sources * 2:
|
||||
return None
|
||||
return group[0]
|
||||
|
||||
|
||||
def reference_majority_suggestions(
|
||||
segments: List[Dict[str, Any]],
|
||||
correction_data: Dict[str, Any],
|
||||
streams: Dict[str, Tuple[List[str], Dict[str, int]]],
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""Pattern 5: replace an implausible-proper-noun gap with the >=2/3 majority reading."""
|
||||
words_by_id, seg_of = _word_maps(segments)
|
||||
anchors_by_id = {
|
||||
a.get("id"): a for a in correction_data.get("anchor_sequences") or [] if a.get("id")
|
||||
}
|
||||
all_ref_tokens = {
|
||||
_norm(t) for texts, _ in streams.values() for t in texts if _norm(t)
|
||||
}
|
||||
seg_first_word_ids = {
|
||||
(seg.get("words") or [{}])[0].get("id") for seg in segments or []
|
||||
}
|
||||
total_sources = len(streams)
|
||||
|
||||
out: List[Dict[str, Any]] = []
|
||||
for gap in correction_data.get("gap_sequences") or []:
|
||||
gap_ids = gap.get("transcribed_word_ids") or []
|
||||
if not gap_ids or len(gap_ids) > P5_MAX_GAP_WORDS:
|
||||
continue
|
||||
gap_words = [words_by_id.get(i) for i in gap_ids]
|
||||
if any(w is None for w in gap_words):
|
||||
continue # a gap word no longer exists in the working segments
|
||||
# Red flag (REQUIRED): a capitalized mid-line token no reference knows.
|
||||
# A token merely SIMILAR to a reference token is a spelling variant,
|
||||
# not an implausible name — that's the LLM's fix, not ours.
|
||||
red_flag = None
|
||||
for wid, w in zip(gap_ids, gap_words):
|
||||
text = (w.get("text") or "").strip()
|
||||
norm = _norm(text)
|
||||
if not (
|
||||
text
|
||||
and text[0].isupper()
|
||||
and wid not in seg_first_word_ids
|
||||
and norm
|
||||
and norm not in all_ref_tokens
|
||||
):
|
||||
continue
|
||||
if any(
|
||||
difflib.SequenceMatcher(None, norm, ref).ratio()
|
||||
>= P5_SPELLING_VARIANT_RATIO
|
||||
for ref in all_ref_tokens
|
||||
):
|
||||
continue
|
||||
red_flag = text
|
||||
break
|
||||
if red_flag is None:
|
||||
continue
|
||||
readings = _gap_readings(gap, anchors_by_id, streams)
|
||||
majority = _majority_reading(readings, total_sources)
|
||||
if majority is None or len(majority) > P5_MAX_READING_WORDS:
|
||||
continue
|
||||
original = [w.get("text") or "" for w in gap_words]
|
||||
if _norm_join(majority) == _norm_join(original):
|
||||
continue
|
||||
segment_ids = sorted({seg_of.get(i, "") for i in gap_ids})
|
||||
out.append(
|
||||
_make_suggestion(
|
||||
op="replace",
|
||||
word_ids=list(gap_ids),
|
||||
segment_ids=segment_ids,
|
||||
original_text=" ".join(original),
|
||||
new_text=" ".join(majority).strip(),
|
||||
reason=(
|
||||
f'Transcription "{" ".join(original)}" contains "{red_flag}", '
|
||||
"which no reference source has; the majority of reference "
|
||||
f'sources read this as "{" ".join(majority).strip()}"'
|
||||
),
|
||||
category="mishearing",
|
||||
confidence=P5_CONFIDENCE,
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def deterministic_suggestions(
|
||||
segments: List[Dict[str, Any]],
|
||||
reference_lyrics: Dict[str, Any],
|
||||
correction_data: Optional[Dict[str, Any]],
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""All deterministic suggestions for the current working segments.
|
||||
|
||||
Needs the job's ``corrections.json`` dict for gap/anchor alignment; with
|
||||
none available (or on any internal error) it returns [] — deterministic
|
||||
fixes are an enhancement, never a failure mode.
|
||||
"""
|
||||
if not correction_data or not reference_lyrics:
|
||||
return []
|
||||
try:
|
||||
streams = _ref_word_streams(reference_lyrics)
|
||||
if not streams:
|
||||
return []
|
||||
return leading_connective_suggestions(
|
||||
segments, correction_data, streams
|
||||
) + reference_majority_suggestions(segments, correction_data, streams)
|
||||
except Exception:
|
||||
logger.warning("deterministic suggestion generation failed", exc_info=True)
|
||||
return []
|
||||
@@ -5,6 +5,7 @@ import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import asdict, dataclass, field
|
||||
@@ -14,6 +15,7 @@ from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.auto_correct.deterministic import deterministic_suggestions
|
||||
from backend.services.auto_correct.pricing import TokenUsage, estimate_cost_usd
|
||||
from backend.services.auto_correct.prompts import (
|
||||
RESPONSE_SCHEMA,
|
||||
@@ -127,6 +129,84 @@ class AutoCorrectResult:
|
||||
cached: bool = False
|
||||
|
||||
|
||||
_NORM_TOKEN_RE = re.compile(r"^[^\w]+|[^\w]+$")
|
||||
|
||||
|
||||
def _norm_tokens(text: str) -> set:
|
||||
return {t for t in (_NORM_TOKEN_RE.sub("", w.lower()) for w in (text or "").split()) if t}
|
||||
|
||||
|
||||
def _assign_conflict_groups(result: list[Suggestion]) -> None:
|
||||
"""(Re)compute conflict groups over a suggestion list, in place.
|
||||
|
||||
Two rules union suggestions into a pick-at-most-one group:
|
||||
- Non-insert suggestions sharing any target word disagree about that span.
|
||||
- An ``insert_after`` whose inserted token(s) also appear in another
|
||||
suggestion's new_text targeting (or anchored on) the same word is the P1
|
||||
self-conflict signature — two overlapping suggestions both adding the
|
||||
same token (corpus f6439692: ``insert_after "fire" -> "you're"`` plus
|
||||
``replace "fire" -> "fire, you're"`` produced "you're you're"). Grouping
|
||||
them lets accept-all pick one winner instead of double-applying.
|
||||
A plain insert next to an edit with disjoint tokens stays independent.
|
||||
"""
|
||||
for s in result:
|
||||
s.conflict_group = None
|
||||
|
||||
parent = list(range(len(result)))
|
||||
|
||||
def find(x: int) -> int:
|
||||
while parent[x] != x:
|
||||
parent[x] = parent[parent[x]]
|
||||
x = parent[x]
|
||||
return x
|
||||
|
||||
def union(a: int, b: int) -> None:
|
||||
parent[find(b)] = find(a)
|
||||
|
||||
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)
|
||||
for overlapping in by_word.values():
|
||||
for other in overlapping[1:]:
|
||||
union(overlapping[0], other)
|
||||
|
||||
for i, s in enumerate(result):
|
||||
if s.op != "insert_after" or not s.word_ids:
|
||||
continue
|
||||
anchor = s.word_ids[0]
|
||||
tokens = _norm_tokens(s.new_text)
|
||||
if not tokens:
|
||||
continue
|
||||
for j, r in enumerate(result):
|
||||
if j == i:
|
||||
continue
|
||||
anchored = (
|
||||
anchor in r.word_ids
|
||||
if r.op != "insert_after"
|
||||
else bool(r.word_ids) and r.word_ids[0] == anchor
|
||||
)
|
||||
if anchored and tokens & _norm_tokens(r.new_text):
|
||||
union(i, j)
|
||||
|
||||
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
|
||||
|
||||
|
||||
def _sort_by_position(result: list[Suggestion], flat: list[tuple[str, str, str]]) -> None:
|
||||
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)
|
||||
|
||||
|
||||
class AutoCorrectService:
|
||||
def __init__(self) -> None:
|
||||
self.settings = get_settings()
|
||||
@@ -140,6 +220,7 @@ class AutoCorrectService:
|
||||
artist: Optional[str],
|
||||
title: Optional[str],
|
||||
settings: AutoCorrectSettings,
|
||||
correction_data: Optional[dict] = None,
|
||||
) -> AutoCorrectResult:
|
||||
if not segments:
|
||||
raise AutoCorrectServiceError("segments is empty")
|
||||
@@ -227,6 +308,9 @@ class AutoCorrectService:
|
||||
)
|
||||
|
||||
merged = self._merge(per_model, flat)
|
||||
merged = self._add_deterministic(
|
||||
merged, job_id, segments, reference_lyrics, correction_data, settings, flat
|
||||
)
|
||||
elapsed = time.time() - t0
|
||||
model_label = ", ".join(per_model.keys())
|
||||
logger.info(
|
||||
@@ -307,8 +391,10 @@ class AutoCorrectService:
|
||||
artist: Optional[str],
|
||||
title: Optional[str],
|
||||
) -> str:
|
||||
# v2: deterministic suggestions (P4/P1/P5 fixers) joined the pipeline —
|
||||
# older cached results predate them, so they must not be served.
|
||||
payload = {
|
||||
"v": 1,
|
||||
"v": 2,
|
||||
"models": models,
|
||||
"settings": settings.to_dict(),
|
||||
"words": [[word_id, text] for word_id, text, _seg in flat],
|
||||
@@ -402,42 +488,78 @@ class AutoCorrectService:
|
||||
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)
|
||||
_assign_conflict_groups(result)
|
||||
_sort_by_position(result, flat)
|
||||
return result
|
||||
|
||||
def _add_deterministic(
|
||||
self,
|
||||
merged: list[Suggestion],
|
||||
job_id: str,
|
||||
segments: list[dict],
|
||||
reference_lyrics: dict[str, dict],
|
||||
correction_data: Optional[dict],
|
||||
settings: AutoCorrectSettings,
|
||||
flat: list[tuple[str, str, str]],
|
||||
) -> list[Suggestion]:
|
||||
"""Fold the deterministic (P4/P5) suggestions into the LLM set.
|
||||
|
||||
A deterministic suggestion identical to an LLM one just tags the
|
||||
existing suggestion; new ones are appended. Conflict groups are then
|
||||
recomputed over the combined set so a deterministic fix that disagrees
|
||||
with an LLM suggestion becomes a pick-one conflict, not a double-apply.
|
||||
"""
|
||||
if correction_data is None:
|
||||
# The proactive worker passes corrections.json in; the review-UI
|
||||
# route doesn't have it, so fetch it (best-effort) — it holds the
|
||||
# gap/anchor alignment the generators key off.
|
||||
try:
|
||||
path = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
storage = self._get_storage()
|
||||
if storage.bucket.blob(path).exists():
|
||||
correction_data = storage.download_json(path)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"auto-correct: corrections.json unavailable for %s; "
|
||||
"skipping deterministic suggestions", job_id, exc_info=True,
|
||||
)
|
||||
raw = deterministic_suggestions(segments, reference_lyrics, correction_data)
|
||||
deterministic = [
|
||||
Suggestion(**s)
|
||||
for s in raw
|
||||
if float(s.get("confidence", 0.0)) >= settings.min_confidence
|
||||
]
|
||||
if not deterministic:
|
||||
return merged
|
||||
|
||||
by_key = {
|
||||
(s.op, tuple(s.word_ids), " ".join(s.new_text.lower().split())): s
|
||||
for s in merged
|
||||
}
|
||||
added = 0
|
||||
for s in deterministic:
|
||||
key = (s.op, tuple(s.word_ids), " ".join(s.new_text.lower().split()))
|
||||
existing = by_key.get(key)
|
||||
if existing is not None:
|
||||
# The deterministic generator counts as an agreeing source:
|
||||
# keeps the consensus == len(models) invariant, and lets an
|
||||
# LLM+deterministic agreement outrank a conflicting
|
||||
# single-model suggestion in winner selection.
|
||||
existing.models.append("deterministic")
|
||||
existing.consensus += 1
|
||||
existing.total_models += 1
|
||||
existing.confidence = max(existing.confidence, s.confidence)
|
||||
continue
|
||||
merged.append(s)
|
||||
added += 1
|
||||
logger.info(
|
||||
"auto-correct deterministic job=%s generated=%d added=%d",
|
||||
job_id, len(deterministic), added,
|
||||
)
|
||||
_assign_conflict_groups(merged)
|
||||
_sort_by_position(merged, flat)
|
||||
return merged
|
||||
|
||||
# ---- internals ----
|
||||
|
||||
def _call_model(
|
||||
|
||||
@@ -101,6 +101,10 @@ class JobManager:
|
||||
youtube_description_template=job_create.youtube_description_template, # video_worker reads this
|
||||
webhook_url=job_create.webhook_url,
|
||||
user_email=job_create.user_email,
|
||||
# Review autonomy ("auto" = skip review screens when confident)
|
||||
review_mode=job_create.review_mode,
|
||||
# Backing-vocals preference ("auto"=retain-where-safe | clean | review)
|
||||
backing_preference=job_create.backing_preference,
|
||||
# Distribution settings
|
||||
brand_prefix=job_create.brand_prefix,
|
||||
discord_webhook_url=job_create.discord_webhook_url,
|
||||
|
||||
@@ -14,6 +14,7 @@ Scoped to public Nomad Karaoke masters only (brand prefix ``NOMAD``, excluding t
|
||||
here must never break the distribution pipeline — the nightly VM remains the safety net.
|
||||
"""
|
||||
import logging
|
||||
import re
|
||||
from typing import Optional
|
||||
|
||||
from google.cloud import storage
|
||||
@@ -23,6 +24,17 @@ from backend.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# A single-track filename prefix must be a full public brand code PLUS at least part
|
||||
# of the artist name ("NOMAD-#### - X..."). Stricter than the by-brand deletes: when a
|
||||
# recycled brand code is shared by two tracks (orphaned files), this lets cleanup
|
||||
# target exactly one of them without touching the other.
|
||||
_TRACK_FILENAME_PREFIX_RE = re.compile(r"^NOMAD-\d{4,} - \S.*")
|
||||
|
||||
|
||||
def is_safe_track_filename_prefix(filename_prefix: Optional[str]) -> bool:
|
||||
"""True if the prefix is specific enough for a single-track mirror delete."""
|
||||
return bool(_TRACK_FILENAME_PREFIX_RE.match(filename_prefix or ""))
|
||||
|
||||
|
||||
def is_nomad_public_brand(brand_code: Optional[str]) -> bool:
|
||||
"""True only for public Nomad releases (``NOMAD-####``), not ``NOMADNP`` privates."""
|
||||
@@ -162,6 +174,53 @@ class NomadMasterMirror:
|
||||
return deleted
|
||||
|
||||
|
||||
def delete_track_objects_by_filename_prefix(self, filename_prefix: str) -> dict:
|
||||
"""Delete mirror objects (720p masters + original-vocals guides) whose filename
|
||||
starts with ``filename_prefix`` — e.g. ``"NOMAD-1583 - Mazzy Star"``.
|
||||
|
||||
Used by orphaned-output cleanup when the owning job doc is gone and a recycled
|
||||
brand code is shared with a live track: the prefix must include artist text
|
||||
(enforced by ``_TRACK_FILENAME_PREFIX_RE``) so only the orphaned track's
|
||||
objects match, never the whole brand code. Matching is delimiter-bounded — the
|
||||
character after the prefix must be a space or ``.`` — so ``"NOMAD-1583 - Mazzy
|
||||
Star"`` can never match a different track named ``"NOMAD-1583 - Mazzy Starlight
|
||||
- ..."``. Raises ``ValueError`` for an unsafe prefix (callers validate with
|
||||
``is_safe_track_filename_prefix``); GCS errors stay best-effort.
|
||||
"""
|
||||
if not is_safe_track_filename_prefix(filename_prefix):
|
||||
raise ValueError(
|
||||
f"Unsafe mirror track prefix {filename_prefix!r} "
|
||||
f"(must look like 'NOMAD-#### - Artist...')"
|
||||
)
|
||||
|
||||
counts = {"masters_deleted": 0, "vocals_guides_deleted": 0}
|
||||
targets = [
|
||||
("masters_deleted", settings.nomad_master_gcs_prefix.strip("/")),
|
||||
("vocals_guides_deleted", settings.nomad_vocals_guide_gcs_prefix.strip("/")),
|
||||
]
|
||||
for key, gcs_prefix in targets:
|
||||
prefix = f"{gcs_prefix}/{filename_prefix}"
|
||||
try:
|
||||
for blob in self._bucket.list_blobs(prefix=prefix):
|
||||
remainder = blob.name[len(prefix):]
|
||||
if remainder and remainder[0] not in " .":
|
||||
# Prefix ends mid-word (a longer artist/title shares it) —
|
||||
# this object belongs to a different track.
|
||||
continue
|
||||
try:
|
||||
blob.delete()
|
||||
counts[key] += 1
|
||||
logger.info(
|
||||
"Removed orphaned mirror object gs://%s/%s",
|
||||
settings.divebar_files_bucket, blob.name,
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("Failed to delete mirror object %s: %s", blob.name, e)
|
||||
except Exception as e: # noqa: BLE001 - never fatal to the caller
|
||||
logger.warning("Mirror track prefix-delete failed for %s: %s", prefix, e)
|
||||
return counts
|
||||
|
||||
|
||||
def cleanup_nomad_masters(brand_code: Optional[str]) -> int:
|
||||
"""Best-effort removal of a Nomad release's 720p master(s) from the GCS mirror,
|
||||
keyed by brand_code prefix (covers renames). No-op for non-Nomad / ``NOMADNP``
|
||||
|
||||
@@ -288,14 +288,28 @@ class StorageService:
|
||||
logger.error(f"Error checking file existence {blob_path}: {e}")
|
||||
raise
|
||||
|
||||
def upload_json(self, destination_path: str, data: Dict[str, Any]) -> str:
|
||||
"""Upload a JSON object to GCS."""
|
||||
def upload_json(
|
||||
self,
|
||||
destination_path: str,
|
||||
data: Dict[str, Any],
|
||||
if_generation_match: Optional[int] = None,
|
||||
) -> str:
|
||||
"""Upload a JSON object to GCS.
|
||||
|
||||
``if_generation_match=0`` makes the write a create-only operation: GCS raises
|
||||
``PreconditionFailed`` (412) if the object already exists, so concurrent
|
||||
writers can't clobber each other. Callers that need this must handle the
|
||||
exception.
|
||||
"""
|
||||
try:
|
||||
blob = self.bucket.blob(destination_path)
|
||||
blob.content_type = "application/json"
|
||||
upload_kwargs = {"content_type": "application/json"}
|
||||
if if_generation_match is not None:
|
||||
upload_kwargs["if_generation_match"] = if_generation_match
|
||||
blob.upload_from_string(
|
||||
json.dumps(data, indent=2, ensure_ascii=False),
|
||||
content_type="application/json"
|
||||
**upload_kwargs,
|
||||
)
|
||||
logger.info(f"Uploaded JSON to gs://{settings.gcs_bucket_name}/{destination_path}")
|
||||
return destination_path
|
||||
|
||||
@@ -249,7 +249,7 @@ class WorkerService:
|
||||
logger.error("GOOGLE_CLOUD_PROJECT not set, cannot enqueue Cloud Task")
|
||||
return False
|
||||
|
||||
location = self.settings.gcp_region # Must match queue location
|
||||
location = self.settings.cloud_tasks_region # queues all live here, NOT gcp_region
|
||||
|
||||
# Build queue path
|
||||
parent = self.tasks_client.queue_path(project, location, queue_name)
|
||||
@@ -754,7 +754,7 @@ class WorkerService:
|
||||
logger.error("GOOGLE_CLOUD_PROJECT not set")
|
||||
return False
|
||||
|
||||
location = self.settings.gcp_region
|
||||
location = self.settings.cloud_tasks_region # queues all live here, NOT gcp_region
|
||||
|
||||
# Build queue path
|
||||
parent = self.tasks_client.queue_path(project, location, queue_name)
|
||||
@@ -843,7 +843,7 @@ class WorkerService:
|
||||
logger.error("GOOGLE_CLOUD_PROJECT not set")
|
||||
return False
|
||||
|
||||
location = self.settings.gcp_region
|
||||
location = self.settings.cloud_tasks_region # queues all live here, NOT gcp_region
|
||||
|
||||
# Build queue path
|
||||
parent = self.tasks_client.queue_path(project, location, queue_name)
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,183 @@
|
||||
"""Tests for the server-side AI-suggestion apply engine.
|
||||
|
||||
This is a port of the review UI's auto-apply (autoCorrectApply.ts /
|
||||
autoCorrectConflicts.ts); these tests pin the port to the frontend's observable
|
||||
behaviour: op semantics, timing distribution, word flags, conflict resolution.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from backend.services.auto_approval.apply import (
|
||||
apply_all_suggestions,
|
||||
apply_suggestion,
|
||||
find_suspicious_duplicates,
|
||||
is_suggestion_stale,
|
||||
pick_accept_all_winners,
|
||||
)
|
||||
|
||||
|
||||
def _word(wid: str, text: str, start: float, end: float) -> Dict[str, Any]:
|
||||
return {"id": wid, "text": text, "start_time": start, "end_time": end, "confidence": 0.9}
|
||||
|
||||
|
||||
def _segments() -> List[Dict[str, Any]]:
|
||||
return [
|
||||
{
|
||||
"id": "s0",
|
||||
"text": "I am a fire",
|
||||
"words": [
|
||||
_word("w0", "I", 0.0, 0.3),
|
||||
_word("w1", "am", 0.3, 0.6),
|
||||
_word("w2", "a", 0.6, 0.9),
|
||||
_word("w3", "fire", 0.9, 1.5),
|
||||
],
|
||||
"start_time": 0.0,
|
||||
"end_time": 1.5,
|
||||
},
|
||||
{
|
||||
"id": "s1",
|
||||
"text": "gasoline",
|
||||
"words": [_word("w4", "gasoline", 2.0, 2.8)],
|
||||
"start_time": 2.0,
|
||||
"end_time": 2.8,
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def _sug(op: str, word_ids: List[str], new_text: str = "", **kw: Any) -> Dict[str, Any]:
|
||||
return {
|
||||
"id": kw.pop("id", "sug1"),
|
||||
"op": op,
|
||||
"word_ids": word_ids,
|
||||
"segment_ids": ["s0"],
|
||||
"original_text": kw.pop("original_text", ""),
|
||||
"new_text": new_text,
|
||||
"confidence": kw.pop("confidence", 0.9),
|
||||
"consensus": kw.pop("consensus", 2),
|
||||
"total_models": kw.pop("total_models", 2),
|
||||
"conflict_group": kw.pop("conflict_group", None),
|
||||
}
|
||||
|
||||
|
||||
# --- replace ---
|
||||
|
||||
def test_replace_single_word_inherits_timing_and_flags() -> None:
|
||||
result = apply_suggestion(_segments(), _sug("replace", ["w1"], "was", original_text="am"))
|
||||
assert result is not None
|
||||
words = result[0]["words"]
|
||||
assert [w["text"] for w in words] == ["I", "was", "a", "fire"]
|
||||
new = words[1]
|
||||
assert new["start_time"] == 0.3 and new["end_time"] == 0.6
|
||||
assert new["ai_corrected"] is True
|
||||
assert new["created_during_correction"] is True
|
||||
assert new["timing_estimated"] is False # single word inherits a real range
|
||||
assert new["original_text"] == "am"
|
||||
assert result[0]["text"] == "I was a fire"
|
||||
|
||||
|
||||
def test_replace_multi_word_splits_timing_and_marks_estimated() -> None:
|
||||
result = apply_suggestion(_segments(), _sug("replace", ["w3"], "fire, you're"))
|
||||
assert result is not None
|
||||
words = result[0]["words"]
|
||||
assert [w["text"] for w in words] == ["I", "am", "a", "fire,", "you're"]
|
||||
a, b = words[3], words[4]
|
||||
assert a["start_time"] == 0.9 and abs(a["end_time"] - 1.2) < 1e-9
|
||||
assert abs(b["start_time"] - 1.2) < 1e-9 and b["end_time"] == 1.5
|
||||
assert a["timing_estimated"] is True and b["timing_estimated"] is True
|
||||
assert "original_text" in a and "original_text" not in b
|
||||
|
||||
|
||||
# --- insert_after ---
|
||||
|
||||
def test_insert_after_uses_gap_to_next_word() -> None:
|
||||
result = apply_suggestion(_segments(), _sug("insert_after", ["w3"], "burning"))
|
||||
assert result is not None
|
||||
words = result[0]["words"]
|
||||
assert [w["text"] for w in words] == ["I", "am", "a", "fire", "burning"]
|
||||
new = words[4]
|
||||
assert new["start_time"] == 1.5 # anchor end
|
||||
assert new["timing_estimated"] is True
|
||||
|
||||
|
||||
# --- delete ---
|
||||
|
||||
def test_delete_word_updates_segment_text_and_timing() -> None:
|
||||
result = apply_suggestion(_segments(), _sug("delete", ["w0"]))
|
||||
assert result is not None
|
||||
seg = result[0]
|
||||
assert seg["text"] == "am a fire"
|
||||
assert seg["start_time"] == 0.3
|
||||
|
||||
|
||||
def test_delete_last_word_removes_segment() -> None:
|
||||
result = apply_suggestion(_segments(), _sug("delete", ["w4"]))
|
||||
assert result is not None
|
||||
assert len(result) == 1
|
||||
assert result[0]["id"] == "s0"
|
||||
|
||||
|
||||
# --- staleness ---
|
||||
|
||||
def test_missing_word_is_stale() -> None:
|
||||
assert is_suggestion_stale(_segments(), _sug("replace", ["nope"], "x"))
|
||||
assert apply_suggestion(_segments(), _sug("replace", ["nope"], "x")) is None
|
||||
|
||||
|
||||
def test_non_contiguous_words_are_stale() -> None:
|
||||
assert is_suggestion_stale(_segments(), _sug("replace", ["w0", "w2"], "x"))
|
||||
|
||||
|
||||
def test_empty_word_ids_is_stale_not_crash() -> None:
|
||||
# all([]) is vacuously True — a cached suggestion with missing/empty
|
||||
# word_ids must be treated as stale, not crash min() on an empty list.
|
||||
assert is_suggestion_stale(_segments(), _sug("replace", [], "x"))
|
||||
assert apply_suggestion(_segments(), _sug("replace", [], "x")) is None
|
||||
|
||||
|
||||
# --- conflict groups / accept-all ---
|
||||
|
||||
def test_conflict_group_winner_by_consensus_then_confidence() -> None:
|
||||
s1 = _sug("replace", ["w1"], "was", id="a", conflict_group="g1", consensus=1, confidence=0.95)
|
||||
s2 = _sug("replace", ["w1"], "is", id="b", conflict_group="g1", consensus=2, confidence=0.7)
|
||||
s3 = _sug("replace", ["w0"], "You", id="c")
|
||||
assert pick_accept_all_winners([s1, s2, s3]) == ["b", "c"]
|
||||
|
||||
|
||||
def test_apply_all_resolves_conflicts_and_reports() -> None:
|
||||
s1 = _sug("replace", ["w1"], "was", id="a", conflict_group="g1", consensus=1)
|
||||
s2 = _sug("replace", ["w1"], "is", id="b", conflict_group="g1", consensus=2)
|
||||
out = apply_all_suggestions(_segments(), [s1, s2])
|
||||
assert out["applied_ids"] == ["b"]
|
||||
assert out["rejected_ids"] == ["a"]
|
||||
assert out["stale_ids"] == []
|
||||
assert [w["text"] for w in out["segments"][0]["words"]] == ["I", "is", "a", "fire"]
|
||||
|
||||
|
||||
def test_apply_all_flags_stale() -> None:
|
||||
out = apply_all_suggestions(_segments(), [_sug("replace", ["gone"], "x", id="a")])
|
||||
assert out["stale_ids"] == ["a"]
|
||||
assert out["applied_ids"] == []
|
||||
|
||||
|
||||
def test_p1_self_conflict_produces_detectable_duplicate() -> None:
|
||||
# Corpus f6439692: overlapping suggestions (conflict_group=null) both add
|
||||
# "you're" -> "fire, you're you're gasoline". The apply engine mirrors the
|
||||
# UI (both apply); find_suspicious_duplicates must catch the result.
|
||||
s1 = _sug("insert_after", ["w3"], "you're", id="a")
|
||||
s2 = _sug("replace", ["w3"], "fire, you're", id="b")
|
||||
out = apply_all_suggestions(_segments(), [s1, s2])
|
||||
dups = find_suspicious_duplicates(out["segments"], {})
|
||||
assert "you're" in dups
|
||||
|
||||
|
||||
def test_duplicates_supported_by_reference_are_ok() -> None:
|
||||
segments = [{
|
||||
"id": "s0", "text": "hey hey you",
|
||||
"words": [_word("w0", "hey", 0.0, 0.2), _word("w1", "hey", 0.2, 0.4),
|
||||
_word("w2", "you", 0.4, 0.6)],
|
||||
"start_time": 0.0, "end_time": 0.6,
|
||||
}]
|
||||
refs = {"genius": {"segments": [{"text": "Hey hey you"}]}}
|
||||
assert find_suspicious_duplicates(segments, refs) == []
|
||||
assert find_suspicious_duplicates(segments, {}) == ["hey"]
|
||||
@@ -0,0 +1,248 @@
|
||||
"""Tests for the Phase-2B 3-stem backing decider (scorer branch + executor gating).
|
||||
|
||||
Comparison fixtures mirror the real corpus signal profiles (private
|
||||
validate_backing_decider.py table, 2026-08-28): the catastrophic
|
||||
backing-stem-is-the-lead job (1d45b286), the noise-floor grungegaze job
|
||||
(95d8e844), the quiet-genuine-harmonies job (d508adb6), and the high-corr
|
||||
genuine keep that must NOT trip the lead gate (33453fa0).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Dict, Optional
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services.auto_approval.models import BackingVerdict
|
||||
from backend.services.auto_approval.scorer import extract_backing_signals, score_backing
|
||||
|
||||
|
||||
def _analysis(
|
||||
audible_percentage: float = 25.0,
|
||||
loud: int = 2,
|
||||
comparison: Optional[Dict[str, Any]] = None,
|
||||
) -> Dict[str, Any]:
|
||||
segments = [
|
||||
{
|
||||
"start_seconds": 10.0 * i,
|
||||
"end_seconds": 10.0 * i + 5.0,
|
||||
"duration_seconds": 5.0,
|
||||
"avg_amplitude_db": -15.0 if i < loud else -35.0,
|
||||
"peak_amplitude_db": -10.0,
|
||||
}
|
||||
for i in range(4)
|
||||
]
|
||||
data: Dict[str, Any] = {
|
||||
"has_audible_content": True,
|
||||
"audible_percentage": audible_percentage,
|
||||
"audible_segments": segments,
|
||||
"recommended_selection": "with_backing",
|
||||
}
|
||||
if comparison is not None:
|
||||
data["stem_comparison"] = comparison
|
||||
return data
|
||||
|
||||
|
||||
def _comparison(**overrides: Any) -> Dict[str, Any]:
|
||||
base = {
|
||||
"window_ms": 100,
|
||||
"silence_threshold_db": -40.0,
|
||||
"duration_seconds": 200.0,
|
||||
"backing_audible_fraction": 0.30,
|
||||
"lead_audible_fraction": 0.65,
|
||||
"vocals_audible_fraction": 0.70,
|
||||
"coverage_ratio": 0.43,
|
||||
"corr_backing_vocals": 0.40,
|
||||
"corr_backing_lead": 0.20,
|
||||
"backing_median_db": -26.0,
|
||||
"lead_median_db": -18.0,
|
||||
"vocals_median_db": -17.0,
|
||||
"lead_overlap_fraction": 0.80,
|
||||
"backing_db_std": 4.5,
|
||||
"flat_fraction": 0.05,
|
||||
"error": None,
|
||||
}
|
||||
base.update(overrides)
|
||||
return base
|
||||
|
||||
|
||||
def test_genuine_backing_is_confident_keep() -> None:
|
||||
result = score_backing(_analysis(comparison=_comparison()))
|
||||
assert result.verdict == BackingVerdict.WITH_BACKING
|
||||
assert result.non_subjective is True
|
||||
|
||||
|
||||
def test_no_comparison_stays_review() -> None:
|
||||
result = score_backing(_analysis())
|
||||
assert result.verdict == BackingVerdict.REVIEW
|
||||
assert result.non_subjective is False
|
||||
|
||||
|
||||
def test_errored_comparison_reads_as_absent() -> None:
|
||||
result = score_backing(
|
||||
_analysis(comparison=_comparison(error="boom"))
|
||||
)
|
||||
assert result.verdict == BackingVerdict.REVIEW
|
||||
assert result.signals.comparison_present is False
|
||||
|
||||
|
||||
def test_backing_stem_is_lead_never_keeps() -> None:
|
||||
# 1d45b286 profile: covR 0.94, corr 0.95, backing 60% vs lead 18%.
|
||||
result = score_backing(
|
||||
_analysis(
|
||||
audible_percentage=60.0,
|
||||
comparison=_comparison(
|
||||
coverage_ratio=0.94,
|
||||
corr_backing_vocals=0.95,
|
||||
backing_audible_fraction=0.60,
|
||||
lead_audible_fraction=0.18,
|
||||
),
|
||||
)
|
||||
)
|
||||
assert result.verdict == BackingVerdict.REVIEW
|
||||
assert "BE the lead" in " ".join(result.reasons)
|
||||
|
||||
|
||||
def test_high_corr_keep_with_stronger_lead_does_not_trip_lead_gate() -> None:
|
||||
# 33453fa0 profile: covR 0.77 / corr 0.86 but backing (28%) < lead (34%).
|
||||
result = score_backing(
|
||||
_analysis(
|
||||
audible_percentage=28.0,
|
||||
comparison=_comparison(
|
||||
coverage_ratio=0.77,
|
||||
corr_backing_vocals=0.86,
|
||||
backing_audible_fraction=0.28,
|
||||
lead_audible_fraction=0.34,
|
||||
backing_median_db=-33.0,
|
||||
),
|
||||
)
|
||||
)
|
||||
assert result.verdict == BackingVerdict.WITH_BACKING
|
||||
|
||||
|
||||
def test_noise_floor_signature_is_review() -> None:
|
||||
# 95d8e844 profile: median -38.6 dB over 30% of the track, corr -0.23.
|
||||
result = score_backing(
|
||||
_analysis(
|
||||
audible_percentage=30.0,
|
||||
comparison=_comparison(
|
||||
backing_median_db=-38.6,
|
||||
backing_audible_fraction=0.30,
|
||||
corr_backing_vocals=-0.23,
|
||||
coverage_ratio=0.42,
|
||||
),
|
||||
)
|
||||
)
|
||||
assert result.verdict == BackingVerdict.REVIEW
|
||||
assert "noise-floor" in " ".join(result.reasons)
|
||||
|
||||
|
||||
def test_quiet_sparse_harmonies_still_keep() -> None:
|
||||
# d508adb6 profile: 1% audible at -38 dB, overlap 0.89 — genuine harmonies.
|
||||
result = score_backing(
|
||||
_analysis(
|
||||
audible_percentage=1.0,
|
||||
loud=1,
|
||||
comparison=_comparison(
|
||||
backing_median_db=-38.1,
|
||||
backing_audible_fraction=0.01,
|
||||
corr_backing_vocals=0.19,
|
||||
coverage_ratio=0.01,
|
||||
lead_overlap_fraction=0.89,
|
||||
),
|
||||
)
|
||||
)
|
||||
assert result.verdict == BackingVerdict.WITH_BACKING
|
||||
|
||||
|
||||
def test_sparse_full_lead_overlap_is_bleed_review() -> None:
|
||||
result = score_backing(
|
||||
_analysis(
|
||||
audible_percentage=2.0,
|
||||
comparison=_comparison(
|
||||
backing_audible_fraction=0.02,
|
||||
coverage_ratio=0.03,
|
||||
lead_overlap_fraction=0.99,
|
||||
),
|
||||
)
|
||||
)
|
||||
assert result.verdict == BackingVerdict.REVIEW
|
||||
assert "bleed" in " ".join(result.reasons)
|
||||
|
||||
|
||||
def test_near_silent_rule_still_wins_over_comparison() -> None:
|
||||
analysis = _analysis(audible_percentage=0.1, comparison=_comparison())
|
||||
analysis["audible_segments"] = []
|
||||
result = score_backing(analysis)
|
||||
assert result.verdict == BackingVerdict.CLEAN
|
||||
|
||||
|
||||
def test_comparison_signals_extracted() -> None:
|
||||
s = extract_backing_signals(_analysis(comparison=_comparison()))
|
||||
assert s.comparison_present is True
|
||||
assert s.coverage_ratio == 0.43
|
||||
assert s.corr_backing_vocals == 0.40
|
||||
assert s.lead_overlap_fraction == 0.80
|
||||
assert s.backing_median_db == -26.0
|
||||
assert s.flat_fraction == 0.05
|
||||
|
||||
|
||||
# ---- executor gating for WITH_BACKING enforcement ----
|
||||
|
||||
from backend.models.job import JobStatus # noqa: E402
|
||||
from backend.tests.services.auto_approval.test_executor import ( # noqa: E402
|
||||
_confident_corrections,
|
||||
_job,
|
||||
_run,
|
||||
)
|
||||
|
||||
|
||||
def _keep_backing_analysis() -> Dict[str, Any]:
|
||||
return _analysis(comparison=_comparison())
|
||||
|
||||
|
||||
def _keep_job(with_backing_stem: bool = True) -> SimpleNamespace:
|
||||
job = _job(backing=_keep_backing_analysis())
|
||||
if with_backing_stem:
|
||||
job.file_urls["stems"]["instrumental_with_backing"] = (
|
||||
"jobs/j1/stems/instrumental_with_backing.flac"
|
||||
)
|
||||
return job
|
||||
|
||||
|
||||
def _settings(keep_enabled: bool) -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
auto_approval_enforce_enabled=True,
|
||||
auto_approval_backing_keep_enabled=keep_enabled,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_confident_keep_blocked_while_flag_off() -> None:
|
||||
result, job_manager, *_ = await _run(_keep_job(), settings=_settings(False))
|
||||
assert result["outcome"] == "review"
|
||||
assert "backing_keep_disabled" in result["blockers"]
|
||||
payload = job_manager.update_processing_metadata.call_args[0][2]
|
||||
assert payload["backing"]["verdict"] == "with_backing"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_confident_keep_enforced_when_flag_on() -> None:
|
||||
result, job_manager, _storage, worker = await _run(
|
||||
_keep_job(), settings=_settings(True)
|
||||
)
|
||||
assert result["outcome"] == "auto_completed"
|
||||
job_manager.update_state_data.assert_any_call(
|
||||
"j1", "instrumental_selection", "with_backing"
|
||||
)
|
||||
worker.trigger_render_video_worker.assert_awaited_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_confident_keep_needs_with_backing_stem() -> None:
|
||||
result, *_ = await _run(
|
||||
_keep_job(with_backing_stem=False), settings=_settings(True)
|
||||
)
|
||||
assert result["outcome"] == "review"
|
||||
assert "no_with_backing_stem" in result["blockers"]
|
||||
@@ -0,0 +1,364 @@
|
||||
"""Tests for the auto-approval executor.
|
||||
|
||||
The executor must (a) record a verdict on every scored job, (b) complete the
|
||||
review end-to-end ONLY when fully confident and eligible, and (c) fail safe —
|
||||
any anomaly or error leaves the job on the normal human-review path.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Dict, List, Optional
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.auto_approval.executor import maybe_auto_complete_review
|
||||
|
||||
|
||||
def _confident_corrections() -> Dict[str, Any]:
|
||||
words = [
|
||||
{"id": f"w{i}", "text": f"word{i}", "start_time": i * 0.5, "end_time": i * 0.5 + 0.4}
|
||||
for i in range(20)
|
||||
]
|
||||
return {
|
||||
"corrected_segments": [{
|
||||
"id": "s0",
|
||||
"text": " ".join(w["text"] for w in words),
|
||||
"words": words,
|
||||
"start_time": 0.0,
|
||||
"end_time": 10.0,
|
||||
}],
|
||||
"corrections": [],
|
||||
"corrections_made": 0,
|
||||
"reference_lyrics": {"spotify": {"metadata": {"is_synced": True}, "segments": []}},
|
||||
"anchor_sequences": [{"id": "a0", "transcribed_word_ids": [w["id"] for w in words]}],
|
||||
"gap_sequences": [],
|
||||
"metadata": {"total_words": 20, "agentic_routing": "disabled", "correction_type": "none"},
|
||||
}
|
||||
|
||||
|
||||
def _clean_backing() -> Dict[str, Any]:
|
||||
return {
|
||||
"has_audible_content": False,
|
||||
"audible_percentage": 0.0,
|
||||
"audible_segments": [],
|
||||
"recommended_selection": "clean",
|
||||
}
|
||||
|
||||
|
||||
def _job(
|
||||
status: JobStatus = JobStatus.GENERATING_SCREENS,
|
||||
review_mode: str = "auto",
|
||||
made_for_you: bool = False,
|
||||
audio_complete: bool = True,
|
||||
backing: Optional[Dict[str, Any]] = None,
|
||||
existing_instrumental: Optional[str] = None,
|
||||
state_extra: Optional[Dict[str, Any]] = None,
|
||||
) -> SimpleNamespace:
|
||||
state: Dict[str, Any] = {"audio_complete": audio_complete}
|
||||
if backing is not None:
|
||||
state["backing_vocals_analysis"] = backing
|
||||
state.update(state_extra or {})
|
||||
return SimpleNamespace(
|
||||
status=status,
|
||||
state_data=state,
|
||||
review_mode=review_mode,
|
||||
made_for_you=made_for_you,
|
||||
existing_instrumental_gcs_path=existing_instrumental,
|
||||
file_urls={"stems": {"instrumental_clean": "jobs/j1/stems/clean.flac"}},
|
||||
)
|
||||
|
||||
|
||||
def _settings(enforce: bool = True) -> SimpleNamespace:
|
||||
return SimpleNamespace(auto_approval_enforce_enabled=enforce)
|
||||
|
||||
|
||||
async def _run(job, *, corrections=None, suggestions=None, settings=None):
|
||||
"""Drive maybe_auto_complete_review with everything mocked; returns
|
||||
(result, job_manager_mock, storage_mock, worker_service_mock)."""
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.return_value = job
|
||||
storage = MagicMock()
|
||||
corrections = corrections if corrections is not None else _confident_corrections()
|
||||
storage.file_exists.return_value = True
|
||||
cache = {"suggestions": suggestions if suggestions is not None else []}
|
||||
storage.list_files.return_value = ["jobs/j1/lyrics/auto_correct_cache/x.json"]
|
||||
|
||||
def _download(path: str):
|
||||
if "auto_correct_cache" in path:
|
||||
return cache
|
||||
return corrections
|
||||
|
||||
storage.download_json.side_effect = _download
|
||||
|
||||
worker_service = MagicMock()
|
||||
worker_service.trigger_render_video_worker = AsyncMock(return_value=True)
|
||||
|
||||
with patch("backend.services.job_manager.JobManager", return_value=job_manager), \
|
||||
patch("backend.services.storage_service.StorageService", return_value=storage), \
|
||||
patch("backend.config.get_settings", return_value=settings or _settings()), \
|
||||
patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
|
||||
result = await maybe_auto_complete_review("j1", trigger="screens_worker")
|
||||
return result, job_manager, storage, worker_service
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_confident_job_is_auto_completed() -> None:
|
||||
result, jm, storage, ws = await _run(_job(backing=_clean_backing()))
|
||||
assert result["outcome"] == "auto_completed"
|
||||
|
||||
# corrections_updated.json saved with the auto-approval marker
|
||||
upload_path, uploaded = storage.upload_json.call_args.args
|
||||
assert upload_path == "jobs/j1/lyrics/corrections_updated.json"
|
||||
assert uploaded["metadata"]["auto_approval"]["auto_approved"] is True
|
||||
|
||||
# instrumental selection stored, progress keys cleared, transitioned, render triggered
|
||||
jm.update_state_data.assert_any_call("j1", "instrumental_selection", "clean")
|
||||
jm.delete_state_data_keys.assert_called_once()
|
||||
transition_kwargs = jm.transition_to_state.call_args.kwargs
|
||||
assert transition_kwargs["new_status"] == JobStatus.REVIEW_COMPLETE
|
||||
ws.trigger_render_video_worker.assert_awaited_once_with("j1")
|
||||
|
||||
# verdict recorded with outcome
|
||||
section, payload = jm.update_processing_metadata.call_args.args[1:3]
|
||||
assert section == "auto_approval"
|
||||
assert payload["outcome"] == "auto_completed"
|
||||
assert payload["mode"] == "enforce"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ai_suggestions_are_applied_in_saved_corrections() -> None:
|
||||
suggestions = [{
|
||||
"id": "sugA", "op": "replace", "word_ids": ["w3"], "segment_ids": ["s0"],
|
||||
"original_text": "word3", "new_text": "fixed", "confidence": 0.9,
|
||||
"consensus": 2, "total_models": 2, "conflict_group": None,
|
||||
}]
|
||||
result, jm, storage, _ = await _run(_job(backing=_clean_backing()), suggestions=suggestions)
|
||||
assert result["outcome"] == "auto_completed"
|
||||
uploaded = storage.upload_json.call_args.args[1]
|
||||
texts = [w["text"] for w in uploaded["corrected_segments"][0]["words"]]
|
||||
assert "fixed" in texts and "word3" not in texts
|
||||
assert uploaded["metadata"]["auto_approval"]["applied_suggestion_ids"] == ["sugA"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unconfident_job_goes_to_review_with_verdict_recorded() -> None:
|
||||
audible = {"has_audible_content": True, "audible_percentage": 40.0,
|
||||
"audible_segments": [{"avg_amplitude_db": -10.0}],
|
||||
"recommended_selection": "with_backing"}
|
||||
result, jm, storage, ws = await _run(_job(backing=audible))
|
||||
assert result["outcome"] == "review"
|
||||
jm.transition_to_state.assert_not_called()
|
||||
storage.upload_json.assert_not_called()
|
||||
ws.trigger_render_video_worker.assert_not_awaited()
|
||||
payload = jm.update_processing_metadata.call_args.args[2]
|
||||
assert payload["outcome"] == "review"
|
||||
assert payload["mode"] == "shadow"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_always_review_mode_blocks_enforcement() -> None:
|
||||
result, jm, _, _ = await _run(_job(review_mode="always_review", backing=_clean_backing()))
|
||||
assert result["outcome"] == "review"
|
||||
assert "review_mode:always_review" in result["blockers"]
|
||||
jm.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_made_for_you_blocks_enforcement() -> None:
|
||||
result, jm, _, _ = await _run(_job(made_for_you=True, backing=_clean_backing()))
|
||||
assert result["outcome"] == "review"
|
||||
assert "made_for_you" in result["blockers"]
|
||||
jm.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_flag_disabled_blocks_enforcement() -> None:
|
||||
result, jm, _, _ = await _run(
|
||||
_job(backing=_clean_backing()), settings=_settings(enforce=False)
|
||||
)
|
||||
assert result["outcome"] == "review"
|
||||
assert "flag_disabled" in result["blockers"]
|
||||
jm.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_incomplete_audio_blocks_enforcement() -> None:
|
||||
result, jm, _, _ = await _run(_job(audio_complete=False, backing=None))
|
||||
assert result["outcome"] == "review"
|
||||
assert "audio_incomplete" in result["blockers"]
|
||||
jm.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_existing_instrumental_completes_with_custom_selection() -> None:
|
||||
# Tenant/bulk jobs with a user-supplied instrumental have NO instrumental
|
||||
# decision — confident lyrics alone auto-complete with selection="custom",
|
||||
# even with NO backing analysis at all (the backing verdict is moot).
|
||||
result, jm, _, _ = await _run(
|
||||
_job(backing=None, existing_instrumental="jobs/j1/custom.flac")
|
||||
)
|
||||
assert result["outcome"] == "auto_completed"
|
||||
jm.update_state_data.assert_any_call("j1", "instrumental_selection", "custom")
|
||||
payload = jm.update_processing_metadata.call_args.args[2]
|
||||
assert payload["enforcement_basis"] == "lyrics_only_custom_instrumental"
|
||||
assert payload["custom_instrumental"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_custom_instrumental_stem_also_selects_custom() -> None:
|
||||
job = _job(backing=None)
|
||||
job.file_urls["stems"]["custom_instrumental"] = "jobs/j1/stems/custom.flac"
|
||||
# No separated instrumental required for custom jobs.
|
||||
del job.file_urls["stems"]["instrumental_clean"]
|
||||
result, jm, _, _ = await _run(job)
|
||||
assert result["outcome"] == "auto_completed"
|
||||
jm.update_state_data.assert_any_call("j1", "instrumental_selection", "custom")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_existing_instrumental_still_requires_confident_lyrics() -> None:
|
||||
corrections = _confident_corrections()
|
||||
corrections["reference_lyrics"] = {} # no references -> lyrics review
|
||||
result, jm, _, _ = await _run(
|
||||
_job(backing=None, existing_instrumental="jobs/j1/custom.flac"),
|
||||
corrections=corrections,
|
||||
)
|
||||
assert result["outcome"] == "review"
|
||||
jm.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_wrong_status_is_noop() -> None:
|
||||
result, jm, _, _ = await _run(_job(status=JobStatus.IN_REVIEW, backing=_clean_backing()))
|
||||
assert result["outcome"] == "wrong_status"
|
||||
jm.update_processing_metadata.assert_not_called()
|
||||
jm.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_existing_selection_is_noop() -> None:
|
||||
result, jm, _, _ = await _run(
|
||||
_job(backing=_clean_backing(), state_extra={"instrumental_selection": "clean"})
|
||||
)
|
||||
assert result["outcome"] == "already_selected"
|
||||
jm.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stale_suggestion_aborts_to_review() -> None:
|
||||
suggestions = [{
|
||||
"id": "sugA", "op": "replace", "word_ids": ["not-a-word"], "segment_ids": ["s0"],
|
||||
"original_text": "x", "new_text": "y", "confidence": 0.9,
|
||||
"consensus": 2, "total_models": 2, "conflict_group": None,
|
||||
}]
|
||||
result, jm, storage, ws = await _run(_job(backing=_clean_backing()), suggestions=suggestions)
|
||||
assert result["outcome"] == "aborted"
|
||||
assert "stale_suggestions" in result["reason"]
|
||||
jm.transition_to_state.assert_not_called()
|
||||
storage.upload_json.assert_not_called()
|
||||
ws.trigger_render_video_worker.assert_not_awaited()
|
||||
payload = jm.update_processing_metadata.call_args.args[2]
|
||||
assert payload["outcome"] == "aborted"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_duplicate_word_artifact_aborts_to_review() -> None:
|
||||
# P1 self-conflict: two overlapping suggestions both add the same token.
|
||||
suggestions = [
|
||||
{"id": "a", "op": "insert_after", "word_ids": ["w3"], "segment_ids": ["s0"],
|
||||
"original_text": "", "new_text": "extra", "confidence": 0.75,
|
||||
"consensus": 1, "total_models": 2, "conflict_group": None},
|
||||
{"id": "b", "op": "replace", "word_ids": ["w4"], "segment_ids": ["s0"],
|
||||
"original_text": "word4", "new_text": "extra word4", "confidence": 0.95,
|
||||
"consensus": 1, "total_models": 2, "conflict_group": None},
|
||||
]
|
||||
result, jm, storage, _ = await _run(_job(backing=_clean_backing()), suggestions=suggestions)
|
||||
assert result["outcome"] == "aborted"
|
||||
assert "duplicate_words" in result["reason"]
|
||||
jm.transition_to_state.assert_not_called()
|
||||
storage.upload_json.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_state_change_during_enforce_aborts() -> None:
|
||||
# A human opening the editor between the snapshot read and the enforce
|
||||
# writes (AWAITING_REVIEW -> IN_REVIEW) must abort — IN_REVIEW ->
|
||||
# REVIEW_COMPLETE is a legal transition, so validation alone won't stop it.
|
||||
eligible = _job(backing=_clean_backing())
|
||||
editing = _job(status=JobStatus.IN_REVIEW, backing=_clean_backing())
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.side_effect = [eligible, editing]
|
||||
storage = MagicMock()
|
||||
storage.file_exists.return_value = True
|
||||
storage.list_files.return_value = []
|
||||
storage.download_json.return_value = _confident_corrections()
|
||||
with patch("backend.services.job_manager.JobManager", return_value=job_manager), \
|
||||
patch("backend.services.storage_service.StorageService", return_value=storage), \
|
||||
patch("backend.config.get_settings", return_value=_settings()):
|
||||
result = await maybe_auto_complete_review("j1", trigger="screens_worker")
|
||||
assert result["outcome"] == "aborted"
|
||||
assert result["reason"] == "state_changed_during_enforce"
|
||||
job_manager.transition_to_state.assert_not_called()
|
||||
storage.upload_json.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_missing_corrections_is_noop() -> None:
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.return_value = _job(backing=_clean_backing())
|
||||
storage = MagicMock()
|
||||
storage.file_exists.return_value = False
|
||||
with patch("backend.services.job_manager.JobManager", return_value=job_manager), \
|
||||
patch("backend.services.storage_service.StorageService", return_value=storage), \
|
||||
patch("backend.config.get_settings", return_value=_settings()):
|
||||
result = await maybe_auto_complete_review("j1", trigger="screens_worker")
|
||||
assert result["outcome"] == "no_corrections"
|
||||
job_manager.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_any_exception_is_nonfatal() -> None:
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.side_effect = Exception("firestore down")
|
||||
with patch("backend.services.job_manager.JobManager", return_value=job_manager), \
|
||||
patch("backend.services.storage_service.StorageService", MagicMock()), \
|
||||
patch("backend.config.get_settings", return_value=_settings()):
|
||||
result = await maybe_auto_complete_review("j1", trigger="screens_worker")
|
||||
assert result["outcome"] == "error"
|
||||
|
||||
|
||||
def _audible_backing() -> Dict[str, Any]:
|
||||
# Pink backing present, no 3-stem comparison -> scorer verdict REVIEW.
|
||||
return {
|
||||
"has_audible_content": True,
|
||||
"audible_percentage": 40.0,
|
||||
"audible_segments": [{"avg_amplitude_db": -10.0}],
|
||||
"recommended_selection": "with_backing",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_backing_preference_clean_forces_clean_completion() -> None:
|
||||
# Backing is subjective (would normally gate), but the user chose "clean"
|
||||
# up-front -> auto-complete on lyrics alone with a clean instrumental.
|
||||
job = _job(backing=_audible_backing())
|
||||
job.backing_preference = "clean"
|
||||
result, jm, storage, ws = await _run(job)
|
||||
assert result["outcome"] == "auto_completed"
|
||||
jm.update_state_data.assert_any_call("j1", "instrumental_selection", "clean")
|
||||
ws.trigger_render_video_worker.assert_awaited_once_with("j1")
|
||||
payload = jm.update_processing_metadata.call_args.args[2]
|
||||
assert payload["enforcement_basis"] == "lyrics_auto_backing_pref:clean"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_backing_preference_review_blocks_even_confident_clean() -> None:
|
||||
# User wants to always pick the instrumental -> never auto-skip the backing half.
|
||||
job = _job(backing=_clean_backing())
|
||||
job.backing_preference = "review"
|
||||
result, jm, _, ws = await _run(job)
|
||||
assert result["outcome"] == "review"
|
||||
jm.transition_to_state.assert_not_called()
|
||||
ws.trigger_render_video_worker.assert_not_awaited()
|
||||
@@ -0,0 +1,193 @@
|
||||
"""Tests for the shared instrumental-decision helper (workstream C).
|
||||
|
||||
``backing_decision`` is the single source of truth used by the executor, the
|
||||
complete-review "auto" resolver, and the per-screen-skip UI summary — they must
|
||||
all agree, so the matrix is pinned here.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from backend.services.auto_approval.instrumental import (
|
||||
auto_approval_summary,
|
||||
backing_decision,
|
||||
has_custom_instrumental,
|
||||
resolve_auto_instrumental,
|
||||
)
|
||||
|
||||
|
||||
def _decide(**kw):
|
||||
base = dict(
|
||||
backing_verdict="clean",
|
||||
backing_non_subjective=True,
|
||||
backing_preference="auto",
|
||||
backing_keep_enabled=True,
|
||||
custom_instrumental=False,
|
||||
)
|
||||
base.update(kw)
|
||||
return backing_decision(**base)
|
||||
|
||||
|
||||
# ---- backing_decision matrix ------------------------------------------------
|
||||
|
||||
def test_custom_instrumental_always_custom():
|
||||
d = _decide(custom_instrumental=True, backing_verdict="review", backing_non_subjective=False)
|
||||
assert d == {"ok": True, "selection": "custom", "keep_backing": False}
|
||||
|
||||
|
||||
def test_clean_verdict_auto_resolves_clean():
|
||||
assert _decide(backing_verdict="clean")["selection"] == "clean"
|
||||
assert _decide(backing_verdict="clean")["ok"] is True
|
||||
|
||||
|
||||
def test_with_backing_verdict_keep_enabled_resolves_with_backing():
|
||||
d = _decide(backing_verdict="with_backing", backing_keep_enabled=True)
|
||||
assert d == {"ok": True, "selection": "with_backing", "keep_backing": True}
|
||||
|
||||
|
||||
def test_with_backing_verdict_keep_disabled_not_resolvable():
|
||||
d = _decide(backing_verdict="with_backing", backing_keep_enabled=False)
|
||||
assert d["ok"] is False and d["selection"] is None and d["keep_backing"] is True
|
||||
|
||||
|
||||
def test_review_verdict_not_resolvable():
|
||||
d = _decide(backing_verdict="review", backing_non_subjective=False)
|
||||
assert d["ok"] is False and d["selection"] is None
|
||||
|
||||
|
||||
def test_preference_clean_forces_clean_even_over_review_verdict():
|
||||
# User explicitly asked to strip backing vocals -> clean regardless of verdict.
|
||||
d = _decide(backing_verdict="review", backing_non_subjective=False, backing_preference="clean")
|
||||
assert d == {"ok": True, "selection": "clean", "keep_backing": False}
|
||||
|
||||
|
||||
def test_preference_clean_overrides_with_backing_verdict():
|
||||
d = _decide(backing_verdict="with_backing", backing_preference="clean")
|
||||
assert d["selection"] == "clean" and d["keep_backing"] is False
|
||||
|
||||
|
||||
def test_preference_review_suppresses_even_confident_clean():
|
||||
# User always wants to pick the instrumental themselves.
|
||||
d = _decide(backing_verdict="clean", backing_preference="review")
|
||||
assert d["ok"] is False and d["selection"] is None
|
||||
|
||||
|
||||
def test_unknown_preference_falls_back_to_auto():
|
||||
assert _decide(backing_verdict="clean", backing_preference="garbage")["selection"] == "clean"
|
||||
|
||||
|
||||
# ---- has_custom_instrumental ------------------------------------------------
|
||||
|
||||
def test_has_custom_instrumental_from_existing_path():
|
||||
job = SimpleNamespace(existing_instrumental_gcs_path="jobs/j/inst.flac", file_urls=None)
|
||||
assert has_custom_instrumental(job) is True
|
||||
|
||||
|
||||
def test_has_custom_instrumental_from_stem():
|
||||
job = SimpleNamespace(
|
||||
existing_instrumental_gcs_path=None,
|
||||
file_urls={"stems": {"custom_instrumental": "jobs/j/custom.flac"}},
|
||||
)
|
||||
assert has_custom_instrumental(job) is True
|
||||
|
||||
|
||||
def test_has_custom_instrumental_false():
|
||||
job = SimpleNamespace(
|
||||
existing_instrumental_gcs_path=None,
|
||||
file_urls={"stems": {"instrumental_clean": "jobs/j/clean.flac"}},
|
||||
)
|
||||
assert has_custom_instrumental(job) is False
|
||||
|
||||
|
||||
# ---- summary + resolver over stored verdict ---------------------------------
|
||||
|
||||
def _job_with_verdict(backing_verdict, non_subjective, lyrics_verdict="auto", pref="auto",
|
||||
custom=False, review_mode="auto", stems=None):
|
||||
if stems is None:
|
||||
stems = {
|
||||
"instrumental_clean": "jobs/j/clean.flac",
|
||||
"instrumental_with_backing": "jobs/j/backing.flac",
|
||||
}
|
||||
return SimpleNamespace(
|
||||
processing_metadata={
|
||||
"auto_approval": {
|
||||
"backing": {"verdict": backing_verdict, "non_subjective": non_subjective},
|
||||
"lyrics": {"verdict": lyrics_verdict},
|
||||
}
|
||||
},
|
||||
backing_preference=pref,
|
||||
review_mode=review_mode,
|
||||
existing_instrumental_gcs_path=("jobs/j/inst.flac" if custom else None),
|
||||
file_urls={"stems": stems},
|
||||
)
|
||||
|
||||
|
||||
def _settings(keep=True):
|
||||
return SimpleNamespace(auto_approval_backing_keep_enabled=keep)
|
||||
|
||||
|
||||
def test_summary_confident_clean():
|
||||
s = auto_approval_summary(_job_with_verdict("clean", True), _settings())
|
||||
assert s["backing"] == {"verdict": "clean", "confident": True, "resolved_selection": "clean"}
|
||||
assert s["lyrics"] == {"verdict": "auto", "confident": True}
|
||||
assert s["verdict_present"] is True
|
||||
|
||||
|
||||
def test_summary_backing_needs_review_not_confident():
|
||||
s = auto_approval_summary(_job_with_verdict("review", False), _settings())
|
||||
assert s["backing"]["confident"] is False
|
||||
assert s["backing"]["resolved_selection"] is None
|
||||
|
||||
|
||||
def test_summary_no_verdict_is_safe_default():
|
||||
job = SimpleNamespace(processing_metadata={}, backing_preference="auto",
|
||||
existing_instrumental_gcs_path=None, file_urls={"stems": {}})
|
||||
s = auto_approval_summary(job, _settings())
|
||||
assert s["verdict_present"] is False
|
||||
assert s["backing"]["confident"] is False
|
||||
assert s["lyrics"]["confident"] is False
|
||||
|
||||
|
||||
def test_resolve_auto_instrumental_with_backing_gated():
|
||||
# keep disabled -> not resolvable
|
||||
assert resolve_auto_instrumental(_job_with_verdict("with_backing", True), _settings(keep=False)) is None
|
||||
# keep enabled -> with_backing
|
||||
assert resolve_auto_instrumental(_job_with_verdict("with_backing", True), _settings(keep=True)) == "with_backing"
|
||||
|
||||
|
||||
def test_resolve_auto_instrumental_custom():
|
||||
assert resolve_auto_instrumental(_job_with_verdict("review", False, custom=True), _settings()) == "custom"
|
||||
|
||||
|
||||
def test_always_review_never_confident():
|
||||
# review_mode="always_review" -> the user wants every screen; nothing skips.
|
||||
s = auto_approval_summary(_job_with_verdict("clean", True, review_mode="always_review"), _settings())
|
||||
assert s["backing"]["confident"] is False
|
||||
assert s["backing"]["resolved_selection"] is None
|
||||
assert s["lyrics"]["confident"] is False
|
||||
assert resolve_auto_instrumental(
|
||||
_job_with_verdict("clean", True, review_mode="always_review"), _settings()) is None
|
||||
|
||||
|
||||
def test_resolve_returns_none_when_clean_stem_absent():
|
||||
# Confident clean verdict but the clean stem isn't present -> a human must pick.
|
||||
job = _job_with_verdict("clean", True, stems={"instrumental_with_backing": "x"})
|
||||
assert resolve_auto_instrumental(job, _settings()) is None
|
||||
assert auto_approval_summary(job, _settings())["backing"]["confident"] is False
|
||||
|
||||
|
||||
def test_resolve_returns_none_when_with_backing_stem_absent():
|
||||
job = _job_with_verdict("with_backing", True, stems={"instrumental_clean": "x"})
|
||||
assert resolve_auto_instrumental(job, _settings(keep=True)) is None
|
||||
|
||||
|
||||
# ---- JobCreate coercion (typo must never silently flip intent) ---------------
|
||||
|
||||
def test_jobcreate_coerces_out_of_set_preferences():
|
||||
from backend.models.job import JobCreate
|
||||
assert JobCreate(backing_preference="cleen").backing_preference == "auto"
|
||||
assert JobCreate(backing_preference="clean").backing_preference == "clean"
|
||||
# review_mode fails safe toward MORE review, never toward auto-skip.
|
||||
assert JobCreate(review_mode="typo").review_mode == "always_review"
|
||||
assert JobCreate(review_mode="auto").review_mode == "auto"
|
||||
assert JobCreate().backing_preference == "auto" and JobCreate().review_mode == "auto"
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Tests for the review-diff reconstruction."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from backend.services.auto_approval.lyrics_diff import compute_lyrics_diff
|
||||
|
||||
|
||||
def _w(wid: str, text: str, start: float, end: float) -> Dict[str, Any]:
|
||||
return {"id": wid, "text": text, "start_time": start, "end_time": end}
|
||||
|
||||
|
||||
def _seg(sid: str, words: List[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
return {
|
||||
"id": sid,
|
||||
"text": " ".join(w["text"] for w in words),
|
||||
"words": words,
|
||||
"start_time": words[0]["start_time"] if words else 0.0,
|
||||
"end_time": words[-1]["end_time"] if words else 0.0,
|
||||
}
|
||||
|
||||
|
||||
def _doc(segments: List[Dict[str, Any]], corrections: List[Any] | None = None) -> Dict[str, Any]:
|
||||
return {"corrected_segments": segments, "corrections": corrections or []}
|
||||
|
||||
|
||||
def test_no_updated_data_means_no_changes() -> None:
|
||||
orig = _doc([_seg("s0", [_w("w0", "hello", 0.0, 0.5)])])
|
||||
diff = compute_lyrics_diff(orig, None)
|
||||
assert diff.has_changes is False
|
||||
assert diff.total_changes == 0
|
||||
assert diff.final_word_count == 1
|
||||
|
||||
|
||||
def test_text_edit_detected() -> None:
|
||||
orig = _doc([_seg("s0", [_w("w0", "helo", 0.0, 0.5), _w("w1", "wrld", 0.5, 1.0)])])
|
||||
final = _doc([_seg("s0", [_w("w0", "hello", 0.0, 0.5), _w("w1", "world", 0.5, 1.0)])])
|
||||
diff = compute_lyrics_diff(orig, final)
|
||||
assert diff.total_changes == 2
|
||||
assert {e.final_text for e in diff.text_edits} == {"hello", "world"}
|
||||
assert not diff.timing_changes
|
||||
|
||||
|
||||
def test_replacement_paired_by_timing() -> None:
|
||||
# UI re-keys a corrected word but keeps its start/end/line -> should pair as replacement.
|
||||
orig = _doc([_seg("s0", [_w("wA", "Carl", 231.18, 231.80)])])
|
||||
final = _doc([_seg("s0", [_w("wB", "Karl", 231.18, 231.80)])])
|
||||
diff = compute_lyrics_diff(orig, final)
|
||||
assert diff.total_changes == 1
|
||||
assert len(diff.replacements) == 1
|
||||
assert not diff.deletions and not diff.insertions
|
||||
r = diff.replacements[0]
|
||||
assert (r.original_text, r.final_text) == ("Carl", "Karl")
|
||||
assert r.original_word_id == "wA" and r.final_word_id == "wB"
|
||||
|
||||
|
||||
def test_replacement_not_paired_when_timing_differs() -> None:
|
||||
# Different timing -> genuine delete + insert, not a replacement.
|
||||
orig = _doc([_seg("s0", [_w("wA", "Carl", 231.18, 231.80)])])
|
||||
final = _doc([_seg("s0", [_w("wB", "Karl", 10.0, 10.5)])])
|
||||
diff = compute_lyrics_diff(orig, final)
|
||||
assert not diff.replacements
|
||||
assert [d.text for d in diff.deletions] == ["Carl"]
|
||||
assert [i.text for i in diff.insertions] == ["Karl"]
|
||||
|
||||
|
||||
def test_timing_change_respects_epsilon() -> None:
|
||||
orig = _doc([_seg("s0", [_w("w0", "hey", 1.000, 1.500)])])
|
||||
# start moved 0.2s (significant), end moved 0.001s (noise, below epsilon)
|
||||
final = _doc([_seg("s0", [_w("w0", "hey", 1.200, 1.501)])])
|
||||
diff = compute_lyrics_diff(orig, final)
|
||||
assert len(diff.timing_changes) == 1
|
||||
tc = diff.timing_changes[0]
|
||||
assert tc.start_delta == 0.2
|
||||
assert not diff.text_edits
|
||||
|
||||
|
||||
def test_deletion_and_insertion() -> None:
|
||||
orig = _doc([_seg("s0", [_w("w0", "one", 0.0, 0.5), _w("w1", "two", 0.5, 1.0)])])
|
||||
final = _doc([_seg("s0", [_w("w0", "one", 0.0, 0.5), _w("w2", "three", 1.0, 1.5)])])
|
||||
diff = compute_lyrics_diff(orig, final)
|
||||
assert [d.text for d in diff.deletions] == ["two"]
|
||||
assert [i.text for i in diff.insertions] == ["three"]
|
||||
assert diff.total_changes == 2
|
||||
|
||||
|
||||
def test_split_detected_as_segmentation_change() -> None:
|
||||
orig = _doc([_seg("s0", [_w("w0", "a", 0.0, 0.5), _w("w1", "b", 0.5, 1.0)])])
|
||||
# Same words, now on two lines -> segment move for w1 + segment count change.
|
||||
final = _doc([
|
||||
_seg("s0", [_w("w0", "a", 0.0, 0.5)]),
|
||||
_seg("s1", [_w("w1", "b", 0.5, 1.0)]),
|
||||
])
|
||||
diff = compute_lyrics_diff(orig, final)
|
||||
assert diff.segmentation_changed is True
|
||||
assert len(diff.segment_moves) == 1
|
||||
assert diff.segment_moves[0].word_id == "w1"
|
||||
assert diff.original_segment_count == 1
|
||||
assert diff.final_segment_count == 2
|
||||
|
||||
|
||||
def test_clean_unedited_job_yields_empty_diff() -> None:
|
||||
seg = [_seg("s0", [_w("w0", "same", 0.0, 0.5)])]
|
||||
diff = compute_lyrics_diff(_doc(seg), _doc(seg))
|
||||
assert diff.has_changes is False
|
||||
assert diff.total_changes == 0
|
||||
@@ -0,0 +1,208 @@
|
||||
"""Tests for the server-side pre-apply (workstream C, C2).
|
||||
|
||||
``ensure_and_pre_apply`` applies the cached AI suggestions BEFORE the review-ready
|
||||
notification and writes ``corrections_updated.json`` with a ``pre_applied`` marker.
|
||||
It is best-effort: any miss leaves corrections_updated absent so the review UI falls
|
||||
back to its client-side on-load auto-apply.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services.auto_approval.pre_apply import ensure_and_pre_apply
|
||||
|
||||
|
||||
def _corrections() -> Dict[str, Any]:
|
||||
words = [
|
||||
{"id": f"w{i}", "text": t, "start_time": i * 0.5, "end_time": i * 0.5 + 0.4}
|
||||
for i, t in enumerate(["an", "amateur", "here"])
|
||||
]
|
||||
return {
|
||||
"corrected_segments": [{
|
||||
"id": "s0",
|
||||
"text": "an amateur here",
|
||||
"words": words,
|
||||
"start_time": 0.0,
|
||||
"end_time": 2.0,
|
||||
}],
|
||||
"reference_lyrics": {"spotify": {"segments": []}},
|
||||
"metadata": {"total_words": 3},
|
||||
}
|
||||
|
||||
|
||||
def _replace_suggestion() -> Dict[str, Any]:
|
||||
# Replace "an amateur" -> "not much" (op=replace on the first two words).
|
||||
return {
|
||||
"id": "sug1",
|
||||
"op": "replace",
|
||||
"segment_ids": ["s0"],
|
||||
"word_ids": ["w0", "w1"],
|
||||
"original_text": "an amateur",
|
||||
"new_text": "not much",
|
||||
"category": "mishearing",
|
||||
"confidence": 0.95,
|
||||
"models": ["m1"],
|
||||
"consensus": 1,
|
||||
"total_models": 1,
|
||||
}
|
||||
|
||||
|
||||
class _FakeStorage:
|
||||
def __init__(self, files: Dict[str, Any]):
|
||||
self._files = dict(files)
|
||||
self.uploads: Dict[str, Any] = {}
|
||||
|
||||
def file_exists(self, path: str) -> bool:
|
||||
return path in self._files
|
||||
|
||||
def download_json(self, path: str):
|
||||
return self._files[path]
|
||||
|
||||
def list_files(self, prefix: str) -> List[str]:
|
||||
return [p for p in self._files if p.startswith(prefix)]
|
||||
|
||||
def upload_json(self, path: str, data: Any, if_generation_match=None):
|
||||
# Model create-only semantics: if_generation_match=0 fails when the object
|
||||
# already exists (mirrors GCS raising PreconditionFailed).
|
||||
if if_generation_match == 0 and path in self._files:
|
||||
from google.api_core.exceptions import PreconditionFailed
|
||||
raise PreconditionFailed("object exists")
|
||||
self.uploads[path] = data
|
||||
self._files[path] = data
|
||||
|
||||
|
||||
async def _run(storage, *, proactive=True, generate_on_miss=True):
|
||||
settings = MagicMock(auto_correct_proactive_enabled=proactive)
|
||||
jm = MagicMock()
|
||||
generated = {"called": False}
|
||||
|
||||
async def _fake_generate(job_id):
|
||||
generated["called"] = True
|
||||
return {"status": "generated"}
|
||||
|
||||
with patch("backend.config.get_settings", return_value=settings), \
|
||||
patch("backend.services.storage_service.StorageService", return_value=storage), \
|
||||
patch("backend.services.job_manager.JobManager", return_value=jm), \
|
||||
patch("backend.workers.auto_correct_worker.process_proactive_auto_correct", _fake_generate):
|
||||
result = await ensure_and_pre_apply("j1", generate_on_miss=generate_on_miss)
|
||||
return result, jm, generated
|
||||
|
||||
|
||||
CORR = "jobs/j1/lyrics/corrections.json"
|
||||
UPD = "jobs/j1/lyrics/corrections_updated.json"
|
||||
CACHE = "jobs/j1/lyrics/auto_correct_cache/x.json"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pre_apply_writes_marker_and_applies():
|
||||
storage = _FakeStorage({
|
||||
CORR: _corrections(),
|
||||
CACHE: {"suggestions": [_replace_suggestion()]},
|
||||
})
|
||||
result, jm, _gen = await _run(storage)
|
||||
assert result["outcome"] == "pre_applied"
|
||||
assert result["applied"] == 1
|
||||
written = storage.uploads[UPD]
|
||||
aa = written["metadata"]["auto_approval"]
|
||||
assert aa["pre_applied"] is True
|
||||
assert aa["applied_suggestion_ids"] == ["sug1"]
|
||||
assert aa["suggestions"] # carried for the UI panel
|
||||
# The correction was actually applied to the segments.
|
||||
assert "not much" in written["corrected_segments"][0]["text"]
|
||||
jm.update_file_url.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pre_apply_empty_suggestions_still_marks():
|
||||
# Known-empty cache: mark pre_applied so the UI doesn't run client-side.
|
||||
storage = _FakeStorage({CORR: _corrections(), CACHE: {"suggestions": []}})
|
||||
result, _, _gen = await _run(storage)
|
||||
assert result["outcome"] == "pre_applied"
|
||||
assert result["applied"] == 0
|
||||
assert storage.uploads[UPD]["metadata"]["auto_approval"]["pre_applied"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pre_apply_no_cache_and_proactive_disabled_is_noop():
|
||||
# No cache + proactive off -> unknown suggestion set -> do NOT mark (fall back).
|
||||
storage = _FakeStorage({CORR: _corrections()})
|
||||
result, _, _gen = await _run(storage, proactive=False)
|
||||
assert result["outcome"] == "skipped"
|
||||
assert result["reason"] == "no_suggestions_cache"
|
||||
assert UPD not in storage.uploads
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pre_apply_skips_when_already_applied():
|
||||
storage = _FakeStorage({
|
||||
CORR: _corrections(),
|
||||
UPD: {"metadata": {"auto_approval": {"auto_approved": True}}},
|
||||
CACHE: {"suggestions": [_replace_suggestion()]},
|
||||
})
|
||||
result, _, _gen = await _run(storage)
|
||||
assert result["outcome"] == "skipped"
|
||||
assert result["reason"] == "already_applied"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pre_apply_no_corrections_is_noop():
|
||||
storage = _FakeStorage({})
|
||||
result, _, _gen = await _run(storage)
|
||||
assert result["outcome"] == "skipped"
|
||||
assert result["reason"] == "no_corrections"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_load_path_applies_existing_cache_without_generating():
|
||||
# generate_on_miss=False (the /correction-data load path): an existing cache is
|
||||
# applied, but generation is never triggered (page must not block on an LLM call).
|
||||
storage = _FakeStorage({
|
||||
CORR: _corrections(),
|
||||
CACHE: {"suggestions": [_replace_suggestion()]},
|
||||
})
|
||||
result, jm, gen = await _run(storage, generate_on_miss=False)
|
||||
assert result["outcome"] == "pre_applied"
|
||||
assert gen["called"] is False
|
||||
assert storage.uploads[UPD]["metadata"]["auto_approval"]["pre_applied"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_load_path_cache_miss_does_not_generate_or_mark():
|
||||
# No cache + proactive ON but generate_on_miss=False -> no generation, no marker;
|
||||
# the UI falls back to its client-side apply (no page hang).
|
||||
storage = _FakeStorage({CORR: _corrections()})
|
||||
result, _, gen = await _run(storage, proactive=True, generate_on_miss=False)
|
||||
assert gen["called"] is False
|
||||
assert result["outcome"] == "skipped"
|
||||
assert result["reason"] == "no_suggestions_cache"
|
||||
assert UPD not in storage.uploads
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_screens_path_generates_on_cache_miss():
|
||||
# Default generate_on_miss=True (screens_worker path): generation IS triggered
|
||||
# on a cache miss.
|
||||
storage = _FakeStorage({CORR: _corrections()})
|
||||
result, _, gen = await _run(storage, proactive=True, generate_on_miss=True)
|
||||
assert gen["called"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pre_apply_raced_concurrent_write_does_not_clobber():
|
||||
# A concurrent writer created corrections_updated.json AFTER our existence check
|
||||
# (invisible to the check, present for the create-only upload) -> theirs wins.
|
||||
storage = _FakeStorage({
|
||||
CORR: _corrections(),
|
||||
CACHE: {"suggestions": [_replace_suggestion()]},
|
||||
UPD: {"metadata": {}, "corrected_segments": [{"id": "s0", "words": [{"id": "x"}]}]},
|
||||
})
|
||||
orig_exists = storage.file_exists
|
||||
storage.file_exists = lambda p: False if p == UPD else orig_exists(p)
|
||||
result, _, _gen = await _run(storage)
|
||||
assert result["outcome"] == "skipped"
|
||||
assert result["reason"] == "raced_concurrent_write"
|
||||
# The concurrent writer's content is untouched.
|
||||
assert storage._files[UPD]["metadata"] == {}
|
||||
@@ -0,0 +1,364 @@
|
||||
"""Tests for the auto-approvability scorer.
|
||||
|
||||
These fixtures mirror the shape of a production ``corrections.json`` built by the
|
||||
uncorrected controller path (auto-correction disabled): ``corrections_made == 0``,
|
||||
``confidence == 1.0``, but anchors/gaps/reference_lyrics still populated.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from backend.services.auto_approval.models import BackingVerdict, LyricsVerdict
|
||||
from backend.services.auto_approval.scorer import (
|
||||
score_backing,
|
||||
score_job,
|
||||
score_lyrics,
|
||||
)
|
||||
|
||||
|
||||
def _word(wid: str, text: str) -> Dict[str, Any]:
|
||||
return {"id": wid, "text": text, "start_time": 0.0, "end_time": 0.5}
|
||||
|
||||
|
||||
def _segments(n_words: int) -> List[Dict[str, Any]]:
|
||||
words = [_word(f"w{i}", f"word{i}") for i in range(n_words)]
|
||||
return [{"id": "s0", "text": " ".join(w["text"] for w in words),
|
||||
"words": words, "start_time": 0.0, "end_time": 10.0}]
|
||||
|
||||
|
||||
def _corrections_json(
|
||||
n_words: int = 20,
|
||||
anchor_words: int = 20,
|
||||
gap_words: int = 0,
|
||||
synced: bool = True,
|
||||
sources: List[str] | None = None,
|
||||
) -> Dict[str, Any]:
|
||||
sources = sources if sources is not None else ["spotify", "genius"]
|
||||
anchor_seq = [{"id": "a0", "transcribed_word_ids": [f"w{i}" for i in range(anchor_words)]}]
|
||||
gap_seq = (
|
||||
[{"id": "g0", "transcribed_word_ids": [f"w{i}" for i in range(anchor_words, anchor_words + gap_words)]}]
|
||||
if gap_words
|
||||
else []
|
||||
)
|
||||
reference_lyrics = {
|
||||
src: {"metadata": {"is_synced": synced}, "segments": [], "source": src}
|
||||
for src in sources
|
||||
}
|
||||
return {
|
||||
"corrected_segments": _segments(n_words),
|
||||
"corrections": [],
|
||||
"corrections_made": 0,
|
||||
"confidence": 1.0, # the trap — must not drive AUTO
|
||||
"reference_lyrics": reference_lyrics,
|
||||
"anchor_sequences": anchor_seq,
|
||||
"gap_sequences": gap_seq,
|
||||
"metadata": {
|
||||
"correction_type": "none",
|
||||
"reason": "correction_disabled",
|
||||
"agentic_routing": "disabled",
|
||||
"total_words": n_words,
|
||||
"anchor_sequences_count": len(anchor_seq),
|
||||
"gap_sequences_count": len(gap_seq),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# --- Lyrics ---
|
||||
|
||||
def test_synced_perfect_is_auto() -> None:
|
||||
res = score_lyrics(_corrections_json(anchor_words=20, gap_words=0, synced=True))
|
||||
assert res.verdict == LyricsVerdict.AUTO
|
||||
assert res.tier == "synced-perfect"
|
||||
assert res.signals.anchor_word_fraction == 1.0
|
||||
assert res.signals.uncorrected_gap_fraction == 0.0
|
||||
|
||||
|
||||
def test_confidence_one_alone_does_not_trigger_auto() -> None:
|
||||
# No reference sources at all -> confidence 1.0 must NOT yield AUTO.
|
||||
data = _corrections_json(sources=[], anchor_words=0, gap_words=0)
|
||||
data["anchor_sequences"] = []
|
||||
res = score_lyrics(data)
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
assert res.tier == "no-reference"
|
||||
|
||||
|
||||
def test_unsynced_reference_never_auto() -> None:
|
||||
res = score_lyrics(_corrections_json(anchor_words=20, gap_words=0, synced=False))
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
assert res.tier == "near-miss"
|
||||
assert not res.signals.has_synced_reference
|
||||
|
||||
|
||||
def test_gaps_push_to_review() -> None:
|
||||
# 16 anchored / 4 gap of 20 -> 80% anchor, 20% gap -> needs-review.
|
||||
res = score_lyrics(_corrections_json(n_words=20, anchor_words=16, gap_words=4, synced=True))
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
assert res.tier == "needs-review"
|
||||
|
||||
|
||||
def test_single_gap_word_blocks_auto() -> None:
|
||||
# Regression for job 79c4f60c "Clarity": 241/242 anchored (99.6%), one gap word that
|
||||
# was a real mis-transcription. A single unresolved gap must NOT be auto-approved.
|
||||
data = _corrections_json(n_words=242, anchor_words=241, gap_words=1, synced=True)
|
||||
res = score_lyrics(data)
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
assert res.signals.gap_word_count == 1
|
||||
|
||||
|
||||
def test_near_miss_band() -> None:
|
||||
# 19 anchored / 1 gap of 20 -> 95% anchor, 5% gap: within near-miss, below AUTO.
|
||||
res = score_lyrics(_corrections_json(n_words=20, anchor_words=19, gap_words=1, synced=True))
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
assert res.tier == "near-miss"
|
||||
|
||||
|
||||
def test_too_few_words() -> None:
|
||||
res = score_lyrics(_corrections_json(n_words=5, anchor_words=5, gap_words=0))
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
assert res.tier == "too-few-words"
|
||||
|
||||
|
||||
# --- AI-resolved tier (gap words covered by auto-applied suggestions) ---
|
||||
|
||||
def _suggestions_for_gaps(data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
||||
gap_ids = [wid for seq in data["gap_sequences"] for wid in seq["transcribed_word_ids"]]
|
||||
return [
|
||||
{"id": f"sug{i}", "op": "replace", "word_ids": [wid], "segment_ids": ["s0"],
|
||||
"original_text": "x", "new_text": "y", "confidence": 0.9,
|
||||
"consensus": 2, "total_models": 2}
|
||||
for i, wid in enumerate(gap_ids)
|
||||
]
|
||||
|
||||
|
||||
def test_ai_covered_gaps_are_auto_resolved() -> None:
|
||||
# 95% anchored with 5 gap words, every gap covered by an auto-applied AI
|
||||
# suggestion -> the post-AI state is clean -> AUTO (ai-resolved tier).
|
||||
data = _corrections_json(n_words=100, anchor_words=95, gap_words=5, synced=True)
|
||||
res = score_lyrics(data, _suggestions_for_gaps(data))
|
||||
assert res.verdict == LyricsVerdict.AUTO
|
||||
assert res.tier == "ai-resolved"
|
||||
assert res.signals.gap_words_covered_by_ai == 5
|
||||
assert res.signals.uncovered_gap_word_count == 0
|
||||
assert res.signals.ai_full_consensus_count == 5
|
||||
|
||||
|
||||
def test_uncovered_gaps_beyond_threshold_stay_review() -> None:
|
||||
# 10 gaps, none covered -> 10% uncovered -> review.
|
||||
data = _corrections_json(n_words=100, anchor_words=90, gap_words=10, synced=True)
|
||||
res = score_lyrics(data, [])
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
assert res.signals.uncovered_gap_word_count == 10
|
||||
|
||||
|
||||
def test_no_suggestion_data_never_ai_resolved() -> None:
|
||||
# Without the suggestion cache we can't know what the AI will fix -> the
|
||||
# ai-resolved tier must not apply (only the strict zero-gap tier can).
|
||||
data = _corrections_json(n_words=100, anchor_words=95, gap_words=5, synced=True)
|
||||
res = score_lyrics(data, None)
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
assert not res.signals.ai_suggestions_available
|
||||
|
||||
|
||||
def test_gates_override_ai_resolution() -> None:
|
||||
# Even with every gap covered, a vocalization section still gates to human.
|
||||
data = _corrections_json(n_words=100, anchor_words=95, gap_words=5, synced=True)
|
||||
voc = [_timed_word(f"v{i}", t, 10.0 + i * 0.4, 10.3 + i * 0.4)
|
||||
for i, t in enumerate(["Da-", "da-", "dun,", "da-", "da-", "dun"])]
|
||||
data = _with_extra_segment(data, voc, 10.0, 12.5)
|
||||
res = score_lyrics(data, _suggestions_for_gaps(data))
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
assert res.tier == "vocalization-gate"
|
||||
|
||||
|
||||
def test_low_anchor_never_ai_resolved() -> None:
|
||||
# Heavy correction of a messy transcription (corpus f247364e: 47.6% anchor,
|
||||
# nearly all gaps covered) still means likely uncaught errors -> review.
|
||||
data = _corrections_json(n_words=100, anchor_words=48, gap_words=52, synced=True)
|
||||
sugs = _suggestions_for_gaps(data)[:50] # 50 of 52 covered
|
||||
res = score_lyrics(data, sugs)
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
|
||||
|
||||
# --- Never-auto gating classes (Pattern 3 vocalizations, Pattern 8 phantoms) ---
|
||||
|
||||
def _timed_word(wid: str, text: str, start: float, end: float) -> Dict[str, Any]:
|
||||
return {"id": wid, "text": text, "start_time": start, "end_time": end}
|
||||
|
||||
|
||||
def _with_extra_segment(data: Dict[str, Any], words: List[Dict[str, Any]],
|
||||
seg_start: float, seg_end: float,
|
||||
anchored: bool = True) -> Dict[str, Any]:
|
||||
"""Append a segment and (optionally) anchor its words so gates are the only blocker."""
|
||||
data["corrected_segments"].append({
|
||||
"id": f"s{len(data['corrected_segments'])}",
|
||||
"text": " ".join(w["text"] for w in words),
|
||||
"words": words,
|
||||
"start_time": seg_start,
|
||||
"end_time": seg_end,
|
||||
})
|
||||
if anchored:
|
||||
data["anchor_sequences"][0]["transcribed_word_ids"].extend(w["id"] for w in words)
|
||||
data["metadata"]["total_words"] += len(words)
|
||||
return data
|
||||
|
||||
|
||||
def test_vocalization_run_gates_even_when_otherwise_perfect() -> None:
|
||||
# b5a7b8aa "Two Birds": lines of "Da- da- dun, da- da- dun" — anchored or not,
|
||||
# the grouping/timing is a musical judgement -> never fully auto.
|
||||
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
|
||||
voc = [_timed_word(f"v{i}", t, 10.0 + i * 0.4, 10.3 + i * 0.4)
|
||||
for i, t in enumerate(["Da-", "da-", "dun,", "da-", "da-", "dun"])]
|
||||
data = _with_extra_segment(data, voc, 10.0, 12.5)
|
||||
res = score_lyrics(data)
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
assert res.tier == "vocalization-gate"
|
||||
assert res.signals.has_vocalization_section
|
||||
assert res.signals.vocalization_max_run == 6
|
||||
|
||||
|
||||
def test_single_very_long_vocalization_gates() -> None:
|
||||
# 8f2305ee seg 35: a single "Ooh," spanning 10.1s = many vocalizations lumped into one.
|
||||
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
|
||||
data = _with_extra_segment(data, [_timed_word("v0", "Ooh,", 100.0, 110.1)], 100.0, 110.1)
|
||||
res = score_lyrics(data)
|
||||
assert res.tier == "vocalization-gate"
|
||||
assert res.signals.long_vocalization_word_count == 1
|
||||
|
||||
|
||||
def test_two_multi_second_vocalizations_gate() -> None:
|
||||
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
|
||||
data = _with_extra_segment(
|
||||
data,
|
||||
[_timed_word("v0", "Ooh,", 100.0, 104.0), _timed_word("v1", "ooh", 105.0, 109.1)],
|
||||
100.0, 109.1,
|
||||
)
|
||||
res = score_lyrics(data)
|
||||
assert res.tier == "vocalization-gate"
|
||||
|
||||
|
||||
def test_few_normal_vocalization_words_do_not_gate() -> None:
|
||||
# A couple of short "oh yeah"s in a normal song must not trip the gate.
|
||||
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
|
||||
data = _with_extra_segment(
|
||||
data,
|
||||
[_timed_word("v0", "Oh,", 50.0, 50.4), _timed_word("v1", "yeah", 50.4, 50.9)],
|
||||
50.0, 50.9,
|
||||
)
|
||||
res = score_lyrics(data)
|
||||
assert res.verdict == LyricsVerdict.AUTO
|
||||
assert not res.signals.has_vocalization_section
|
||||
|
||||
|
||||
def test_absurd_word_duration_is_phantom_gate() -> None:
|
||||
# 33453fa0 "Angel": phantom "(I'm sorry)" line with a 7.4s word.
|
||||
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
|
||||
data = _with_extra_segment(
|
||||
data, [_timed_word("p0", "sorry", 0.0, 7.4)], 0.0, 7.4,
|
||||
)
|
||||
res = score_lyrics(data)
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
assert res.tier == "phantom-gate"
|
||||
assert res.signals.absurd_duration_word_count == 1
|
||||
assert res.signals.max_word_duration_s == 7.4
|
||||
|
||||
|
||||
def test_stretched_short_parenthetical_is_phantom_gate() -> None:
|
||||
# Short parenthetical line spanning several seconds, individual words normal-length.
|
||||
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
|
||||
data = _with_extra_segment(
|
||||
data,
|
||||
[_timed_word("p0", "(I'm", 0.0, 0.4), _timed_word("p1", "sorry)", 4.4, 4.8)],
|
||||
0.0, 4.8,
|
||||
)
|
||||
res = score_lyrics(data)
|
||||
assert res.tier == "phantom-gate"
|
||||
assert res.signals.suspicious_parenthetical_count == 1
|
||||
|
||||
|
||||
def test_normal_parenthetical_backing_bit_does_not_gate() -> None:
|
||||
# Pattern 7 trailing "(Dreaming)" bits are left alone — a short parenthetical with
|
||||
# a normal duration must not be treated as a phantom.
|
||||
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
|
||||
data = _with_extra_segment(
|
||||
data, [_timed_word("p0", "(Dreaming)", 60.0, 61.2)], 60.0, 61.2,
|
||||
)
|
||||
res = score_lyrics(data)
|
||||
assert res.verdict == LyricsVerdict.AUTO
|
||||
|
||||
|
||||
def test_verdict_to_dict_is_json_safe() -> None:
|
||||
import json
|
||||
|
||||
v = score_job(
|
||||
_corrections_json(anchor_words=20, gap_words=0, synced=True),
|
||||
{"has_audible_content": False, "audible_percentage": 0.0, "audible_segments": []},
|
||||
)
|
||||
d = v.to_dict()
|
||||
json.dumps(d) # must not raise (enums converted to plain strings)
|
||||
assert d["lyrics"]["verdict"] == "auto"
|
||||
assert d["backing"]["verdict"] == "clean"
|
||||
|
||||
|
||||
# --- Backing ---
|
||||
|
||||
def test_no_audible_backing_is_non_subjective_clean() -> None:
|
||||
res = score_backing({"has_audible_content": False, "audible_percentage": 0.0,
|
||||
"audible_segments": [], "recommended_selection": "clean"})
|
||||
assert res.verdict == BackingVerdict.CLEAN
|
||||
assert res.non_subjective is True
|
||||
|
||||
|
||||
def test_near_silent_backing_is_clean() -> None:
|
||||
res = score_backing({"has_audible_content": True, "audible_percentage": 0.3,
|
||||
"audible_segments": [{"avg_amplitude_db": -35.0}],
|
||||
"recommended_selection": "clean"})
|
||||
assert res.verdict == BackingVerdict.CLEAN
|
||||
assert res.non_subjective is True
|
||||
|
||||
|
||||
def test_audible_backing_is_subjective_review() -> None:
|
||||
res = score_backing({"has_audible_content": True, "audible_percentage": 42.0,
|
||||
"audible_segments": [{"avg_amplitude_db": -12.0, "peak_amplitude_db": -6.0}],
|
||||
"recommended_selection": "with_backing"})
|
||||
assert res.verdict == BackingVerdict.REVIEW
|
||||
assert res.non_subjective is False
|
||||
assert res.signals.loud_segment_count == 1
|
||||
|
||||
|
||||
def test_missing_backing_analysis_is_review() -> None:
|
||||
res = score_backing(None)
|
||||
assert res.verdict == BackingVerdict.REVIEW
|
||||
assert res.non_subjective is False
|
||||
|
||||
|
||||
def test_errored_backing_analysis_is_review_not_clean() -> None:
|
||||
# A failed analysis stores has_audible_content=None + analysis_error; it
|
||||
# must NOT read as "no audible content" (that would wrongly auto-pick clean).
|
||||
res = score_backing({
|
||||
"has_audible_content": None,
|
||||
"analysis_error": "download failed",
|
||||
"recommended_selection": "clean",
|
||||
})
|
||||
assert res.verdict == BackingVerdict.REVIEW
|
||||
assert res.non_subjective is False
|
||||
assert res.signals.analysis_present is False
|
||||
|
||||
|
||||
# --- Combined ---
|
||||
|
||||
def test_overall_auto_requires_both() -> None:
|
||||
v = score_job(
|
||||
_corrections_json(anchor_words=20, gap_words=0, synced=True),
|
||||
{"has_audible_content": False, "audible_percentage": 0.0, "audible_segments": []},
|
||||
)
|
||||
assert v.overall_auto is True
|
||||
|
||||
|
||||
def test_overall_not_auto_when_backing_subjective() -> None:
|
||||
v = score_job(
|
||||
_corrections_json(anchor_words=20, gap_words=0, synced=True),
|
||||
{"has_audible_content": True, "audible_percentage": 30.0,
|
||||
"audible_segments": [{"avg_amplitude_db": -10.0}]},
|
||||
)
|
||||
assert v.lyrics.verdict == LyricsVerdict.AUTO
|
||||
assert v.overall_auto is False
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Tests for the pure 3-stem comparison signal extraction.
|
||||
|
||||
Synthesizes tiny WAVs with pydub so the signal math is exercised on real
|
||||
audio decoding, not mocks.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
from pydub import AudioSegment
|
||||
from pydub.generators import Sine, WhiteNoise
|
||||
|
||||
from karaoke_gen.instrumental_review.stem_comparison import (
|
||||
StemComparison,
|
||||
compare_stems,
|
||||
)
|
||||
|
||||
|
||||
def _silence(ms: int = 4000) -> AudioSegment:
|
||||
return AudioSegment.silent(duration=ms, frame_rate=16000)
|
||||
|
||||
|
||||
def _tone_bursts(ms: int = 4000, *, burst_ms: int = 500, gain_db: float = -10.0) -> AudioSegment:
|
||||
"""Alternating 500ms tone / 500ms silence."""
|
||||
out = AudioSegment.silent(duration=0, frame_rate=16000)
|
||||
tone = Sine(440, sample_rate=16000).to_audio_segment(duration=burst_ms).apply_gain(gain_db)
|
||||
quiet = AudioSegment.silent(duration=burst_ms, frame_rate=16000)
|
||||
while len(out) < ms:
|
||||
out += tone + quiet
|
||||
return out[:ms]
|
||||
|
||||
|
||||
def _write(tmp_path, name: str, audio: AudioSegment) -> str:
|
||||
path = os.path.join(tmp_path, name)
|
||||
audio.export(path, format="wav")
|
||||
return path
|
||||
|
||||
|
||||
def test_silent_backing_has_zero_fractions(tmp_path) -> None:
|
||||
backing = _write(tmp_path, "b.wav", _silence())
|
||||
lead = _write(tmp_path, "l.wav", _tone_bursts())
|
||||
vocals = _write(tmp_path, "v.wav", _tone_bursts())
|
||||
c = compare_stems(backing, lead, vocals)
|
||||
assert c.error is None
|
||||
assert c.backing_audible_fraction == 0.0
|
||||
assert c.coverage_ratio == 0.0
|
||||
assert c.lead_overlap_fraction == 0.0
|
||||
assert c.lead_audible_fraction > 0.3
|
||||
|
||||
|
||||
def test_backing_identical_to_vocals_is_high_corr_full_coverage(tmp_path) -> None:
|
||||
# The backing-stem-is-the-lead shape: backing tracks the whole vocal line
|
||||
# while the lead stem is empty.
|
||||
bursts = _tone_bursts()
|
||||
backing = _write(tmp_path, "b.wav", bursts)
|
||||
lead = _write(tmp_path, "l.wav", _silence())
|
||||
vocals = _write(tmp_path, "v.wav", bursts)
|
||||
c = compare_stems(backing, lead, vocals)
|
||||
assert c.error is None
|
||||
assert c.coverage_ratio == 1.0
|
||||
assert c.corr_backing_vocals > 0.95
|
||||
assert c.backing_audible_fraction > c.lead_audible_fraction
|
||||
assert c.lead_overlap_fraction == 0.0
|
||||
|
||||
|
||||
def test_offset_backing_has_low_overlap_and_corr(tmp_path) -> None:
|
||||
# Backing sings only in the lead's gaps (genuine call-and-response shape).
|
||||
bursts = _tone_bursts()
|
||||
offset = _silence(500) + bursts
|
||||
backing = _write(tmp_path, "b.wav", offset[: len(bursts)])
|
||||
lead = _write(tmp_path, "l.wav", bursts)
|
||||
vocals = _write(tmp_path, "v.wav", bursts)
|
||||
c = compare_stems(backing, lead, vocals)
|
||||
assert c.error is None
|
||||
assert c.corr_backing_vocals < 0.0 # anti-phase with the vocal line
|
||||
assert c.lead_overlap_fraction < 0.2
|
||||
|
||||
|
||||
def test_continuous_noise_floor_is_flat(tmp_path) -> None:
|
||||
noise = WhiteNoise(sample_rate=16000).to_audio_segment(duration=8000).apply_gain(-25.0)
|
||||
backing = _write(tmp_path, "b.wav", noise)
|
||||
lead = _write(tmp_path, "l.wav", _tone_bursts(8000))
|
||||
vocals = _write(tmp_path, "v.wav", _tone_bursts(8000))
|
||||
c = compare_stems(backing, lead, vocals)
|
||||
assert c.error is None
|
||||
assert c.backing_audible_fraction == 1.0
|
||||
assert c.flat_fraction > 0.9 # sustained low-variance content
|
||||
assert c.backing_db_std < 2.5
|
||||
|
||||
|
||||
def test_missing_file_reports_error_not_raise(tmp_path) -> None:
|
||||
lead = _write(tmp_path, "l.wav", _silence(500))
|
||||
c = compare_stems(os.path.join(tmp_path, "nope.wav"), lead, lead)
|
||||
assert isinstance(c, StemComparison)
|
||||
assert c.error is not None
|
||||
|
||||
|
||||
def test_to_dict_round_trips_json_safe(tmp_path) -> None:
|
||||
import json
|
||||
|
||||
p = _write(tmp_path, "a.wav", _tone_bursts(1000))
|
||||
c = compare_stems(p, p, p)
|
||||
payload = c.to_dict()
|
||||
assert json.loads(json.dumps(payload)) == payload
|
||||
@@ -0,0 +1,481 @@
|
||||
"""Tests for the deterministic (no-LLM) suggestion generators + P1 conflict grouping.
|
||||
|
||||
Scenarios mirror the 2026-08 replay-review corpus jobs that motivated each
|
||||
pattern: P4 leading-connective over-insertion (8f2305ee "And they" -> "They"),
|
||||
P5 reference-majority resolution (6d0640fa "yo Mick," -> "Come here,"), and the
|
||||
P1 AI self-conflict (f6439692 insert+replace both adding "you're").
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from backend.services.auto_correct.deterministic import (
|
||||
deterministic_suggestions,
|
||||
leading_connective_suggestions,
|
||||
reference_majority_suggestions,
|
||||
_ref_word_streams,
|
||||
)
|
||||
from backend.services.auto_correct.service import (
|
||||
AutoCorrectService,
|
||||
Suggestion,
|
||||
_assign_conflict_groups,
|
||||
)
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
|
||||
def _ref_source(word_texts, prefix):
|
||||
"""A reference source with ids <prefix>0, <prefix>1, ..."""
|
||||
return {
|
||||
"segments": [
|
||||
{
|
||||
"text": " ".join(word_texts),
|
||||
"words": [
|
||||
{"id": f"{prefix}{i}", "text": t} for i, t in enumerate(word_texts)
|
||||
],
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def _seg(seg_id, words):
|
||||
return {
|
||||
"id": seg_id,
|
||||
"text": " ".join(t for _, t in words),
|
||||
"words": [{"id": wid, "text": t} for wid, t in words],
|
||||
}
|
||||
|
||||
|
||||
# ---- Pattern 4: leading connective ----
|
||||
|
||||
|
||||
def _p4_fixture(ref_line="They count everything", gap_ref_ids=None):
|
||||
"""Segment "And they count ..." where "And" is a gap word.
|
||||
|
||||
The single reference reads "They count everything" — no "And" — with the
|
||||
gap aligned to reference word r0 ("They") unless overridden.
|
||||
"""
|
||||
segments = [
|
||||
_seg("seg-0", [("w0", "And"), ("w1", "they"), ("w2", "count"), ("w3", "everything")])
|
||||
]
|
||||
refs = {"genius": _ref_source(ref_line.split(), "r")}
|
||||
correction_data = {
|
||||
"gap_sequences": [
|
||||
{
|
||||
"id": "gap-0",
|
||||
"transcribed_word_ids": ["w0"],
|
||||
"reference_word_ids": {"genius": gap_ref_ids if gap_ref_ids is not None else ["r0"]},
|
||||
}
|
||||
],
|
||||
"anchor_sequences": [],
|
||||
}
|
||||
return segments, refs, correction_data
|
||||
|
||||
|
||||
def test_p4_deletes_unsupported_leading_connective_and_recapitalizes() -> None:
|
||||
segments, refs, cd = _p4_fixture()
|
||||
out = deterministic_suggestions(segments, refs, cd)
|
||||
assert [s["op"] for s in out] == ["delete", "replace"]
|
||||
delete, recap = out
|
||||
assert delete["word_ids"] == ["w0"]
|
||||
assert delete["new_text"] == ""
|
||||
assert recap["word_ids"] == ["w1"]
|
||||
assert recap["new_text"] == "They"
|
||||
assert all(s["models"] == ["deterministic"] for s in out)
|
||||
|
||||
|
||||
def test_p4_skips_when_a_reference_supports_the_connective() -> None:
|
||||
segments, refs, cd = _p4_fixture(ref_line="And they count everything")
|
||||
out = deterministic_suggestions(segments, refs, cd)
|
||||
assert out == []
|
||||
|
||||
|
||||
def test_p4_skips_when_no_reference_evidence() -> None:
|
||||
# Gap aligned to nothing and no usable anchors -> no reading -> no delete.
|
||||
segments, refs, cd = _p4_fixture(gap_ref_ids=[])
|
||||
out = deterministic_suggestions(segments, refs, cd)
|
||||
assert out == []
|
||||
|
||||
|
||||
def test_p4_skips_anchored_leading_connective() -> None:
|
||||
segments, refs, cd = _p4_fixture()
|
||||
cd["gap_sequences"] = [] # "And" is not a gap word
|
||||
assert deterministic_suggestions(segments, refs, cd) == []
|
||||
|
||||
|
||||
def test_p4_skips_vocalization_run() -> None:
|
||||
# "Oh- whoa whoa whoa" — grouping vocalizations is a musical judgement.
|
||||
segments = [
|
||||
_seg("seg-0", [("w0", "Oh-"), ("w1", "whoa,"), ("w2", "whoa,"), ("w3", "whoa")])
|
||||
]
|
||||
refs = {"genius": _ref_source(["Whoa,", "whoa,", "whoa"], "r")}
|
||||
cd = {
|
||||
"gap_sequences": [
|
||||
{
|
||||
"id": "gap-0",
|
||||
"transcribed_word_ids": ["w0"],
|
||||
"reference_word_ids": {"genius": ["r0"]},
|
||||
}
|
||||
],
|
||||
"anchor_sequences": [],
|
||||
}
|
||||
assert deterministic_suggestions(segments, refs, cd) == []
|
||||
|
||||
|
||||
def test_p4_skips_two_word_segment() -> None:
|
||||
segments = [_seg("seg-0", [("w0", "And"), ("w1", "run")])]
|
||||
refs = {"genius": _ref_source(["Run"], "r")}
|
||||
cd = {
|
||||
"gap_sequences": [
|
||||
{"id": "g", "transcribed_word_ids": ["w0"], "reference_word_ids": {"genius": ["r0"]}}
|
||||
],
|
||||
"anchor_sequences": [],
|
||||
}
|
||||
assert deterministic_suggestions(segments, refs, cd) == []
|
||||
|
||||
|
||||
def test_p4_already_capitalized_next_word_gets_no_recap_suggestion() -> None:
|
||||
segments = [
|
||||
_seg("seg-0", [("w0", "And"), ("w1", "Mary"), ("w2", "sings"), ("w3", "loud")])
|
||||
]
|
||||
refs = {"genius": _ref_source(["Mary", "sings", "loud"], "r")}
|
||||
cd = {
|
||||
"gap_sequences": [
|
||||
{"id": "g", "transcribed_word_ids": ["w0"], "reference_word_ids": {"genius": ["r0"]}}
|
||||
],
|
||||
"anchor_sequences": [],
|
||||
}
|
||||
out = deterministic_suggestions(segments, refs, cd)
|
||||
assert [s["op"] for s in out] == ["delete"]
|
||||
|
||||
|
||||
# ---- Pattern 5: reference majority ----
|
||||
|
||||
|
||||
def _p5_fixture():
|
||||
"""The 6d0640fa shape: transcription "yo Mick," where genius aligned
|
||||
"My man," on the gap, and lrclib/spotify (unaligned on the gap) read
|
||||
"Come here," after the preceding anchor."""
|
||||
segments = [
|
||||
_seg(
|
||||
"seg-0",
|
||||
[
|
||||
("w0", "Hit"),
|
||||
("w1", "the"),
|
||||
("w2", "button,"),
|
||||
("w3", "yo"),
|
||||
("w4", "Mick,"),
|
||||
("w5", "come"),
|
||||
("w6", "on"),
|
||||
],
|
||||
)
|
||||
]
|
||||
refs = {
|
||||
"lrclib": _ref_source(["Hit", "the", "button,", "Come", "here,", "come", "on"], "l"),
|
||||
"spotify": _ref_source(["Hit", "the", "button,", "Come", "here,", "come", "on"], "s"),
|
||||
"genius": _ref_source(["Hit", "the", "button,", "My", "man,", "come", "on"], "g"),
|
||||
}
|
||||
correction_data = {
|
||||
"gap_sequences": [
|
||||
{
|
||||
"id": "gap-0",
|
||||
"transcribed_word_ids": ["w3", "w4"],
|
||||
"preceding_anchor_id": "anchor-0",
|
||||
"following_anchor_id": None,
|
||||
"reference_word_ids": {"lrclib": [], "spotify": [], "genius": ["g3", "g4"]},
|
||||
}
|
||||
],
|
||||
"anchor_sequences": [
|
||||
{
|
||||
"id": "anchor-0",
|
||||
"transcribed_word_ids": ["w0", "w1", "w2"],
|
||||
"reference_word_ids": {
|
||||
"lrclib": ["l0", "l1", "l2"],
|
||||
"spotify": ["s0", "s1", "s2"],
|
||||
"genius": ["g0", "g1", "g2"],
|
||||
},
|
||||
}
|
||||
],
|
||||
}
|
||||
return segments, refs, correction_data
|
||||
|
||||
|
||||
def test_p5_replaces_implausible_proper_noun_with_majority_reading() -> None:
|
||||
segments, refs, cd = _p5_fixture()
|
||||
out = deterministic_suggestions(segments, refs, cd)
|
||||
assert len(out) == 1
|
||||
s = out[0]
|
||||
assert s["op"] == "replace"
|
||||
assert s["word_ids"] == ["w3", "w4"]
|
||||
assert s["new_text"] == "Come here,"
|
||||
assert "Mick," in s["reason"]
|
||||
|
||||
|
||||
def test_p5_requires_the_red_flag_token() -> None:
|
||||
# Same majority disagreement but the transcription is plausible lowercase
|
||||
# ("though" vs 2/3 "dog") -> the human deliberately leaves these; so do we.
|
||||
segments, refs, cd = _p5_fixture()
|
||||
segments[0]["words"][3]["text"] = "yo"
|
||||
segments[0]["words"][4]["text"] = "mick,"
|
||||
assert deterministic_suggestions(segments, refs, cd) == []
|
||||
|
||||
|
||||
def test_p5_skips_spelling_variant_of_reference_token() -> None:
|
||||
# "Crick" ~ "Cricket": a truncation/spelling variant, the LLM's fix.
|
||||
segments, refs, cd = _p5_fixture()
|
||||
segments[0]["words"][4]["text"] = "Herre," # close to reference "here,"
|
||||
assert deterministic_suggestions(segments, refs, cd) == []
|
||||
|
||||
|
||||
def test_p5_requires_two_thirds_majority() -> None:
|
||||
segments, refs, cd = _p5_fixture()
|
||||
# Make spotify read something else -> no 2/3 agreement.
|
||||
for w, t in zip(refs["spotify"]["segments"][0]["words"][3:5], ["Over", "there,"]):
|
||||
w["text"] = t
|
||||
assert deterministic_suggestions(segments, refs, cd) == []
|
||||
|
||||
|
||||
def test_p5_ignores_segment_initial_capitalization() -> None:
|
||||
# A capitalized SEGMENT-FIRST word is sentence case, not a proper noun.
|
||||
segments = [_seg("seg-0", [("w0", "Mick,"), ("w1", "come"), ("w2", "on")])]
|
||||
refs = {
|
||||
"lrclib": _ref_source(["Quick,", "come", "on"], "l"),
|
||||
"spotify": _ref_source(["Quick,", "come", "on"], "s"),
|
||||
"genius": _ref_source(["Slick,", "come", "on"], "g"),
|
||||
}
|
||||
cd = {
|
||||
"gap_sequences": [
|
||||
{
|
||||
"id": "gap-0",
|
||||
"transcribed_word_ids": ["w0"],
|
||||
"reference_word_ids": {"lrclib": ["l0"], "spotify": ["s0"], "genius": ["g0"]},
|
||||
}
|
||||
],
|
||||
"anchor_sequences": [],
|
||||
}
|
||||
assert deterministic_suggestions(segments, refs, cd) == []
|
||||
|
||||
|
||||
def test_p5_skips_stale_gap_word_ids() -> None:
|
||||
segments, refs, cd = _p5_fixture()
|
||||
cd["gap_sequences"][0]["transcribed_word_ids"] = ["w3", "gone"]
|
||||
assert deterministic_suggestions(segments, refs, cd) == []
|
||||
|
||||
|
||||
def test_generators_never_raise_on_garbage() -> None:
|
||||
assert deterministic_suggestions([], {}, None) == []
|
||||
assert deterministic_suggestions([{"weird": True}], {"x": {}}, {"gap_sequences": [{}]}) == []
|
||||
|
||||
|
||||
# ---- Pattern 1: insert/replace self-conflict grouping ----
|
||||
|
||||
|
||||
def _s(id_, op, word_ids, new_text, confidence=0.9, consensus=1):
|
||||
return Suggestion(
|
||||
id=id_,
|
||||
op=op,
|
||||
word_ids=word_ids,
|
||||
segment_ids=["seg-0"],
|
||||
original_text="fire" if op != "insert_after" else "",
|
||||
new_text=new_text,
|
||||
reason="r",
|
||||
category="mishearing",
|
||||
confidence=confidence,
|
||||
models=["m"],
|
||||
consensus=consensus,
|
||||
total_models=1,
|
||||
conflict_group=None,
|
||||
)
|
||||
|
||||
|
||||
def test_p1_insert_and_replace_adding_same_token_share_a_group() -> None:
|
||||
# f6439692: insert_after "fire" -> "you're" AND replace "fire" ->
|
||||
# "fire, you're" both applied -> "you're you're". Must become a conflict.
|
||||
insert = _s("i", "insert_after", ["w-fire"], "you're", confidence=0.75)
|
||||
replace = _s("r", "replace", ["w-fire"], "fire, you're", confidence=0.95)
|
||||
suggestions = [insert, replace]
|
||||
_assign_conflict_groups(suggestions)
|
||||
assert insert.conflict_group is not None
|
||||
assert insert.conflict_group == replace.conflict_group
|
||||
|
||||
|
||||
def test_p1_disjoint_tokens_stay_independent() -> None:
|
||||
# Replacing a word AND inserting different text after it is legitimate.
|
||||
insert = _s("i", "insert_after", ["w-fire"], "gasoline")
|
||||
replace = _s("r", "replace", ["w-fire"], "fire,")
|
||||
suggestions = [insert, replace]
|
||||
_assign_conflict_groups(suggestions)
|
||||
assert insert.conflict_group is None
|
||||
assert replace.conflict_group is None
|
||||
|
||||
|
||||
def test_p1_two_inserts_same_anchor_same_token_share_a_group() -> None:
|
||||
a = _s("a", "insert_after", ["w-fire"], "you're")
|
||||
b = _s("b", "insert_after", ["w-fire"], "you're baby")
|
||||
suggestions = [a, b]
|
||||
_assign_conflict_groups(suggestions)
|
||||
assert a.conflict_group is not None
|
||||
assert a.conflict_group == b.conflict_group
|
||||
|
||||
|
||||
def test_p1_insert_vs_delete_not_grouped() -> None:
|
||||
insert = _s("i", "insert_after", ["w-fire"], "you're")
|
||||
delete = _s("d", "delete", ["w-fire"], "")
|
||||
suggestions = [insert, delete]
|
||||
_assign_conflict_groups(suggestions)
|
||||
assert insert.conflict_group is None
|
||||
|
||||
|
||||
def test_assign_conflict_groups_is_idempotent_and_resets() -> None:
|
||||
a = _s("a", "replace", ["w1"], "x")
|
||||
b = _s("b", "replace", ["w2"], "y")
|
||||
a.conflict_group = b.conflict_group = "stale-group"
|
||||
suggestions = [a, b]
|
||||
_assign_conflict_groups(suggestions)
|
||||
assert a.conflict_group is None
|
||||
assert b.conflict_group is None
|
||||
|
||||
|
||||
def test_word_overlap_grouping_still_works() -> None:
|
||||
a = _s("a", "replace", ["w1", "w2"], "x")
|
||||
b = _s("b", "delete", ["w2"], "")
|
||||
suggestions = [a, b]
|
||||
_assign_conflict_groups(suggestions)
|
||||
assert a.conflict_group is not None
|
||||
assert a.conflict_group == b.conflict_group
|
||||
|
||||
|
||||
# ---- pipeline integration: suggest() folds deterministic suggestions in ----
|
||||
|
||||
|
||||
def _run_single_model(llm_suggestions, segments, refs, correction_data):
|
||||
service = AutoCorrectService()
|
||||
|
||||
def fake_call(model, system_prompt, user_prompt, *, job_id):
|
||||
return {"suggestions": llm_suggestions}, None
|
||||
|
||||
with 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=AutoCorrectSettings(),
|
||||
correction_data=correction_data,
|
||||
)
|
||||
|
||||
|
||||
def test_suggest_appends_deterministic_suggestions() -> None:
|
||||
segments, refs, cd = _p4_fixture()
|
||||
result = _run_single_model([], segments, refs, cd)
|
||||
assert [s.op for s in result.suggestions] == ["delete", "replace"]
|
||||
assert all(s.models == ["deterministic"] for s in result.suggestions)
|
||||
|
||||
|
||||
def test_suggest_dedupes_identical_llm_and_deterministic() -> None:
|
||||
segments, refs, cd = _p4_fixture()
|
||||
llm = [
|
||||
{
|
||||
"op": "delete",
|
||||
"start_idx": 0,
|
||||
"end_idx": 0,
|
||||
"new_text": "",
|
||||
"reason": "spurious leading word",
|
||||
"category": "mishearing",
|
||||
"confidence": 0.8,
|
||||
}
|
||||
]
|
||||
result = _run_single_model(llm, segments, refs, cd)
|
||||
deletes = [s for s in result.suggestions if s.op == "delete"]
|
||||
assert len(deletes) == 1
|
||||
assert "deterministic" in deletes[0].models
|
||||
assert deletes[0].confidence == 0.9 # bumped to the deterministic confidence
|
||||
# The deterministic generator counts as an agreeing source.
|
||||
assert deletes[0].consensus == 2
|
||||
assert deletes[0].total_models == 2
|
||||
assert deletes[0].consensus == len(deletes[0].models)
|
||||
|
||||
|
||||
def test_suggest_groups_conflicting_llm_and_deterministic() -> None:
|
||||
segments, refs, cd = _p4_fixture()
|
||||
llm = [
|
||||
{
|
||||
"op": "replace",
|
||||
"start_idx": 0,
|
||||
"end_idx": 0,
|
||||
"new_text": "And,",
|
||||
"reason": "punctuation",
|
||||
"category": "formatting",
|
||||
"confidence": 0.7,
|
||||
}
|
||||
]
|
||||
result = _run_single_model(llm, segments, refs, cd)
|
||||
on_w0 = [s for s in result.suggestions if s.word_ids == ["w0"]]
|
||||
assert len(on_w0) == 2
|
||||
assert on_w0[0].conflict_group is not None
|
||||
assert on_w0[0].conflict_group == on_w0[1].conflict_group
|
||||
|
||||
|
||||
def test_suggest_without_correction_data_still_works() -> None:
|
||||
segments, refs, _ = _p4_fixture()
|
||||
service = AutoCorrectService()
|
||||
|
||||
def fake_call(model, system_prompt, user_prompt, *, job_id):
|
||||
return {"suggestions": []}, None
|
||||
|
||||
with patch.object(service, "_cache_get", return_value=None), \
|
||||
patch.object(service, "_cache_put"), \
|
||||
patch.object(service, "_get_storage", side_effect=RuntimeError("no gcs")), \
|
||||
patch.object(service, "_call_model", side_effect=fake_call):
|
||||
result = service.suggest(
|
||||
job_id="job-1",
|
||||
segments=segments,
|
||||
reference_lyrics=refs,
|
||||
artist="A",
|
||||
title="T",
|
||||
settings=AutoCorrectSettings(),
|
||||
)
|
||||
assert result.suggestions == []
|
||||
|
||||
|
||||
def test_deterministic_respects_min_confidence_setting() -> None:
|
||||
segments, refs, cd = _p4_fixture()
|
||||
service = AutoCorrectService()
|
||||
|
||||
def fake_call(model, system_prompt, user_prompt, *, job_id):
|
||||
return {"suggestions": []}, None
|
||||
|
||||
with patch.object(service, "_cache_get", return_value=None), \
|
||||
patch.object(service, "_cache_put"), \
|
||||
patch.object(service, "_call_model", side_effect=fake_call):
|
||||
result = service.suggest(
|
||||
job_id="job-1",
|
||||
segments=segments,
|
||||
reference_lyrics=refs,
|
||||
artist="A",
|
||||
title="T",
|
||||
settings=AutoCorrectSettings(min_confidence=0.95),
|
||||
correction_data=cd,
|
||||
)
|
||||
assert result.suggestions == []
|
||||
|
||||
|
||||
# ---- module-level helpers ----
|
||||
|
||||
|
||||
def test_ref_word_streams_indexes_ids() -> None:
|
||||
streams = _ref_word_streams({"genius": _ref_source(["a", "b"], "g")})
|
||||
texts, index = streams["genius"]
|
||||
assert texts == ["a", "b"]
|
||||
assert index == {"g0": 0, "g1": 1}
|
||||
|
||||
|
||||
def test_direct_generator_calls_share_stream_shape() -> None:
|
||||
segments, refs, cd = _p4_fixture()
|
||||
streams = _ref_word_streams(refs)
|
||||
assert leading_connective_suggestions(segments, cd, streams)
|
||||
segments5, refs5, cd5 = _p5_fixture()
|
||||
streams5 = _ref_word_streams(refs5)
|
||||
assert reference_majority_suggestions(segments5, cd5, streams5)
|
||||
@@ -0,0 +1,190 @@
|
||||
"""
|
||||
Tests for POST /api/admin/orphaned-outputs/cleanup.
|
||||
|
||||
This endpoint deletes distributed outputs whose owning job doc no longer exists
|
||||
(a job deleted while its outputs were still published). Targets are explicit —
|
||||
YouTube video ID, Dropbox folder path, GDrive file IDs, kjbox mirror filename
|
||||
prefix — because there is no job doc left to resolve them from.
|
||||
|
||||
Origin: NOMAD-1583 duplicate incident (2026-08-29) — a job was deleted with its
|
||||
outputs still live, the brand code was recycled and reused, and the orphaned files
|
||||
had to be removed without any job record.
|
||||
"""
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.api.routes.admin import router
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
|
||||
|
||||
def get_mock_admin():
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Admin authenticated",
|
||||
user_email="admin@example.com",
|
||||
is_admin=True,
|
||||
)
|
||||
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
URL = "/api/admin/orphaned-outputs/cleanup"
|
||||
|
||||
|
||||
class TestOrphanedOutputsCleanupValidation:
|
||||
def test_no_targets_returns_400(self, client):
|
||||
response = client.post(URL, json={})
|
||||
assert response.status_code == 400
|
||||
assert "No cleanup targets" in response.json()["detail"]
|
||||
|
||||
@pytest.mark.parametrize("prefix", ["NOMAD-1583", "NOMAD-1583 - ", "Mazzy Star"])
|
||||
def test_unsafe_mirror_prefix_returns_400_before_any_cleanup(self, client, prefix):
|
||||
"""An unsafe mirror prefix fails the whole request up front — even the other
|
||||
(valid) targets must not run, so a bad call can be corrected and retried
|
||||
atomically."""
|
||||
with patch("backend.services.youtube_service.get_youtube_service") as mock_get_yt:
|
||||
response = client.post(URL, json={
|
||||
"youtube_video_id": "vid",
|
||||
"mirror_filename_prefix": prefix,
|
||||
})
|
||||
assert response.status_code == 400
|
||||
assert "mirror_filename_prefix" in response.json()["detail"]
|
||||
mock_get_yt.assert_not_called()
|
||||
|
||||
|
||||
class TestOrphanedOutputsCleanupYouTube:
|
||||
def test_deletes_youtube_video_by_id(self, client):
|
||||
mock_finalise = MagicMock()
|
||||
mock_finalise.delete_youtube_video.return_value = True
|
||||
mock_yt = MagicMock()
|
||||
mock_yt.is_configured = True
|
||||
mock_yt.get_credentials_dict.return_value = {"token": "x"}
|
||||
|
||||
with patch("karaoke_gen.karaoke_finalise.karaoke_finalise.KaraokeFinalise", return_value=mock_finalise), \
|
||||
patch("backend.services.youtube_service.get_youtube_service", return_value=mock_yt):
|
||||
response = client.post(URL, json={"youtube_video_id": "R3QZm8yXqvw"})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["results"]["youtube"] == {"status": "success", "video_id": "R3QZm8yXqvw"}
|
||||
mock_finalise.delete_youtube_video.assert_called_once_with("R3QZm8yXqvw")
|
||||
|
||||
def test_youtube_not_configured_reports_failed(self, client):
|
||||
mock_yt = MagicMock()
|
||||
mock_yt.is_configured = False
|
||||
with patch("backend.services.youtube_service.get_youtube_service", return_value=mock_yt):
|
||||
response = client.post(URL, json={"youtube_video_id": "abc123"})
|
||||
assert response.status_code == 200
|
||||
assert response.json()["results"]["youtube"]["status"] == "failed"
|
||||
|
||||
def test_youtube_error_is_captured_not_raised(self, client):
|
||||
with patch("backend.services.youtube_service.get_youtube_service", side_effect=RuntimeError("boom")):
|
||||
response = client.post(URL, json={"youtube_video_id": "abc123"})
|
||||
assert response.status_code == 200
|
||||
assert response.json()["results"]["youtube"]["status"] == "error"
|
||||
|
||||
|
||||
class TestOrphanedOutputsCleanupDropbox:
|
||||
def test_deletes_dropbox_folder(self, client):
|
||||
mock_dropbox = MagicMock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
path = "/MediaUnsynced/Karaoke/Tracks-Organized/NOMAD-1583 - Mazzy Star - Fade Into You"
|
||||
|
||||
with patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox):
|
||||
response = client.post(URL, json={"dropbox_folder_path": path})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["results"]["dropbox"] == {"status": "success", "path": path}
|
||||
mock_dropbox.delete_folder.assert_called_once_with(path)
|
||||
|
||||
def test_dropbox_delete_failure_reported(self, client):
|
||||
mock_dropbox = MagicMock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = False
|
||||
with patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox):
|
||||
response = client.post(URL, json={"dropbox_folder_path": "/x/y"})
|
||||
assert response.json()["results"]["dropbox"]["status"] == "failed"
|
||||
|
||||
|
||||
class TestOrphanedOutputsCleanupGDrive:
|
||||
def test_deletes_gdrive_files_by_id(self, client):
|
||||
mock_gdrive = MagicMock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.delete_files.return_value = {"id1": True, "id2": True}
|
||||
|
||||
with patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive):
|
||||
response = client.post(URL, json={"gdrive_file_ids": ["id1", "id2"]})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["results"]["gdrive"]["status"] == "success"
|
||||
mock_gdrive.delete_files.assert_called_once_with(["id1", "id2"])
|
||||
|
||||
def test_partial_gdrive_failure_reported(self, client):
|
||||
mock_gdrive = MagicMock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.delete_files.return_value = {"id1": True, "id2": False}
|
||||
with patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive):
|
||||
response = client.post(URL, json={"gdrive_file_ids": ["id1", "id2"]})
|
||||
assert response.json()["results"]["gdrive"]["status"] == "partial"
|
||||
|
||||
|
||||
class TestOrphanedOutputsCleanupMirror:
|
||||
def test_deletes_mirror_objects_by_track_prefix(self, client):
|
||||
mock_mirror = MagicMock()
|
||||
mock_mirror.delete_track_objects_by_filename_prefix.return_value = {
|
||||
"masters_deleted": 1, "vocals_guides_deleted": 1,
|
||||
}
|
||||
with patch("backend.services.nomad_master_mirror.NomadMasterMirror", return_value=mock_mirror):
|
||||
response = client.post(URL, json={"mirror_filename_prefix": "NOMAD-1583 - Mazzy Star"})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["results"]["mirror"] == {
|
||||
"status": "success", "masters_deleted": 1, "vocals_guides_deleted": 1,
|
||||
}
|
||||
mock_mirror.delete_track_objects_by_filename_prefix.assert_called_once_with("NOMAD-1583 - Mazzy Star")
|
||||
|
||||
|
||||
class TestOrphanedOutputsCleanupCombined:
|
||||
def test_all_targets_cleaned_in_one_call(self, client):
|
||||
mock_finalise = MagicMock()
|
||||
mock_finalise.delete_youtube_video.return_value = True
|
||||
mock_yt = MagicMock(is_configured=True)
|
||||
mock_yt.get_credentials_dict.return_value = {}
|
||||
mock_dropbox = MagicMock(is_configured=True)
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
mock_gdrive = MagicMock(is_configured=True)
|
||||
mock_gdrive.delete_files.return_value = {"id1": True}
|
||||
mock_mirror = MagicMock()
|
||||
mock_mirror.delete_track_objects_by_filename_prefix.return_value = {
|
||||
"masters_deleted": 1, "vocals_guides_deleted": 0,
|
||||
}
|
||||
|
||||
with patch("karaoke_gen.karaoke_finalise.karaoke_finalise.KaraokeFinalise", return_value=mock_finalise), \
|
||||
patch("backend.services.youtube_service.get_youtube_service", return_value=mock_yt), \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.nomad_master_mirror.NomadMasterMirror", return_value=mock_mirror):
|
||||
response = client.post(URL, json={
|
||||
"youtube_video_id": "vid",
|
||||
"dropbox_folder_path": "/a/b",
|
||||
"gdrive_file_ids": ["id1"],
|
||||
"mirror_filename_prefix": "NOMAD-1583 - Mazzy Star",
|
||||
})
|
||||
|
||||
assert response.status_code == 200
|
||||
results = response.json()["results"]
|
||||
assert {results[k]["status"] for k in ("youtube", "dropbox", "gdrive", "mirror")} == {"success"}
|
||||
@@ -177,11 +177,12 @@ class TestAnalyzeAndGenerateWaveform:
|
||||
service = AudioAnalysisService()
|
||||
|
||||
# Call method
|
||||
result, waveform_path = service.analyze_and_generate_waveform(
|
||||
result, waveform_path, comparison = service.analyze_and_generate_waveform(
|
||||
gcs_audio_path="uploads/job123/backing.flac",
|
||||
job_id="job123",
|
||||
gcs_waveform_destination="uploads/job123/waveform.png",
|
||||
)
|
||||
assert comparison is None # no lead/vocals stems passed
|
||||
|
||||
# Verify analysis was performed
|
||||
mock_analyzer.analyze.assert_called_once()
|
||||
|
||||
@@ -145,17 +145,78 @@ class TestAudioAnalysisService:
|
||||
mock_storage_service.upload_file.return_value = "jobs/test/analysis/waveform.png"
|
||||
|
||||
service = AudioAnalysisService(storage_service=mock_storage_service)
|
||||
result, waveform_path = service.analyze_and_generate_waveform(
|
||||
result, waveform_path, comparison = service.analyze_and_generate_waveform(
|
||||
gcs_audio_path="jobs/test/stems/backing_vocals.flac",
|
||||
job_id="test-job",
|
||||
gcs_waveform_destination="jobs/test/analysis/waveform.png",
|
||||
)
|
||||
|
||||
|
||||
# Verify upload was called
|
||||
mock_storage_service.upload_file.assert_called_once()
|
||||
|
||||
|
||||
# Verify waveform path is returned
|
||||
assert waveform_path == "jobs/test/analysis/waveform.png"
|
||||
# No lead/vocals stems passed -> no 3-stem comparison
|
||||
assert comparison is None
|
||||
|
||||
def test_analyze_with_extra_stems_returns_comparison(
|
||||
self, mock_storage_service, temp_audio_file
|
||||
):
|
||||
"""Passing lead + vocals stem paths yields a stem_comparison dict."""
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
def mock_download(gcs_path, local_path):
|
||||
import shutil
|
||||
shutil.copy(temp_audio_file, local_path)
|
||||
return local_path
|
||||
|
||||
mock_storage_service.download_file.side_effect = mock_download
|
||||
mock_storage_service.upload_file.return_value = "jobs/test/analysis/waveform.png"
|
||||
|
||||
service = AudioAnalysisService(storage_service=mock_storage_service)
|
||||
_result, _waveform, comparison = service.analyze_and_generate_waveform(
|
||||
gcs_audio_path="jobs/test/stems/backing_vocals.flac",
|
||||
job_id="test-job",
|
||||
gcs_waveform_destination="jobs/test/analysis/waveform.png",
|
||||
gcs_lead_vocals_path="jobs/test/stems/lead_vocals.flac",
|
||||
gcs_vocals_path="jobs/test/stems/vocals_clean.flac",
|
||||
)
|
||||
|
||||
assert comparison is not None
|
||||
assert comparison["error"] is None
|
||||
# All three "stems" are the same file here -> full coverage + corr 1.
|
||||
assert comparison["coverage_ratio"] == 1.0
|
||||
|
||||
def test_comparison_download_failure_is_non_fatal(
|
||||
self, mock_storage_service, temp_audio_file
|
||||
):
|
||||
"""A failure fetching the extra stems yields comparison=None, no raise."""
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
calls = {"n": 0}
|
||||
|
||||
def mock_download(gcs_path, local_path):
|
||||
import shutil
|
||||
calls["n"] += 1
|
||||
if calls["n"] > 1: # backing succeeds, extra stems fail
|
||||
raise RuntimeError("gcs down")
|
||||
shutil.copy(temp_audio_file, local_path)
|
||||
return local_path
|
||||
|
||||
mock_storage_service.download_file.side_effect = mock_download
|
||||
mock_storage_service.upload_file.return_value = "jobs/test/analysis/waveform.png"
|
||||
|
||||
service = AudioAnalysisService(storage_service=mock_storage_service)
|
||||
_result, waveform_path, comparison = service.analyze_and_generate_waveform(
|
||||
gcs_audio_path="jobs/test/stems/backing_vocals.flac",
|
||||
job_id="test-job",
|
||||
gcs_waveform_destination="jobs/test/analysis/waveform.png",
|
||||
gcs_lead_vocals_path="jobs/test/stems/lead_vocals.flac",
|
||||
gcs_vocals_path="jobs/test/stems/vocals_clean.flac",
|
||||
)
|
||||
|
||||
assert waveform_path == "jobs/test/analysis/waveform.png"
|
||||
assert comparison is None
|
||||
|
||||
def test_get_waveform_data_returns_amplitudes(
|
||||
self, mock_storage_service, temp_audio_file
|
||||
|
||||
+101
-50
@@ -215,61 +215,30 @@ class TestDeleteJob:
|
||||
|
||||
|
||||
class TestDeleteJobBrandCodeRecycling:
|
||||
"""Tests for brand code recycling in DELETE /api/jobs/{job_id}."""
|
||||
"""Tests for published-output cleanup + brand code recycling in DELETE /api/jobs/{job_id}.
|
||||
|
||||
def test_brand_code_recycled_before_deletion(self, mock_worker_service, mock_theme_service, auth_headers):
|
||||
"""Test that brand code is recycled before the job is deleted."""
|
||||
mock_job_manager = MagicMock()
|
||||
job_with_brand = Job(
|
||||
job_id="test-bc-123",
|
||||
Recycling must ONLY happen via the distribution cleanup (which gates it on
|
||||
Dropbox + GDrive success). Blind-recycling on delete hands the same NOMAD-####
|
||||
to a future job while the old files are still in the public share (duplicate
|
||||
brand code incident, NOMAD-1583, 2026-08-29).
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def _job_with_brand(job_id, outputs_deleted_at=None):
|
||||
return Job(
|
||||
job_id=job_id,
|
||||
status=JobStatus.COMPLETE,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Test",
|
||||
state_data={"brand_code": "NOMAD-0042"},
|
||||
outputs_deleted_at=datetime.now(UTC),
|
||||
outputs_deleted_at=outputs_deleted_at,
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job_with_brand
|
||||
mock_job_manager.delete_job.return_value = True
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
|
||||
with patch('backend.api.routes.jobs.job_manager', mock_job_manager), \
|
||||
patch('backend.api.routes.jobs.worker_service', mock_worker_service), \
|
||||
patch('backend.api.routes.jobs.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.services.job_manager.JobManager', lambda *a, **k: mock_job_manager), \
|
||||
patch('backend.services.firestore_service.firestore'), \
|
||||
patch('backend.services.storage_service.storage'), \
|
||||
patch('google.auth.default', return_value=(mock_creds, 'test-project')), \
|
||||
patch('backend.services.brand_code_service.BrandCodeService.parse_brand_code', return_value=("NOMAD", 42)) as mock_parse, \
|
||||
patch('backend.services.brand_code_service.get_brand_code_service') as mock_get_svc:
|
||||
mock_svc = MagicMock()
|
||||
mock_get_svc.return_value = mock_svc
|
||||
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.delete("/api/jobs/test-bc-123", headers=auth_headers)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_parse.assert_called_once_with("NOMAD-0042")
|
||||
mock_svc.recycle_brand_code.assert_called_once_with("NOMAD", 42)
|
||||
mock_job_manager.delete_job.assert_called_once()
|
||||
|
||||
def test_recycling_failure_does_not_prevent_deletion(self, mock_worker_service, mock_theme_service, auth_headers):
|
||||
"""Test that job deletion proceeds even if brand code recycling fails."""
|
||||
def _delete(self, job, auth_headers, mock_worker_service, mock_theme_service, cleanup_patch):
|
||||
mock_job_manager = MagicMock()
|
||||
job_with_brand = Job(
|
||||
job_id="test-bc-456",
|
||||
status=JobStatus.COMPLETE,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Test",
|
||||
state_data={"brand_code": "NOMAD-0099"},
|
||||
outputs_deleted_at=datetime.now(UTC),
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job_with_brand
|
||||
mock_job_manager.get_job.return_value = job
|
||||
mock_job_manager.delete_job.return_value = True
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
@@ -281,14 +250,96 @@ class TestDeleteJobBrandCodeRecycling:
|
||||
patch('backend.services.firestore_service.firestore'), \
|
||||
patch('backend.services.storage_service.storage'), \
|
||||
patch('google.auth.default', return_value=(mock_creds, 'test-project')), \
|
||||
patch('backend.services.brand_code_service.BrandCodeService.parse_brand_code', side_effect=ValueError("Bad format")):
|
||||
patch('backend.api.routes.jobs._run_distribution_cleanup', cleanup_patch) as mock_cleanup:
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.delete("/api/jobs/test-bc-456", headers=auth_headers)
|
||||
response = client.delete(f"/api/jobs/{job.job_id}", headers=auth_headers)
|
||||
return response, mock_job_manager, mock_cleanup
|
||||
|
||||
assert response.status_code == 200
|
||||
# Job should still be deleted despite recycling failure
|
||||
mock_job_manager.delete_job.assert_called_once()
|
||||
def test_published_outputs_cleaned_up_before_deletion(self, mock_worker_service, mock_theme_service, auth_headers):
|
||||
"""A job with a brand code and outputs never cleaned up gets full distribution
|
||||
cleanup (which owns the gated recycle) before the record is deleted."""
|
||||
job = self._job_with_brand("test-bc-123", outputs_deleted_at=None)
|
||||
cleanup = MagicMock(return_value={"youtube": {"status": "success"}})
|
||||
|
||||
response, mock_job_manager, mock_cleanup = self._delete(
|
||||
job, auth_headers, mock_worker_service, mock_theme_service, cleanup)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_cleanup.assert_called_once_with("test-bc-123", job)
|
||||
mock_job_manager.delete_job.assert_called_once()
|
||||
assert response.json()["distribution_cleanup"] == {"youtube": {"status": "success"}}
|
||||
|
||||
def test_outputs_already_deleted_skips_cleanup_and_recycle(self, mock_worker_service, mock_theme_service, auth_headers):
|
||||
"""A job whose outputs were already deleted (admin delete-outputs recycled the
|
||||
code then) must NOT be cleaned up or recycled again — re-recycling a code that
|
||||
a new job may have since claimed would create duplicates."""
|
||||
job = self._job_with_brand("test-bc-456", outputs_deleted_at=datetime.now(UTC))
|
||||
cleanup = MagicMock()
|
||||
|
||||
response, mock_job_manager, mock_cleanup = self._delete(
|
||||
job, auth_headers, mock_worker_service, mock_theme_service, cleanup)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_cleanup.assert_not_called()
|
||||
mock_job_manager.delete_job.assert_called_once()
|
||||
assert "distribution_cleanup" not in response.json()
|
||||
|
||||
def test_delete_files_false_rejected_for_published_job(self, mock_worker_service, mock_theme_service, auth_headers):
|
||||
"""Published outputs can't be preserved when their job record is deleted —
|
||||
the record holds the only file IDs/paths needed to ever clean them up."""
|
||||
job = self._job_with_brand("test-bc-df", outputs_deleted_at=None)
|
||||
cleanup = MagicMock()
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_manager.get_job.return_value = job
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
|
||||
with patch('backend.api.routes.jobs.job_manager', mock_job_manager), \
|
||||
patch('backend.api.routes.jobs.worker_service', mock_worker_service), \
|
||||
patch('backend.api.routes.jobs.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.services.job_manager.JobManager', lambda *a, **k: mock_job_manager), \
|
||||
patch('backend.services.firestore_service.firestore'), \
|
||||
patch('backend.services.storage_service.storage'), \
|
||||
patch('google.auth.default', return_value=(mock_creds, 'test-project')), \
|
||||
patch('backend.api.routes.jobs._run_distribution_cleanup', cleanup):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.delete("/api/jobs/test-bc-df?delete_files=false", headers=auth_headers)
|
||||
|
||||
assert response.status_code == 400
|
||||
cleanup.assert_not_called()
|
||||
mock_job_manager.delete_job.assert_not_called()
|
||||
|
||||
def test_incomplete_cleanup_aborts_deletion(self, mock_worker_service, mock_theme_service, auth_headers):
|
||||
"""If any provider cleanup reports failed/partial/error, the job record must
|
||||
be kept so the cleanup can be retried with its IDs intact."""
|
||||
job = self._job_with_brand("test-bc-incomplete", outputs_deleted_at=None)
|
||||
cleanup = MagicMock(return_value={
|
||||
"youtube": {"status": "success"},
|
||||
"dropbox": {"status": "failed", "path": "/x"},
|
||||
"gdrive": {"status": "success"},
|
||||
})
|
||||
|
||||
response, mock_job_manager, _mock_cleanup = self._delete(
|
||||
job, auth_headers, mock_worker_service, mock_theme_service, cleanup)
|
||||
|
||||
assert response.status_code == 502
|
||||
assert "dropbox" in response.json()["detail"]
|
||||
mock_job_manager.delete_job.assert_not_called()
|
||||
|
||||
def test_unexpected_cleanup_error_aborts_deletion(self, mock_worker_service, mock_theme_service, auth_headers):
|
||||
"""If cleanup crashes outright (per-service failures are handled internally),
|
||||
the job record must be preserved — deleting it would orphan the outputs with
|
||||
no way to resolve their IDs later."""
|
||||
job = self._job_with_brand("test-bc-789", outputs_deleted_at=None)
|
||||
cleanup = MagicMock(side_effect=RuntimeError("boom"))
|
||||
|
||||
response, mock_job_manager, _mock_cleanup = self._delete(
|
||||
job, auth_headers, mock_worker_service, mock_theme_service, cleanup)
|
||||
|
||||
assert response.status_code == 500
|
||||
mock_job_manager.delete_job.assert_not_called()
|
||||
|
||||
def test_no_brand_code_skips_recycling(self, client, mock_job_manager, auth_headers):
|
||||
"""Test that deletion without brand code doesn't attempt recycling."""
|
||||
|
||||
@@ -206,3 +206,92 @@ def test_cleanup_nomad_masters_noop_for_non_nomad(brand, monkeypatch):
|
||||
# Must not even construct the mirror (no GCS client) for non-Nomad brands.
|
||||
monkeypatch.setattr(mod, "NomadMasterMirror", lambda: (_ for _ in ()).throw(AssertionError("should not construct")))
|
||||
assert mod.cleanup_nomad_masters(brand) == 0
|
||||
|
||||
|
||||
# --- delete_track_objects_by_filename_prefix (single-track orphan cleanup) ---
|
||||
|
||||
def _blob(name):
|
||||
b = MagicMock()
|
||||
b.name = name
|
||||
return b
|
||||
|
||||
|
||||
def _mirror_with_blobs_per_prefix(blobs_by_prefix):
|
||||
"""Mirror whose bucket.list_blobs returns blobs matching the requested prefix,
|
||||
like real GCS (the shared-list shortcut breaks delimiter-bound tests)."""
|
||||
bucket = MagicMock()
|
||||
|
||||
def list_blobs(prefix):
|
||||
return [b for b in blobs_by_prefix if b.name.startswith(prefix)]
|
||||
|
||||
bucket.list_blobs.side_effect = list_blobs
|
||||
client = MagicMock()
|
||||
client.bucket.return_value = bucket
|
||||
return NomadMasterMirror(client=client), bucket
|
||||
|
||||
|
||||
def test_delete_track_objects_by_filename_prefix_deletes_from_both_prefixes():
|
||||
# One master + one vocals guide for the orphaned track; both must go.
|
||||
master = _blob("files/Nomad Karaoke/MP4-720p/NOMAD-1583 - Mazzy Star - Fade Into You.mp4")
|
||||
guide = _blob("files/Nomad Karaoke/vocals-padded/NOMAD-1583 - Mazzy Star - Fade Into You.flac")
|
||||
mirror, bucket = _mirror_with_blobs_per_prefix([master, guide])
|
||||
|
||||
counts = mirror.delete_track_objects_by_filename_prefix("NOMAD-1583 - Mazzy Star")
|
||||
|
||||
assert counts == {"masters_deleted": 1, "vocals_guides_deleted": 1}
|
||||
prefixes = [c.kwargs.get("prefix") or c.args[0] for c in bucket.list_blobs.call_args_list]
|
||||
assert prefixes == [
|
||||
"files/Nomad Karaoke/MP4-720p/NOMAD-1583 - Mazzy Star",
|
||||
"files/Nomad Karaoke/vocals-padded/NOMAD-1583 - Mazzy Star",
|
||||
]
|
||||
master.delete.assert_called_once()
|
||||
guide.delete.assert_called_once()
|
||||
|
||||
|
||||
def test_delete_track_objects_by_filename_prefix_is_delimiter_bounded():
|
||||
# "NOMAD-1583 - Mazzy Star" must NOT match a different track by a longer-named
|
||||
# artist that happens to share the recycled brand code and the string prefix.
|
||||
orphan = _blob("files/Nomad Karaoke/MP4-720p/NOMAD-1583 - Mazzy Star - Fade Into You.mp4")
|
||||
other = _blob("files/Nomad Karaoke/MP4-720p/NOMAD-1583 - Mazzy Starlight - Other Song.mp4")
|
||||
mirror, _bucket = _mirror_with_blobs_per_prefix([orphan, other])
|
||||
|
||||
counts = mirror.delete_track_objects_by_filename_prefix("NOMAD-1583 - Mazzy Star")
|
||||
|
||||
assert counts == {"masters_deleted": 1, "vocals_guides_deleted": 0}
|
||||
orphan.delete.assert_called_once()
|
||||
other.delete.assert_not_called()
|
||||
|
||||
|
||||
def test_delete_track_objects_full_stem_matches_extension_boundary():
|
||||
# A full "brand - artist - title" stem must still match its own files (".mp4").
|
||||
master = _blob("files/Nomad Karaoke/MP4-720p/NOMAD-1583 - Mazzy Star - Fade Into You.mp4")
|
||||
mirror, _bucket = _mirror_with_blobs_per_prefix([master])
|
||||
|
||||
counts = mirror.delete_track_objects_by_filename_prefix(
|
||||
"NOMAD-1583 - Mazzy Star - Fade Into You"
|
||||
)
|
||||
|
||||
assert counts == {"masters_deleted": 1, "vocals_guides_deleted": 0}
|
||||
master.delete.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("prefix", [
|
||||
"NOMAD-1583", # bare brand code — would match BOTH tracks sharing it
|
||||
"NOMAD-1583 - ", # brand code + separator but no artist text
|
||||
"NOMADNP-0001 - X", # private prefix
|
||||
"Mazzy Star", # no brand code
|
||||
"",
|
||||
None,
|
||||
])
|
||||
def test_delete_track_objects_by_filename_prefix_refuses_unsafe_prefixes(prefix):
|
||||
mirror, bucket, _blobs = _mirror_with_blobs([])
|
||||
with pytest.raises(ValueError):
|
||||
mirror.delete_track_objects_by_filename_prefix(prefix)
|
||||
bucket.list_blobs.assert_not_called()
|
||||
|
||||
|
||||
def test_delete_track_objects_by_filename_prefix_non_fatal_on_list_error():
|
||||
mirror, bucket, _blobs = _mirror_with_blobs([])
|
||||
bucket.list_blobs.side_effect = RuntimeError("gcs down")
|
||||
counts = mirror.delete_track_objects_by_filename_prefix("NOMAD-1583 - Mazzy Star")
|
||||
assert counts == {"masters_deleted": 0, "vocals_guides_deleted": 0}
|
||||
@@ -55,16 +55,19 @@ def _job(job_id, status, *, minutes_stale=0, source_name=None, download_retry=No
|
||||
)
|
||||
|
||||
|
||||
def _mock_jm(*, downloading=None, pending=None, rendering=None, jobs=None):
|
||||
"""Wire a JobManager mock for the endpoint's 3 status queries.
|
||||
def _mock_jm(*, downloading=None, pending=None, rendering=None, review_complete=None, jobs=None):
|
||||
"""Wire a JobManager mock for the endpoint's 4 status queries.
|
||||
|
||||
downloading/rendering use .where().stream(); pending uses .where().limit().stream().
|
||||
`jobs` maps job_id -> Job returned by get_job().
|
||||
downloading/rendering/review_complete use .where().stream(); pending uses
|
||||
.where().limit().stream(). `jobs` maps job_id -> Job returned by get_job().
|
||||
"""
|
||||
mock_jm = MagicMock()
|
||||
where = mock_jm.firestore.db.collection.return_value.where.return_value
|
||||
# Two non-limited .stream() calls in order: downloading_audio, rendering_video
|
||||
where.stream.side_effect = [iter(downloading or []), iter(rendering or [])]
|
||||
# Non-limited .stream() calls in order: downloading_audio, rendering_video,
|
||||
# review_complete (lost-render-trigger sweep)
|
||||
where.stream.side_effect = [
|
||||
iter(downloading or []), iter(rendering or []), iter(review_complete or []),
|
||||
]
|
||||
# One .limit().stream() call: download_pending_retry
|
||||
where.limit.return_value.stream.return_value = iter(pending or [])
|
||||
mock_jm.get_job.side_effect = lambda jid: (jobs or {}).get(jid)
|
||||
@@ -175,3 +178,38 @@ def test_fresh_render_not_reparked(client):
|
||||
resp, _ = _run(client, mock_jm)
|
||||
assert resp.json()["reparked_render_count"] == 0
|
||||
mock_jm.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
def test_stalled_review_complete_render_is_retriggered(client):
|
||||
"""REVIEW_COMPLETE >10 min with no render_progress = lost render trigger
|
||||
(e.g. Cloud Tasks enqueue failed from the GPU worker) -> re-trigger."""
|
||||
job = _job("rc1", JobStatus.REVIEW_COMPLETE, minutes_stale=30)
|
||||
mock_jm = _mock_jm(
|
||||
review_complete=[_doc("rc1", JobStatus.REVIEW_COMPLETE)],
|
||||
jobs={"rc1": job},
|
||||
)
|
||||
mock_ws = MagicMock()
|
||||
mock_ws.trigger_audio_download_worker = AsyncMock(return_value=True)
|
||||
mock_ws.trigger_render_video_worker = AsyncMock(return_value=True)
|
||||
with patch("backend.api.routes.internal.JobManager", return_value=mock_jm), \
|
||||
patch("backend.services.worker_service.get_worker_service", return_value=mock_ws):
|
||||
resp = client.post("/api/internal/recover-stuck-jobs")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["render_retriggered_jobs"] == ["rc1"]
|
||||
mock_ws.trigger_render_video_worker.assert_awaited_once_with("rc1")
|
||||
|
||||
|
||||
def test_fresh_review_complete_is_left_alone(client):
|
||||
job = _job("rc2", JobStatus.REVIEW_COMPLETE, minutes_stale=1)
|
||||
mock_jm = _mock_jm(
|
||||
review_complete=[_doc("rc2", JobStatus.REVIEW_COMPLETE)],
|
||||
jobs={"rc2": job},
|
||||
)
|
||||
mock_ws = MagicMock()
|
||||
mock_ws.trigger_render_video_worker = AsyncMock(return_value=True)
|
||||
with patch("backend.api.routes.internal.JobManager", return_value=mock_jm), \
|
||||
patch("backend.services.worker_service.get_worker_service", return_value=mock_ws):
|
||||
resp = client.post("/api/internal/recover-stuck-jobs")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["render_retriggered_jobs"] == []
|
||||
mock_ws.trigger_render_video_worker.assert_not_awaited()
|
||||
@@ -1325,3 +1325,309 @@ class TestGetVocalsAudio:
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
self._call({}, audio_complete=True)
|
||||
assert exc_info.value.status_code == 404
|
||||
|
||||
|
||||
class TestReplayCorrectionData:
|
||||
"""Replay mode for correction-data: re-open a COMPLETED job read-only.
|
||||
|
||||
Verifies the status gate is bypassed with ?replay=true (full auth only), the
|
||||
AWAITING_REVIEW->IN_REVIEW transition is skipped, and the edit_log is attached.
|
||||
"""
|
||||
|
||||
def _client_with_auth(self, auth_type: str = "full"):
|
||||
from backend.main import app
|
||||
from backend.api.dependencies import require_review_auth
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
async def _mock_auth(job_id: str = "job1"):
|
||||
return (job_id, auth_type)
|
||||
|
||||
app.dependency_overrides[require_review_auth] = _mock_auth
|
||||
return TestClient(app)
|
||||
|
||||
def _teardown(self):
|
||||
from backend.main import app
|
||||
from backend.api.dependencies import require_review_auth
|
||||
app.dependency_overrides.pop(require_review_auth, None)
|
||||
|
||||
def _completed_job(self):
|
||||
from backend.models.job import JobStatus
|
||||
job = MagicMock()
|
||||
job.status = JobStatus.COMPLETE
|
||||
job.job_id = "job1"
|
||||
job.artist = "A"
|
||||
job.title = "T"
|
||||
job.input_media_gcs_path = "jobs/job1/input/audio.flac"
|
||||
job.file_urls = {"lyrics": {"corrections_updated": "jobs/job1/lyrics/corrections_updated.json"},
|
||||
"stems": {}, "analysis": {}}
|
||||
job.state_data = {"instrumental_selection": "with_backing",
|
||||
"last_edit_log_path": "jobs/job1/lyrics/edit_log_x.json"}
|
||||
return job
|
||||
|
||||
def test_replay_bypasses_status_gate_and_attaches_edit_log(self):
|
||||
client = self._client_with_auth("full")
|
||||
try:
|
||||
with patch("backend.api.routes.review.JobManager") as jm, \
|
||||
patch("backend.api.routes.review.StorageService") as storage_cls, \
|
||||
patch("backend.api.routes.review._get_audio_hash", return_value="h1"):
|
||||
jm.return_value.get_job.return_value = self._completed_job()
|
||||
storage = storage_cls.return_value
|
||||
storage.file_exists.return_value = True
|
||||
storage.download_json.side_effect = lambda p: (
|
||||
{"entries": [{"operation": "ai_suggestion_accept"}]}
|
||||
if p.endswith("edit_log_x.json")
|
||||
else {"corrected_segments": [], "metadata": {}}
|
||||
)
|
||||
resp = client.get("/api/review/job1/correction-data?replay=true")
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["replay"]["is_replay"] is True
|
||||
assert body["replay"]["instrumental_selection"] == "with_backing"
|
||||
assert body["replay"]["job_status"] # some status string
|
||||
assert len(body["replay"]["edit_log"]["entries"]) == 1
|
||||
# Read-only: must NOT transition state.
|
||||
jm.return_value.transition_to_state.assert_not_called()
|
||||
finally:
|
||||
self._teardown()
|
||||
|
||||
def test_non_replay_completed_job_is_rejected(self):
|
||||
client = self._client_with_auth("full")
|
||||
try:
|
||||
with patch("backend.api.routes.review.JobManager") as jm, \
|
||||
patch("backend.api.routes.review.StorageService"):
|
||||
jm.return_value.get_job.return_value = self._completed_job()
|
||||
resp = client.get("/api/review/job1/correction-data")
|
||||
assert resp.status_code == 400
|
||||
finally:
|
||||
self._teardown()
|
||||
|
||||
def test_replay_requires_full_auth(self):
|
||||
client = self._client_with_auth("review_token")
|
||||
try:
|
||||
with patch("backend.api.routes.review.JobManager") as jm, \
|
||||
patch("backend.api.routes.review.StorageService"):
|
||||
jm.return_value.get_job.return_value = self._completed_job()
|
||||
resp = client.get("/api/review/job1/correction-data?replay=true")
|
||||
assert resp.status_code == 403
|
||||
finally:
|
||||
self._teardown()
|
||||
|
||||
|
||||
class TestDevAudioProxy:
|
||||
"""The dev-only audio byte-proxy is inert unless REVIEW_AUDIO_PROXY is set."""
|
||||
|
||||
def test_dev_audio_404_when_flag_disabled(self, monkeypatch):
|
||||
from backend.main import app
|
||||
from fastapi.testclient import TestClient
|
||||
monkeypatch.delenv("REVIEW_AUDIO_PROXY", raising=False)
|
||||
client = TestClient(app)
|
||||
resp = client.get("/api/review/job1/dev-audio?path=jobs/job1/stems/x.flac")
|
||||
assert resp.status_code == 404
|
||||
|
||||
def test_dev_audio_rejects_out_of_scope_path(self, monkeypatch):
|
||||
from backend.main import app
|
||||
from fastapi.testclient import TestClient
|
||||
monkeypatch.setenv("REVIEW_AUDIO_PROXY", "1")
|
||||
client = TestClient(app)
|
||||
resp = client.get("/api/review/job1/dev-audio?path=jobs/other/stems/x.flac")
|
||||
assert resp.status_code == 400
|
||||
|
||||
def test_dev_audio_rejects_prefix_bypass_shapes(self, monkeypatch):
|
||||
# The path must be anchored at jobs/{job_id}/ — a job_id that merely
|
||||
# appears somewhere in the path (e.g. job_id="jobs") must not pass.
|
||||
from backend.main import app
|
||||
from fastapi.testclient import TestClient
|
||||
monkeypatch.setenv("REVIEW_AUDIO_PROXY", "1")
|
||||
client = TestClient(app)
|
||||
resp = client.get("/api/review/jobs/dev-audio?path=jobs/other/stems/x.flac")
|
||||
assert resp.status_code == 400
|
||||
resp = client.get("/api/review/job1/dev-audio?path=jobs/job1/../other/x.flac")
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
class TestPreviewVideoAsyncFlow:
|
||||
"""Tests for the async (non-blocking) GCE preview flow.
|
||||
|
||||
POST /preview-video must NOT wait for GCE encoding — cold-starting a
|
||||
fallback encoder VM can take 2-3 minutes, longer than Cloudflare's ~100s
|
||||
edge timeout (incident 2026-08-29, job 326e1aef: preview encoded fine but
|
||||
the browser connection was cut and the UI spun forever). Instead the
|
||||
endpoint returns {"status": "generating"} immediately and the browser
|
||||
polls the /status endpoint until the mp4 exists in GCS.
|
||||
"""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job(self):
|
||||
from backend.models.job import Job, JobStatus
|
||||
job = MagicMock(spec=Job)
|
||||
job.job_id = "job-preview-async"
|
||||
job.status = JobStatus.AWAITING_REVIEW
|
||||
job.input_media_gcs_path = "jobs/job-preview-async/audio/input.flac"
|
||||
job.style_params_gcs_path = None
|
||||
job.style_assets = {}
|
||||
job.artist = "Test Artist"
|
||||
job.title = "Test Song"
|
||||
return job
|
||||
|
||||
def _run_gce_preview(self, mock_job, *, mp4_exists, background_mock):
|
||||
"""Run generate_preview_video with GCE enabled and heavy deps mocked."""
|
||||
import asyncio
|
||||
from backend.api.routes.review import generate_preview_video
|
||||
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_storage = MagicMock()
|
||||
mock_storage.file_exists.return_value = mp4_exists
|
||||
|
||||
mock_encoding_service = MagicMock()
|
||||
mock_encoding_service.is_preview_enabled = True
|
||||
|
||||
mock_settings = MagicMock()
|
||||
mock_settings.gcs_bucket_name = "test-bucket"
|
||||
|
||||
async def _run():
|
||||
result = await generate_preview_video(
|
||||
job_id=mock_job.job_id,
|
||||
updated_data={},
|
||||
auth_info=("user@test.com", "job_owner"),
|
||||
)
|
||||
# Let any create_task'd background coroutine start
|
||||
await asyncio.sleep(0)
|
||||
return result
|
||||
|
||||
with patch("backend.api.routes.review.JobManager", return_value=mock_job_manager), \
|
||||
patch("backend.api.routes.review.StorageService", return_value=mock_storage), \
|
||||
patch("backend.api.routes.review.get_encoding_service", return_value=mock_encoding_service), \
|
||||
patch("backend.api.routes.review.get_settings", return_value=mock_settings), \
|
||||
patch("backend.api.routes.review._prepare_preview_inputs",
|
||||
return_value=(MagicMock(), "/tmp/audio.flac", MagicMock())), \
|
||||
patch("backend.api.routes.review._encode_preview_in_background", background_mock), \
|
||||
patch("backend.api.routes.review.CorrectionOperations") as mock_co, \
|
||||
patch("tempfile.TemporaryDirectory") as mock_tmpdir:
|
||||
mock_tmpdir.return_value.__enter__ = MagicMock(return_value="/tmp/preview_test")
|
||||
mock_tmpdir.return_value.__exit__ = MagicMock(return_value=False)
|
||||
mock_co.generate_preview_video.return_value = {
|
||||
"preview_hash": "hash123",
|
||||
"ass_path": "/tmp/preview.ass",
|
||||
}
|
||||
result = asyncio.run(_run())
|
||||
return result, mock_storage, mock_co
|
||||
|
||||
def test_cache_hit_returns_success_without_encoding(self, mock_job):
|
||||
"""Same edits → same hash: if the mp4 already exists (e.g. user retried
|
||||
after a dropped connection), return success immediately."""
|
||||
background_mock = AsyncMock()
|
||||
result, mock_storage, mock_co = self._run_gce_preview(
|
||||
mock_job, mp4_exists=True, background_mock=background_mock)
|
||||
assert result == {"status": "success", "preview_hash": "hash123"}
|
||||
background_mock.assert_not_called()
|
||||
# ASS is generated with ass_only=True (no local video render)
|
||||
assert mock_co.generate_preview_video.call_args.kwargs["ass_only"] is True
|
||||
|
||||
def test_cache_miss_returns_generating_and_spawns_background_encode(self, mock_job):
|
||||
"""When the mp4 doesn't exist, the endpoint must return immediately
|
||||
with status=generating and hand encoding to a background task."""
|
||||
background_mock = AsyncMock()
|
||||
result, mock_storage, _ = self._run_gce_preview(
|
||||
mock_job, mp4_exists=False, background_mock=background_mock)
|
||||
assert result == {"status": "generating", "preview_hash": "hash123"}
|
||||
background_mock.assert_called_once()
|
||||
kwargs = background_mock.call_args.kwargs
|
||||
assert kwargs["preview_hash"] == "hash123"
|
||||
assert kwargs["encode_kwargs"]["job_id"] == "preview_job-preview-async_hash123"
|
||||
assert kwargs["encode_kwargs"]["output_gcs_path"] == \
|
||||
"gs://test-bucket/jobs/job-preview-async/previews/hash123.mp4"
|
||||
# Stale error marker from a previous failed attempt must be cleared
|
||||
mock_storage.delete_file.assert_called_once_with(
|
||||
"jobs/job-preview-async/previews/hash123.error.json", ignore_missing=True)
|
||||
|
||||
|
||||
class TestPreviewVideoStatusEndpoint:
|
||||
"""GET /{job_id}/preview-video/{hash}/status — poll target for async encodes."""
|
||||
|
||||
def _call(self, mock_storage, job_id="job-x", preview_hash="abc123"):
|
||||
import asyncio
|
||||
from backend.api.routes.review import get_preview_video_status
|
||||
with patch("backend.api.routes.review.StorageService", return_value=mock_storage):
|
||||
return asyncio.run(get_preview_video_status(
|
||||
job_id=job_id,
|
||||
preview_hash=preview_hash,
|
||||
auth_info=("user@test.com", "job_owner"),
|
||||
))
|
||||
|
||||
def test_ready_when_mp4_exists(self):
|
||||
mock_storage = MagicMock()
|
||||
mock_storage.file_exists.side_effect = lambda p: p.endswith(".mp4")
|
||||
result = self._call(mock_storage)
|
||||
assert result == {"status": "ready", "preview_hash": "abc123"}
|
||||
|
||||
def test_error_when_marker_exists(self):
|
||||
mock_storage = MagicMock()
|
||||
mock_storage.file_exists.side_effect = lambda p: p.endswith(".error.json")
|
||||
mock_storage.download_json.return_value = {"error": "encoder exploded"}
|
||||
result = self._call(mock_storage)
|
||||
assert result["status"] == "error"
|
||||
assert result["message"] == "encoder exploded"
|
||||
|
||||
def test_generating_when_neither_exists(self):
|
||||
mock_storage = MagicMock()
|
||||
mock_storage.file_exists.return_value = False
|
||||
result = self._call(mock_storage)
|
||||
assert result == {"status": "generating", "preview_hash": "abc123"}
|
||||
|
||||
|
||||
class TestEncodePreviewInBackground:
|
||||
"""The background encode task: GCE first, local fallback, error marker last."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job(self):
|
||||
from backend.models.job import Job
|
||||
job = MagicMock(spec=Job)
|
||||
job.job_id = "job-bg"
|
||||
return job
|
||||
|
||||
def _run(self, mock_job, encoding_service, storage, local_render):
|
||||
import asyncio
|
||||
from backend.api.routes.review import _encode_preview_in_background
|
||||
with patch("backend.api.routes.review.get_encoding_service", return_value=encoding_service), \
|
||||
patch("backend.api.routes.review.StorageService", return_value=storage), \
|
||||
patch("backend.api.routes.review._render_preview_locally", local_render):
|
||||
asyncio.run(_encode_preview_in_background(
|
||||
job=mock_job,
|
||||
preview_hash="h1",
|
||||
encode_kwargs={"job_id": "preview_job-bg_h1"},
|
||||
updated_data={},
|
||||
is_duet=False,
|
||||
))
|
||||
|
||||
def test_gce_success_skips_local_fallback(self, mock_job):
|
||||
encoding_service = MagicMock()
|
||||
encoding_service.encode_preview_video = AsyncMock(return_value={"status": "complete"})
|
||||
storage = MagicMock()
|
||||
local_render = MagicMock()
|
||||
self._run(mock_job, encoding_service, storage, local_render)
|
||||
local_render.assert_not_called()
|
||||
storage.upload_json.assert_not_called()
|
||||
|
||||
def test_gce_failure_falls_back_to_local(self, mock_job):
|
||||
encoding_service = MagicMock()
|
||||
encoding_service.encode_preview_video = AsyncMock(side_effect=RuntimeError("stockout"))
|
||||
storage = MagicMock()
|
||||
local_render = MagicMock(return_value="h1")
|
||||
self._run(mock_job, encoding_service, storage, local_render)
|
||||
local_render.assert_called_once()
|
||||
storage.upload_json.assert_not_called()
|
||||
|
||||
def test_both_failures_write_error_marker(self, mock_job):
|
||||
"""If GCE and the local fallback both fail, an error marker must land in
|
||||
GCS so the status poll surfaces the failure instead of timing out."""
|
||||
encoding_service = MagicMock()
|
||||
encoding_service.encode_preview_video = AsyncMock(side_effect=RuntimeError("stockout"))
|
||||
storage = MagicMock()
|
||||
local_render = MagicMock(side_effect=RuntimeError("ffmpeg died"))
|
||||
self._run(mock_job, encoding_service, storage, local_render)
|
||||
storage.upload_json.assert_called_once_with(
|
||||
"jobs/job-bg/previews/h1.error.json",
|
||||
{"error": "ffmpeg died"},
|
||||
)
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Cloud Tasks queue paths must use cloud_tasks_region, not gcp_region.
|
||||
|
||||
The GPU audio-separation-job runs with GCP_REGION set to its GPU region, but
|
||||
every Cloud Tasks queue lives in us-central1 — building queue paths from
|
||||
gcp_region 404s ("Queue does not exist") from that worker, which silently
|
||||
dropped the auto-approval render trigger (job b8bda9c2, 2026-08-27).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_enqueue_uses_cloud_tasks_region_not_gcp_region(monkeypatch) -> None:
|
||||
monkeypatch.setenv("ENABLE_CLOUD_TASKS", "true")
|
||||
monkeypatch.setenv("GCP_REGION", "us-east4") # simulate the GPU job env
|
||||
monkeypatch.delenv("CLOUD_TASKS_REGION", raising=False)
|
||||
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "test-project")
|
||||
|
||||
from backend.config import Settings
|
||||
from backend.services.worker_service import WorkerService
|
||||
|
||||
with patch("backend.services.worker_service.get_settings", return_value=Settings()):
|
||||
service = WorkerService()
|
||||
tasks_client = MagicMock()
|
||||
tasks_client.queue_path.side_effect = (
|
||||
lambda project, location, queue: f"projects/{project}/locations/{location}/queues/{queue}"
|
||||
)
|
||||
service._tasks_client = tasks_client
|
||||
|
||||
await service._enqueue_cloud_task("render-video", "job1")
|
||||
|
||||
args = tasks_client.queue_path.call_args.args
|
||||
assert args[1] == "us-central1", f"queue location must be us-central1, got {args[1]}"
|
||||
|
||||
|
||||
def test_settings_cloud_tasks_region_default(monkeypatch) -> None:
|
||||
monkeypatch.delenv("CLOUD_TASKS_REGION", raising=False)
|
||||
from backend.config import Settings
|
||||
assert Settings().cloud_tasks_region == "us-central1"
|
||||
|
||||
|
||||
# --- REVIEW_COMPLETE stall detection (lost render trigger) ---
|
||||
|
||||
def _job(minutes_old: float, render_progress: bool = False) -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
state_data={"render_progress": {"stage": "encoding"}} if render_progress else {},
|
||||
updated_at=datetime.now(timezone.utc) - timedelta(minutes=minutes_old),
|
||||
)
|
||||
|
||||
|
||||
def test_review_complete_stalled_after_ten_minutes() -> None:
|
||||
from backend.api.routes.internal import _review_complete_stalled
|
||||
assert _review_complete_stalled(_job(minutes_old=15)) is True
|
||||
|
||||
|
||||
def test_review_complete_fresh_is_not_stalled() -> None:
|
||||
from backend.api.routes.internal import _review_complete_stalled
|
||||
assert _review_complete_stalled(_job(minutes_old=2)) is False
|
||||
|
||||
|
||||
def test_review_complete_with_render_underway_is_not_stalled() -> None:
|
||||
from backend.api.routes.internal import _review_complete_stalled
|
||||
assert _review_complete_stalled(_job(minutes_old=30, render_progress=True)) is False
|
||||
@@ -48,7 +48,8 @@
|
||||
"invalidInstrumentalSelection": "Invalid instrumental_selection. Must be one of: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental selected. Video generation started.",
|
||||
"instrumentalSelectionError": "Error selecting instrumental for job {job_id}: {error}",
|
||||
"downloadUrlsError": "Error getting download URLs: {error}"
|
||||
"downloadUrlsError": "Error getting download URLs: {error}",
|
||||
"deletePublishedRequiresFiles": "This track's published files must be removed when the job is deleted. Retry the delete without delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Job not found",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "تم تحديد المسار الموسيقي. بدأ إنشاء الفيديو.",
|
||||
"instrumentalSelectionError": "خطأ في تحديد المسار الموسيقي للمهمة {job_id}: {error}",
|
||||
"downloadUrlsError": "خطأ في الحصول على روابط التنزيل: {error}",
|
||||
"fileNoLongerAvailable": "الملف لم يعد متاحاً"
|
||||
"fileNoLongerAvailable": "الملف لم يعد متاحاً",
|
||||
"deletePublishedRequiresFiles": "يجب إزالة الملفات المنشورة لهذا المسار عند حذف المهمة. يُرجى إعادة محاولة الحذف بدون delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "المهمة غير موجودة",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Pista instrumental seleccionada. S'ha iniciat la generació del vídeo.",
|
||||
"instrumentalSelectionError": "Error en seleccionar la pista instrumental per a la tasca {job_id}: {error}",
|
||||
"downloadUrlsError": "Error en obtenir els URL de descàrrega: {error}",
|
||||
"fileNoLongerAvailable": "El fitxer ja no està disponible"
|
||||
"fileNoLongerAvailable": "El fitxer ja no està disponible",
|
||||
"deletePublishedRequiresFiles": "Els fitxers publicats d'aquesta pista s'han d'eliminar quan s'elimini la tasca. Torna a intentar l'eliminació sense delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tasca no trobada",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumentál vybrán. Začalo generování videa.",
|
||||
"instrumentalSelectionError": "Chyba při výběru instrumentálu pro úlohu {job_id}: {error}",
|
||||
"downloadUrlsError": "Chyba při získávání adres URL ke stažení: {error}",
|
||||
"fileNoLongerAvailable": "Soubor již není dostupný"
|
||||
"fileNoLongerAvailable": "Soubor již není dostupný",
|
||||
"deletePublishedRequiresFiles": "Při mazání úlohy je nutné odstranit i publikované soubory této skladby. Zkus to smazat znovu bez delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Úloha nebyla nalezena",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumental valgt. Videogenerering er startet.",
|
||||
"instrumentalSelectionError": "Fejl ved valg af instrumental for job {job_id}: {error}",
|
||||
"downloadUrlsError": "Fejl ved hentning af download-URL'er: {error}",
|
||||
"fileNoLongerAvailable": "Filen er ikke længere tilgængelig"
|
||||
"fileNoLongerAvailable": "Filen er ikke længere tilgængelig",
|
||||
"deletePublishedRequiresFiles": "Dette spors udgivne filer skal fjernes, når jobbet slettes. Prøv at slette igen uden delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Jobbet blev ikke fundet",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumental ausgewählt. Video-Generierung gestartet.",
|
||||
"instrumentalSelectionError": "Fehler bei der Auswahl des Instrumentals für Auftrag {job_id}: {error}",
|
||||
"downloadUrlsError": "Fehler beim Abrufen der Download-URLs: {error}",
|
||||
"fileNoLongerAvailable": "Datei nicht mehr verfügbar"
|
||||
"fileNoLongerAvailable": "Datei nicht mehr verfügbar",
|
||||
"deletePublishedRequiresFiles": "Die veröffentlichten Dateien dieses Tracks müssen entfernt werden, wenn der Auftrag gelöscht wird. Versuche den Löschvorgang ohne delete_files=false erneut."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Auftrag nicht gefunden",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Το instrumental επιλέχθηκε. Ξεκίνησε η δημιουργία βίντεο.",
|
||||
"instrumentalSelectionError": "Σφάλμα κατά την επιλογή instrumental για την εργασία {job_id}: {error}",
|
||||
"downloadUrlsError": "Σφάλμα κατά τη λήψη των URL λήψης: {error}",
|
||||
"fileNoLongerAvailable": "Το αρχείο δεν είναι πλέον διαθέσιμο"
|
||||
"fileNoLongerAvailable": "Το αρχείο δεν είναι πλέον διαθέσιμο",
|
||||
"deletePublishedRequiresFiles": "Τα δημοσιευμένα αρχεία αυτού του κομματιού πρέπει να αφαιρεθούν όταν διαγράφεται η εργασία. Δοκίμασε ξανά τη διαγραφή χωρίς το delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Η εργασία δεν βρέθηκε",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"invalidInstrumentalSelection": "Invalid instrumental_selection. Must be one of: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental selected. Video generation started.",
|
||||
"instrumentalSelectionError": "Error selecting instrumental for job {job_id}: {error}",
|
||||
"downloadUrlsError": "Error getting download URLs: {error}"
|
||||
"downloadUrlsError": "Error getting download URLs: {error}",
|
||||
"deletePublishedRequiresFiles": "This track's published files must be removed when the job is deleted. Retry the delete without delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Job not found",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumental seleccionado. Generación de video iniciada.",
|
||||
"instrumentalSelectionError": "Error al seleccionar el instrumental para el trabajo {job_id}: {error}",
|
||||
"downloadUrlsError": "Error al obtener las URLs de descarga: {error}",
|
||||
"fileNoLongerAvailable": "El archivo ya no está disponible"
|
||||
"fileNoLongerAvailable": "El archivo ya no está disponible",
|
||||
"deletePublishedRequiresFiles": "Los archivos publicados de esta pista deben eliminarse cuando se elimine el trabajo. Vuelve a intentar la eliminación sin delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Trabajo no encontrado",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumentaali valittu. Videon luonti aloitettu.",
|
||||
"instrumentalSelectionError": "Virhe valittaessa instrumentaalia työlle {job_id}: {error}",
|
||||
"downloadUrlsError": "Virhe haettaessa latausosoitteita: {error}",
|
||||
"fileNoLongerAvailable": "Tiedosto ei ole enää saatavilla"
|
||||
"fileNoLongerAvailable": "Tiedosto ei ole enää saatavilla",
|
||||
"deletePublishedRequiresFiles": "Tämän kappaleen julkaistut tiedostot täytyy poistaa työn poistamisen yhteydessä. Yritä poistoa uudelleen ilman delete_files=false -määritystä."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Työtä ei löytynyt",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumental sélectionné. La génération de la vidéo a commencé.",
|
||||
"instrumentalSelectionError": "Erreur lors de la sélection de l'instrumental pour la tâche {job_id} : {error}",
|
||||
"downloadUrlsError": "Erreur lors de l'obtention des URL de téléchargement : {error}",
|
||||
"fileNoLongerAvailable": "Le fichier n'est plus disponible"
|
||||
"fileNoLongerAvailable": "Le fichier n'est plus disponible",
|
||||
"deletePublishedRequiresFiles": "Les fichiers publiés de cette piste doivent être supprimés en même temps que la tâche. Réessaie la suppression sans delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tâche introuvable",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "הפלייבק נבחר. יצירת הווידאו התחילה.",
|
||||
"instrumentalSelectionError": "שגיאה בבחירת פלייבק עבור המשימה {job_id}: {error}",
|
||||
"downloadUrlsError": "שגיאה בקבלת כתובות ההורדה: {error}",
|
||||
"fileNoLongerAvailable": "הקובץ אינו זמין יותר"
|
||||
"fileNoLongerAvailable": "הקובץ אינו זמין יותר",
|
||||
"deletePublishedRequiresFiles": "יש להסיר את הקבצים שפורסמו עבור רצועה זו בעת מחיקת המשימה. נסה שוב את המחיקה ללא delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "המשימה לא נמצאה",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "इंस्ट्रुमेंटल चुना गया। वीडियो जनरेशन शुरू हो गया है।",
|
||||
"instrumentalSelectionError": "जॉब {job_id} के लिए इंस्ट्रुमेंटल चुनने में त्रुटि: {error}",
|
||||
"downloadUrlsError": "डाउनलोड URLs प्राप्त करने में त्रुटि: {error}",
|
||||
"fileNoLongerAvailable": "फ़ाइल अब उपलब्ध नहीं है"
|
||||
"fileNoLongerAvailable": "फ़ाइल अब उपलब्ध नहीं है",
|
||||
"deletePublishedRequiresFiles": "जॉब डिलीट करते समय इस ट्रैक की पब्लिश की गई फ़ाइलों को हटाना ज़रूरी है। delete_files=false के बिना डिलीट करने की दोबारा कोशिश करो।"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "जॉब नहीं मिली",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumental je odabran. Generiranje videa je započelo.",
|
||||
"instrumentalSelectionError": "Pogreška pri odabiru instrumentala za zadatak {job_id}: {error}",
|
||||
"downloadUrlsError": "Pogreška pri dohvaćanju URL-ova za preuzimanje: {error}",
|
||||
"fileNoLongerAvailable": "Datoteka više nije dostupna"
|
||||
"fileNoLongerAvailable": "Datoteka više nije dostupna",
|
||||
"deletePublishedRequiresFiles": "Objavljene datoteke ove pjesme moraju se ukloniti kada se zadatak izbriše. Pokušaj ponovno obrisati bez delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Zadatak nije pronađen",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumentális sáv kiválasztva. A videó generálása megkezdődött.",
|
||||
"instrumentalSelectionError": "Hiba a(z) {job_id} feladat instrumentális sávjának kiválasztásakor: {error}",
|
||||
"downloadUrlsError": "Hiba a letöltési URL-ek lekérésekor: {error}",
|
||||
"fileNoLongerAvailable": "A fájl már nem elérhető"
|
||||
"fileNoLongerAvailable": "A fájl már nem elérhető",
|
||||
"deletePublishedRequiresFiles": "Ennek a számnak a közzétett fájljait el kell távolítani a feladat törlésekor. Próbáld újra a törlést a delete_files=false nélkül."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "A feladat nem található",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumental dipilih. Pembuatan video dimulai.",
|
||||
"instrumentalSelectionError": "Kesalahan saat memilih instrumental untuk tugas {job_id}: {error}",
|
||||
"downloadUrlsError": "Kesalahan saat mendapatkan URL unduhan: {error}",
|
||||
"fileNoLongerAvailable": "File sudah tidak tersedia"
|
||||
"fileNoLongerAvailable": "File sudah tidak tersedia",
|
||||
"deletePublishedRequiresFiles": "File yang telah dipublikasikan dari trek ini harus ikut dihapus saat tugas dihapus. Silakan ulangi penghapusan tanpa delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tugas tidak ditemukan",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Strumentale selezionata. Generazione del video avviata.",
|
||||
"instrumentalSelectionError": "Errore durante la selezione della strumentale per il lavoro {job_id}: {error}",
|
||||
"downloadUrlsError": "Errore durante il recupero degli URL di download: {error}",
|
||||
"fileNoLongerAvailable": "File non più disponibile"
|
||||
"fileNoLongerAvailable": "File non più disponibile",
|
||||
"deletePublishedRequiresFiles": "I file pubblicati di questa traccia devono essere rimossi quando il lavoro viene eliminato. Riprova l'eliminazione senza delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Lavoro non trovato",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "インストゥルメンタルが選択されました。動画の生成を開始しました。",
|
||||
"instrumentalSelectionError": "ジョブ {job_id} のインストゥルメンタル選択中にエラーが発生しました: {error}",
|
||||
"downloadUrlsError": "ダウンロードURLの取得中にエラーが発生しました: {error}",
|
||||
"fileNoLongerAvailable": "ファイルはご利用いただけなくなりました"
|
||||
"fileNoLongerAvailable": "ファイルはご利用いただけなくなりました",
|
||||
"deletePublishedRequiresFiles": "ジョブを削除する際は、このトラックの公開済みファイルも削除する必要があります。delete_files=false を指定せずに、削除を再試行してください。"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "ジョブが見つかりません",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "반주가 선택되었습니다. 비디오 생성이 시작되었습니다.",
|
||||
"instrumentalSelectionError": "작업 {job_id}의 반주 선택 중 오류 발생: {error}",
|
||||
"downloadUrlsError": "다운로드 URL을 가져오는 중 오류 발생: {error}",
|
||||
"fileNoLongerAvailable": "파일을 더 이상 사용할 수 없습니다"
|
||||
"fileNoLongerAvailable": "파일을 더 이상 사용할 수 없습니다",
|
||||
"deletePublishedRequiresFiles": "작업을 삭제할 때 이 트랙에 게시된 파일도 함께 삭제해야 합니다. delete_files=false 없이 삭제를 다시 시도해 주세요."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "작업을 찾을 수 없습니다",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumental dipilih. Penjanaan video bermula.",
|
||||
"instrumentalSelectionError": "Ralat memilih instrumental untuk tugasan {job_id}: {error}",
|
||||
"downloadUrlsError": "Ralat mendapatkan URL muat turun: {error}",
|
||||
"fileNoLongerAvailable": "Fail tidak lagi tersedia"
|
||||
"fileNoLongerAvailable": "Fail tidak lagi tersedia",
|
||||
"deletePublishedRequiresFiles": "Fail terbitan trek ini mesti dipadamkan apabila tugas dipadamkan. Sila cuba padam semula tanpa delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tugasan tidak dijumpai",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumental valgt. Videogenerering startet.",
|
||||
"instrumentalSelectionError": "Feil ved valg av instrumental for jobb {job_id}: {error}",
|
||||
"downloadUrlsError": "Feil ved henting av nedlastings-URL-er: {error}",
|
||||
"fileNoLongerAvailable": "Filen er ikke lenger tilgjengelig"
|
||||
"fileNoLongerAvailable": "Filen er ikke lenger tilgjengelig",
|
||||
"deletePublishedRequiresFiles": "De publiserte filene for dette sporet må fjernes når jobben slettes. Prøv å slette på nytt uten delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Jobben ble ikke funnet",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumental geselecteerd. Videogeneratie is gestart.",
|
||||
"instrumentalSelectionError": "Fout bij het selecteren van instrumental voor taak {job_id}: {error}",
|
||||
"downloadUrlsError": "Fout bij het ophalen van download-URL's: {error}",
|
||||
"fileNoLongerAvailable": "Bestand niet meer beschikbaar"
|
||||
"fileNoLongerAvailable": "Bestand niet meer beschikbaar",
|
||||
"deletePublishedRequiresFiles": "De gepubliceerde bestanden van deze track moeten worden verwijderd als de taak wordt verwijderd. Probeer het verwijderen opnieuw zonder delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Taak niet gevonden",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Wybrano podkład. Rozpoczęto generowanie wideo.",
|
||||
"instrumentalSelectionError": "Błąd podczas wybierania podkładu dla zadania {job_id}: {error}",
|
||||
"downloadUrlsError": "Błąd podczas pobierania linków: {error}",
|
||||
"fileNoLongerAvailable": "Plik nie jest już dostępny"
|
||||
"fileNoLongerAvailable": "Plik nie jest już dostępny",
|
||||
"deletePublishedRequiresFiles": "Opublikowane pliki tego utworu muszą zostać usunięte podczas usuwania zadania. Spróbuj usunąć ponownie bez delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Nie znaleziono zadania",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumental selecionado. Geração de vídeo iniciada.",
|
||||
"instrumentalSelectionError": "Erro ao selecionar instrumental para o job {job_id}: {error}",
|
||||
"downloadUrlsError": "Erro ao obter URLs de download: {error}",
|
||||
"fileNoLongerAvailable": "O arquivo não está mais disponível"
|
||||
"fileNoLongerAvailable": "O arquivo não está mais disponível",
|
||||
"deletePublishedRequiresFiles": "Os arquivos publicados desta faixa devem ser removidos quando a tarefa for excluída. Tente excluir novamente sem delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Job não encontrado",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumental selectat. A început generarea videoclipului.",
|
||||
"instrumentalSelectionError": "Eroare la selectarea instrumentalului pentru jobul {job_id}: {error}",
|
||||
"downloadUrlsError": "Eroare la obținerea adreselor URL de descărcare: {error}",
|
||||
"fileNoLongerAvailable": "Fișierul nu mai este disponibil"
|
||||
"fileNoLongerAvailable": "Fișierul nu mai este disponibil",
|
||||
"deletePublishedRequiresFiles": "Fișierele publicate ale acestei piese trebuie eliminate la ștergerea jobului. Încearcă din nou ștergerea fără delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Jobul nu a fost găsit",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Инструментал выбран. Началась генерация видео.",
|
||||
"instrumentalSelectionError": "Ошибка при выборе инструментала для задачи {job_id}: {error}",
|
||||
"downloadUrlsError": "Ошибка при получении URL-адресов для скачивания: {error}",
|
||||
"fileNoLongerAvailable": "Файл больше недоступен"
|
||||
"fileNoLongerAvailable": "Файл больше недоступен",
|
||||
"deletePublishedRequiresFiles": "Опубликованные файлы этого трека нужно удалить вместе с задачей. Повтори удаление без delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Задача не найдена",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Inštrumentál bol vybraný. Začalo sa generovanie videa.",
|
||||
"instrumentalSelectionError": "Chyba pri výbere inštrumentálu pre úlohu {job_id}: {error}",
|
||||
"downloadUrlsError": "Chyba pri získavaní adries URL na stiahnutie: {error}",
|
||||
"fileNoLongerAvailable": "Súbor už nie je dostupný"
|
||||
"fileNoLongerAvailable": "Súbor už nie je dostupný",
|
||||
"deletePublishedRequiresFiles": "Publikované súbory tejto skladby musia byť pri odstránení úlohy vymazané. Zopakuj odstránenie bez delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Úloha sa nenašla",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumental vald. Videogenereringen har startat.",
|
||||
"instrumentalSelectionError": "Fel vid val av instrumental för jobb {job_id}: {error}",
|
||||
"downloadUrlsError": "Fel vid hämtning av nedladdningslänkar: {error}",
|
||||
"fileNoLongerAvailable": "Filen är inte längre tillgänglig"
|
||||
"fileNoLongerAvailable": "Filen är inte längre tillgänglig",
|
||||
"deletePublishedRequiresFiles": "Det här spårets publicerade filer måste tas bort när jobbet raderas. Försök att radera igen utan delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Jobbet hittades inte",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "เลือกดนตรีบรรเลงแล้ว กำลังเริ่มสร้างวิดีโอ",
|
||||
"instrumentalSelectionError": "เกิดข้อผิดพลาดในการเลือกดนตรีบรรเลงสำหรับงาน {job_id}: {error}",
|
||||
"downloadUrlsError": "เกิดข้อผิดพลาดในการรับ URL สำหรับดาวน์โหลด: {error}",
|
||||
"fileNoLongerAvailable": "ไฟล์ไม่พร้อมใช้งานแล้ว"
|
||||
"fileNoLongerAvailable": "ไฟล์ไม่พร้อมใช้งานแล้ว",
|
||||
"deletePublishedRequiresFiles": "ไฟล์ที่เผยแพร่แล้วของแทร็กนี้ต้องถูกลบออกเมื่อลบงาน โปรดลองลบใหม่อีกครั้งโดยไม่ใช้ delete_files=false"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "ไม่พบงาน",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Napili na ang instrumental. Nagsimula na ang paggawa ng video.",
|
||||
"instrumentalSelectionError": "Error sa pagpili ng instrumental para sa job {job_id}: {error}",
|
||||
"downloadUrlsError": "Error sa pagkuha ng mga download URL: {error}",
|
||||
"fileNoLongerAvailable": "Hindi na available ang file"
|
||||
"fileNoLongerAvailable": "Hindi na available ang file",
|
||||
"deletePublishedRequiresFiles": "Kailangang tanggalin ang mga na-publish na file ng track na ito kapag na-delete ang job. Subukang i-delete muli nang walang delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Hindi nahanap ang job",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Enstrümantal seçildi. Video oluşturma başladı.",
|
||||
"instrumentalSelectionError": "{job_id} işi için enstrümantal seçme hatası: {error}",
|
||||
"downloadUrlsError": "İndirme URL'lerini alma hatası: {error}",
|
||||
"fileNoLongerAvailable": "Dosya artık mevcut değil"
|
||||
"fileNoLongerAvailable": "Dosya artık mevcut değil",
|
||||
"deletePublishedRequiresFiles": "İş silindiğinde bu parçanın yayınlanmış dosyaları da kaldırılmalıdır. Silme işlemini delete_files=false olmadan tekrar dene."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "İş bulunamadı",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Інструментал вибрано. Розпочато генерацію відео.",
|
||||
"instrumentalSelectionError": "Помилка вибору інструменталу для завдання {job_id}: {error}",
|
||||
"downloadUrlsError": "Помилка отримання URL-адрес для завантаження: {error}",
|
||||
"fileNoLongerAvailable": "Файл більше недоступний"
|
||||
"fileNoLongerAvailable": "Файл більше недоступний",
|
||||
"deletePublishedRequiresFiles": "Опубліковані файли цього треку потрібно видалити під час видалення завдання. Повтори спробу видалення без delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Завдання не знайдено",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Đã chọn nhạc nền. Đã bắt đầu tạo video.",
|
||||
"instrumentalSelectionError": "Lỗi khi chọn nhạc nền cho công việc {job_id}: {error}",
|
||||
"downloadUrlsError": "Lỗi khi lấy URL tải xuống: {error}",
|
||||
"fileNoLongerAvailable": "Tệp không còn khả dụng"
|
||||
"fileNoLongerAvailable": "Tệp không còn khả dụng",
|
||||
"deletePublishedRequiresFiles": "Các tệp đã xuất bản của bài hát này phải được xóa khi xóa tác vụ. Vui lòng thử xóa lại mà không có delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Không tìm thấy công việc",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "已选择伴奏。已开始生成视频。",
|
||||
"instrumentalSelectionError": "为任务 {job_id} 选择伴奏时出错:{error}",
|
||||
"downloadUrlsError": "获取下载 URL 时出错:{error}",
|
||||
"fileNoLongerAvailable": "文件已不可用"
|
||||
"fileNoLongerAvailable": "文件已不可用",
|
||||
"deletePublishedRequiresFiles": "删除任务时,必须移除此曲目已发布的文件。请去掉 delete_files=false 后重试删除。"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "未找到任务",
|
||||
|
||||
@@ -360,6 +360,19 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
# This will check if lyrics are also complete and transition to next stage if so
|
||||
job_manager.mark_audio_complete(job_id)
|
||||
|
||||
# Auto-approval second chance: when lyrics/screens finished BEFORE
|
||||
# audio, the job is already parked in AWAITING_REVIEW and the
|
||||
# screens-worker scoring ran without backing analysis. Now that
|
||||
# stems + analysis exist, re-score and auto-complete the review if
|
||||
# fully confident. No-op (fail-safe) in every other state.
|
||||
try:
|
||||
from backend.services.auto_approval.executor import maybe_auto_complete_review
|
||||
auto_result = await maybe_auto_complete_review(job_id, trigger="audio_worker")
|
||||
if auto_result.get("outcome") == "auto_completed":
|
||||
job_log.info("Auto-approved after audio completion: review skipped")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] auto-approval attempt failed (non-fatal): {e}")
|
||||
|
||||
root_span.set_attribute("duration_seconds", duration)
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=audio status=success duration={duration:.1f}s")
|
||||
return True
|
||||
|
||||
@@ -70,6 +70,9 @@ async def process_proactive_auto_correct(job_id: str) -> dict:
|
||||
# Must match what the review UI sends (default settings,
|
||||
# multi-model) or the cache key won't line up.
|
||||
settings=AutoCorrectSettings(compare_models=True),
|
||||
# Already loaded — saves the service re-fetching it for the
|
||||
# deterministic (P4/P5) generators.
|
||||
correction_data=data,
|
||||
),
|
||||
timeout=180,
|
||||
)
|
||||
|
||||
@@ -209,14 +209,42 @@ async def generate_screens(job_id: str) -> bool:
|
||||
worker_service = get_worker_service()
|
||||
await worker_service.trigger_render_video_worker(job_id)
|
||||
else:
|
||||
# Normal flow: transition to combined review
|
||||
logger.info(f"[job:{job_id}] Screens generated, awaiting combined review")
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_REVIEW,
|
||||
progress=55,
|
||||
message="Ready for review. Please review lyrics and select your instrumental."
|
||||
)
|
||||
# Auto-approval: score the job (verdict always recorded in
|
||||
# processing_metadata.auto_approval) and, when fully confident
|
||||
# and eligible, complete the review here — skipping the
|
||||
# AWAITING_REVIEW state (and its notifications) entirely.
|
||||
# Fail-safe: anything short of confident falls through to
|
||||
# normal human review.
|
||||
from backend.services.auto_approval.executor import maybe_auto_complete_review
|
||||
with job_span("auto-approval", job_id):
|
||||
auto_result = await maybe_auto_complete_review(job_id, trigger="screens_worker")
|
||||
|
||||
if auto_result.get("outcome") == "auto_completed":
|
||||
job_log.info("Auto-approved: review screens skipped, render triggered")
|
||||
logger.info(f"[job:{job_id}] Auto-approved — review skipped")
|
||||
else:
|
||||
# Server-side pre-apply: apply the AI corrections + heuristic
|
||||
# fixes BEFORE the review-ready notification fires, so the
|
||||
# review screen loads one final state (no in-browser auto-apply
|
||||
# race). Best-effort + bounded: on any miss the UI falls back to
|
||||
# its client-side on-load apply.
|
||||
from backend.services.auto_approval.pre_apply import ensure_and_pre_apply
|
||||
with job_span("pre-apply-corrections", job_id):
|
||||
pre_apply_result = await ensure_and_pre_apply(job_id)
|
||||
if pre_apply_result.get("outcome") == "pre_applied":
|
||||
job_log.info(
|
||||
f"Pre-applied {pre_apply_result.get('applied', 0)} AI corrections "
|
||||
"server-side before review notification"
|
||||
)
|
||||
|
||||
# Normal flow: transition to combined review
|
||||
logger.info(f"[job:{job_id}] Screens generated, awaiting combined review")
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_REVIEW,
|
||||
progress=55,
|
||||
message="Ready for review. Please review lyrics and select your instrumental."
|
||||
)
|
||||
|
||||
duration = time.time() - start_time
|
||||
# Store worker-level timing
|
||||
@@ -561,7 +589,8 @@ async def _analyze_backing_vocals(
|
||||
return
|
||||
|
||||
# Get backing vocals path
|
||||
backing_vocals_path = job.file_urls.get('stems', {}).get('backing_vocals')
|
||||
stems = job.file_urls.get('stems', {})
|
||||
backing_vocals_path = stems.get('backing_vocals')
|
||||
if not backing_vocals_path:
|
||||
job_log.warning("No backing vocals file found - skipping analysis")
|
||||
return
|
||||
@@ -574,11 +603,16 @@ async def _analyze_backing_vocals(
|
||||
# Define output path for waveform
|
||||
waveform_gcs_path = f"jobs/{job_id}/analysis/backing_vocals_waveform.png"
|
||||
|
||||
# Run analysis and generate waveform
|
||||
result, waveform_path = analysis_service.analyze_and_generate_waveform(
|
||||
# Run analysis and generate waveform. Passing the lead + full-vocals
|
||||
# stems as well enables the 3-stem comparison the backing-vocals
|
||||
# decider uses to tell genuine harmonies from lead bleed / a
|
||||
# misclassified lead / flat noise (best-effort — None when missing).
|
||||
result, waveform_path, stem_comparison = analysis_service.analyze_and_generate_waveform(
|
||||
gcs_audio_path=backing_vocals_path,
|
||||
job_id=job_id,
|
||||
gcs_waveform_destination=waveform_gcs_path,
|
||||
gcs_lead_vocals_path=stems.get('lead_vocals'),
|
||||
gcs_vocals_path=stems.get('vocals_clean'),
|
||||
)
|
||||
|
||||
# Store analysis results in job state_data
|
||||
@@ -600,6 +634,8 @@ async def _analyze_backing_vocals(
|
||||
'audible_percentage': result.audible_percentage,
|
||||
'silence_threshold_db': result.silence_threshold_db,
|
||||
}
|
||||
if stem_comparison is not None:
|
||||
analysis_data['stem_comparison'] = stem_comparison
|
||||
|
||||
job_manager.update_state_data(job_id, 'backing_vocals_analysis', analysis_data)
|
||||
|
||||
|
||||
+20
-1
@@ -296,6 +296,15 @@ Response:
|
||||
|
||||
The combined review flow allows users to review lyrics AND select instrumental track in a single session.
|
||||
|
||||
**Auto-approval:** jobs default to `review_mode="auto"` — when the auto-approval scorer is fully
|
||||
confident (lyrics verified against a synced reference with every gap covered by the auto-applied
|
||||
AI suggestions, AND no audible backing vocals), the review screens are skipped entirely: the AI
|
||||
suggestions are applied server-side, the clean instrumental is selected, and the job goes
|
||||
straight to render. All other jobs stop at review as before. The verdict for every job is
|
||||
recorded in `processing_metadata.auto_approval` (fields: `mode`, `outcome`, per-axis verdicts +
|
||||
signals). Set `review_mode="always_review"` (admin job PATCH) to force the review screens;
|
||||
global kill switch: `AUTO_APPROVAL_ENFORCE_ENABLED=false`.
|
||||
|
||||
#### Get Correction Data
|
||||
|
||||
```http
|
||||
@@ -337,7 +346,17 @@ Content-Type: application/json
|
||||
}
|
||||
```
|
||||
|
||||
Generates preview video during review. The `use_background_image` option controls whether the preview renders with the theme's background image (slower, ~30-60s) or a solid black background (faster, ~10s). Defaults to black background for speed.
|
||||
Generates a preview video during review. Returns `{"status": "success", "preview_hash": "..."}` when the video is immediately available (cache hit — the hash is deterministic over the correction data — or local render), or `{"status": "generating", "preview_hash": "..."}` when encoding continues in the background on a GCE worker. In the generating case, poll the status endpoint below; the request never waits for the encoder (cold-starting a worker VM can take minutes, longer than Cloudflare's edge timeout).
|
||||
|
||||
The `use_background_image` option controls whether the preview renders with the theme's background image (slower, ~30-60s) or a solid black background (faster, ~10s). Defaults to black background for speed.
|
||||
|
||||
#### Poll Preview Status
|
||||
|
||||
```http
|
||||
GET /api/review/{job_id}/preview-video/{preview_hash}/status
|
||||
```
|
||||
|
||||
Returns `{"status": "ready" | "generating" | "error", "preview_hash": "...", "message"?: "..."}`. Backed by GCS (mp4 existence / error marker), so polls work across Cloud Run instances. Once ready, fetch the video via `GET /api/review/{job_id}/preview-video/{preview_hash}`.
|
||||
|
||||
#### Stream Audio
|
||||
|
||||
|
||||
@@ -250,10 +250,38 @@ The post-job trigger uses a 5-minute Cloud Tasks delay (via `gdrive-validation-q
|
||||
|
||||
This is the most critical alert. Steps:
|
||||
1. Check which files have the duplicate: the notification lists them
|
||||
2. Determine which is correct (check Firestore job records)
|
||||
3. Remove or rename the incorrect file in Google Drive
|
||||
2. Determine which is correct (check Firestore job records — usually only ONE of the
|
||||
two tracks still has a job with that `state_data.brand_code`; the other is orphaned)
|
||||
3. Remove the orphaned track's outputs (see below)
|
||||
4. Re-trigger validation to confirm the fix
|
||||
|
||||
**Known cause — job deleted while outputs still published** (NOMAD-1583 incident,
|
||||
2026-08-29): before v0.206.0, `DELETE /api/jobs/{id}` recycled the brand code even
|
||||
when the job's outputs had never been cleaned up, leaving the files live in the
|
||||
public share. The next job to allocate reused the recycled number → duplicate.
|
||||
Since v0.206.0, deleting a job with published outputs runs the full distribution
|
||||
cleanup first (YouTube + Dropbox + GDrive + kjbox mirror) and only recycles the
|
||||
code once Dropbox and GDrive are confirmed clean.
|
||||
|
||||
**Cleaning up orphaned outputs when the job doc is gone** — use the admin endpoint
|
||||
`POST /api/admin/orphaned-outputs/cleanup` with explicit targets (find file IDs and
|
||||
the YouTube video ID in Cloud Run logs from the job's publish window):
|
||||
|
||||
```bash
|
||||
curl -X POST "https://api.nomadkaraoke.com/api/admin/orphaned-outputs/cleanup" \
|
||||
-H "Authorization: Bearer $KARAOKE_ADMIN_TOKEN" -H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"youtube_video_id": "VIDEO_ID",
|
||||
"dropbox_folder_path": "/MediaUnsynced/Karaoke/Tracks-Organized/NOMAD-XXXX - Artist - Title",
|
||||
"gdrive_file_ids": ["...", "...", "..."],
|
||||
"mirror_filename_prefix": "NOMAD-XXXX - Artist"
|
||||
}'
|
||||
```
|
||||
|
||||
The `mirror_filename_prefix` must include artist text after the brand code — the
|
||||
mirror delete refuses a bare `NOMAD-XXXX` so it can never touch the OTHER track
|
||||
legitimately holding the recycled code.
|
||||
|
||||
## Cloud Function vs Local Script
|
||||
|
||||
| Check | Cloud Function | Local Script (`validate_and_sync.py`) |
|
||||
@@ -274,4 +302,5 @@ The cloud function does metadata-only checks via the GDrive API (fast, cheap, ca
|
||||
- **2026-02-28**: Added SendGrid email (primary), kept Pushbullet (fallback). Added post-job trigger from backend. Added `scripts/check_public_share.py` for manual invocation. Motivated by NOMAD-1271 duplicate brand code incident where daily-only checks left a duplicate undetected for ~24 hours.
|
||||
- **2026-03-02**: NOMAD-1276 incident fix. Post-job trigger now uses 5-minute Cloud Tasks delay instead of immediate invocation, preventing false "all clear" when E2E test files are still in GDrive during cleanup. Also fixed cross-folder gap detection (uses global max across all folders) and added 28 unit tests for the Cloud Function.
|
||||
- **2026-03-06**: NOMAD-1295 gap. Stale GCE encoding cache (#499) caused job `f4a552bf` to produce bad output on first run (allocated NOMAD-1295, only CDG uploaded). Admin re-triggered the job, which allocated a new brand code (NOMAD-1297) without recycling 1295. Fix: recycled 1295 back to the pool. Updated docs to clarify that new gaps must always be investigated and fixed, never added to KNOWN_GAPS.
|
||||
- **2026-08-29**: NOMAD-1583 duplicate. Job `e97475ff` (`Mazzy Star – Fade Into You`) published at 02:15 UTC with NOMAD-1583, then was deleted at 03:02 via `DELETE /api/jobs/{id}?delete_files=true` — which recycled the brand code but left all published outputs live (GDrive ×3, Dropbox folder, YouTube video, kjbox mirror ×2). At 04:16 job `326e1aef` (`Chase & Status – No Problem`) reused the recycled 1583 → duplicate in all three share folders. Fixes (v0.206.0): `DELETE /api/jobs/{id}` now runs full distribution cleanup before deleting when outputs are still published (recycle stays gated on Dropbox+GDrive success, shared `_run_distribution_cleanup` helper); jobs whose outputs were already deleted no longer re-recycle; new `POST /api/admin/orphaned-outputs/cleanup` endpoint removes orphaned outputs by explicit IDs when the job doc is gone (used to clean up the Mazzy Star orphans).
|
||||
- **2026-08-18**: NOMAD-1537 gap. A **public→private visibility change** on job `25d076e5` (`Alma Nocturna – Mejor Cállate`) deleted the public GDrive/YouTube/Dropbox outputs and recycled 1537, then the private redistribution crashed (`redistribute_video` drove an illegal `complete → packaging` transition), so the change failed *after* the public files were already gone — a delete-first, no-rollback flow. The daily validator caught the hole; it self-closed when an unrelated public job reused the recycled 1537. **Going-private is a legitimate cause of a transient gap** (the number is recycled and refilled by the next public track) — the alert is expected and desired, not suppressed. Fixes (v0.196.1): `redistribute_video` runs in `redistribute_mode` (no status transition, stays `complete`); `change_to_private` is now **distribute-then-delete** (public outputs removed only after the private archive succeeds; on failure the job stays fully public); failed redistributions recycle any allocated `NOMADNP` code. Validator intentionally left unchanged.
|
||||
@@ -0,0 +1,88 @@
|
||||
# PyPI storage-cap prune runbook
|
||||
|
||||
## The problem
|
||||
|
||||
PyPI caps **total project size at 10 GB**. `karaoke-gen` publishes a universal
|
||||
`py3-none-any` wheel on every merge to `main` (auto-versioned in CI). Since the
|
||||
i18n initiative the wheel bundles a Next.js static export pre-rendered into 33
|
||||
locales (the CLI local lyrics-review UI serves it at runtime), so each release is
|
||||
**~62 MiB**. At ~50 releases/month that's **~3 GB/month**, so the project refills
|
||||
the cap every few months and the publish step fails:
|
||||
|
||||
```
|
||||
HTTP Error 400: Project size too large. Limit for project 'karaoke-gen'
|
||||
total size is 10 GB.
|
||||
```
|
||||
|
||||
Only the public `pip install` publish step fails — the Cloud Run backend and the
|
||||
GCE encoding worker (which pulls the wheel from **GCS**, not PyPI) are unaffected.
|
||||
|
||||
## Why we can't just automate deletion
|
||||
|
||||
PyPI has **no deletion API**. Upload tokens and Trusted Publishing are
|
||||
upload-only, and PyPI mandates 2FA, so deletion is only possible from a
|
||||
logged-in browser session — which can't be safely or durably stored in CI. So we
|
||||
automate the *decision and the reminder*, and keep the *deletion* a ~1-minute
|
||||
human step.
|
||||
|
||||
## Retention policy
|
||||
|
||||
Keep every release from the **last 60 days**, plus the **newest release of each
|
||||
older calendar month**, plus the **latest release overall**. Delete the rest.
|
||||
Run recurringly, this holds steady-state around 6–7 GB — permanently under the
|
||||
cap. Deletion is irreversible and a deleted version/filename can never be
|
||||
re-uploaded; that's acceptable here (nothing builds from source; PyPI is only the
|
||||
public `pip install` channel, whose users want recent versions).
|
||||
|
||||
## How it runs
|
||||
|
||||
- **`.github/workflows/pypi-prune-reminder.yml`** — monthly cron (1st, 09:00
|
||||
UTC) + manual `workflow_dispatch`. Computes the plan and, when there's anything
|
||||
to prune, opens or updates a single tracking issue titled
|
||||
**"🧹 PyPI storage prune due: karaoke-gen"** with the plan + a paste-in
|
||||
deletion snippet. No secrets.
|
||||
- **`scripts/prune_pypi_releases.py`** — the planner. Reads the public JSON API,
|
||||
applies the policy, and renders a table / JSON / Markdown / browser-console JS.
|
||||
It never deletes anything itself.
|
||||
|
||||
## How to prune (≈1 minute)
|
||||
|
||||
1. Open the tracking issue (or run the script locally, below) to get the snippet.
|
||||
2. Go to **<https://pypi.org/manage/project/karaoke-gen/releases/>** and log in.
|
||||
3. Open browser devtools → **Console**.
|
||||
4. Paste the snippet and press Enter. It reads the page's CSRF token and POSTs a
|
||||
whole-version delete for each planned version, ~0.5s apart, logging progress.
|
||||
5. Reload to confirm. If a publish was blocked, re-run it: push an empty commit /
|
||||
re-run the failed CI `Deploy - Publish to PyPI` job, or `poetry publish`
|
||||
locally.
|
||||
|
||||
> The aggregate `pypi.org/pypi/karaoke-gen/json` is Fastly-cached and lags a few
|
||||
> minutes after deletes — trust the logged-in manage page for live state.
|
||||
|
||||
## Running the planner locally
|
||||
|
||||
```bash
|
||||
# Dry-run table (what would be deleted, and the resulting size)
|
||||
python scripts/prune_pypi_releases.py
|
||||
|
||||
# Just the paste-in deletion snippet
|
||||
python scripts/prune_pypi_releases.py --format console-js
|
||||
|
||||
# Machine-readable / the Markdown the workflow posts
|
||||
python scripts/prune_pypi_releases.py --format json
|
||||
python scripts/prune_pypi_releases.py --format markdown
|
||||
|
||||
# Tune the window (default 60 days) or target another project
|
||||
python scripts/prune_pypi_releases.py --keep-days 90 --project karaoke-gen
|
||||
```
|
||||
|
||||
Stdlib only — no dependencies to install.
|
||||
|
||||
## Related
|
||||
|
||||
- One-off escape hatch: request a PyPI storage-limit increase via the
|
||||
`limit-request-project` template on
|
||||
[`pypi/support`](https://github.com/pypi/support) (we filed
|
||||
[pypi/support#12050](https://github.com/pypi/support/issues/12050) for 50 GB).
|
||||
A larger cap just buys time; the recurring prune is the durable fix.
|
||||
- History of the first time this bit us: `docs/LESSONS-LEARNED.md`.
|
||||
@@ -23,6 +23,8 @@
|
||||
| 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 |
|
||||
| **Auto-approval (fully-auto review)** | Live (default `review_mode="auto"`): when the scorer is fully confident (synced-reference lyrics with all gaps AI-covered + no audible backing vocals), the review screens are skipped and the job renders straight through; every other job falls back to human review. Verdict on every job in `processing_metadata.auto_approval`. Kill switch `AUTO_APPROVAL_ENFORCE_ENABLED=false`; per-job `review_mode="always_review"` (admin-editable). See `docs/archive/2026-08-25-full-auto-review-design.md` |
|
||||
| **Review replay tool (admin)** | Working (`?replay=1` read-only replay of completed jobs — see `docs/REPLAY.md`) |
|
||||
| Preview video generation | Working |
|
||||
| Multi-format encoding | Working |
|
||||
| Token-based auth | Working |
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
# Review Replay (read-only re-open of completed jobs)
|
||||
|
||||
Re-open the **real** lyrics-review and instrumental-selection UIs for a job that's
|
||||
already **completed**, with full audio playback + backing-vocals previews (streamed
|
||||
from GCS), plus a side panel showing your ordered actions (AI-accept / AI-reject /
|
||||
manual / timing) from the stored edit log.
|
||||
|
||||
Built for the fully-automated-review recording program — see
|
||||
`docs/archive/2026-08-25-full-auto-review-design.md`.
|
||||
|
||||
## What it is
|
||||
|
||||
- Backend `GET /api/review/{job_id}/correction-data?replay=true` (admin/owner only):
|
||||
serves the same payload for a job in **any** status — skips the
|
||||
AWAITING_REVIEW/IN_REVIEW gate and the status-transition side-effect, and attaches
|
||||
the reviewer's `edit_log`. Purely read-only.
|
||||
- Frontend `?replay=1` on the review/instrumental route: bypasses the state gate
|
||||
(admins), renders the existing UI with `isReadOnly` (no submit / no mutations),
|
||||
and shows the **Replay action log** panel.
|
||||
- `REVIEW_AUDIO_PROXY=1` (local dev only): the backend streams review audio **bytes**
|
||||
instead of GCS signed URLs, because local user ADC can't sign. Inert in prod.
|
||||
|
||||
## Run it locally (against real prod data, read-only)
|
||||
|
||||
```bash
|
||||
# Terminal 1 — backend (needs `gcloud auth application-default login` with read
|
||||
# access to Firestore `jobs` + the GCS bucket; makes NO writes):
|
||||
./scripts/run-replay-local.sh
|
||||
|
||||
# Terminal 2 — frontend:
|
||||
cd frontend && npm run dev # http://localhost:3000
|
||||
```
|
||||
|
||||
Then in the browser:
|
||||
|
||||
1. Open http://localhost:3000, open DevTools console, and sign in as admin:
|
||||
```js
|
||||
localStorage.setItem('karaoke_access_token', 'replay-local-token') // matches ADMIN_TOKENS
|
||||
```
|
||||
Reload — you're now `admin@nomadkaraoke.com`.
|
||||
2. Open a job in replay:
|
||||
- Lyrics review:
|
||||
`http://localhost:3000/en/app/jobs?baseApiUrl=http://127.0.0.1:8000&replay=1#/<JOB_ID>/review`
|
||||
- Instrumental screen:
|
||||
`http://localhost:3000/en/app/jobs?baseApiUrl=http://127.0.0.1:8000&replay=1#/<JOB_ID>/instrumental`
|
||||
|
||||
Audio, vocals waveform, and backing-vocals previews all play (proxied through the
|
||||
local backend). The submit/mutation controls are hidden; nothing can be changed.
|
||||
|
||||
### Editable replay (`&edit=1`) — dev only
|
||||
|
||||
Append `&edit=1` to the replay URL to make the review UI **editable** against the
|
||||
real job's data + audio (e.g. to exercise Tap To Sync / segment editing locally):
|
||||
|
||||
```
|
||||
http://localhost:3000/en/app/jobs?baseApiUrl=http://127.0.0.1:8000&replay=1&edit=1#/<JOB_ID>/review
|
||||
```
|
||||
|
||||
The header reads "Replay (editable · dev)". This flag is guarded by
|
||||
`NODE_ENV !== 'production'` — it is ignored in production builds, where replay stays
|
||||
strictly read-only. Edits are local-only (the replay backend makes no writes).
|
||||
|
||||
## Using it for the recording sessions
|
||||
|
||||
Work through the job list in the private corpus
|
||||
(`~/Projects/nomadkaraoke/docs/automation-corpus/`). For each job, with the replay
|
||||
UI open, narrate the two things we're capturing (the agent writes them into the
|
||||
corpus record):
|
||||
|
||||
1. **Lyrics — what I corrected and why** (per manual edit / AI rejection: why the AI
|
||||
was wrong, how you knew the right answer, whether a deterministic check could catch it).
|
||||
**Timings too**: which timing adjustments you make, and what signal (e.g. the
|
||||
separated vocal audio) could detect them automatically.
|
||||
2. **Backing vocals — what I heard and how I decided** (clean vs. with-backing, why;
|
||||
what would make it a clear yes/no vs. a judgement call).
|
||||
|
||||
The action-log panel groups your edits as **AI ✓ / AI ✗ / manual / timing** so it's
|
||||
easy to talk through what the AI got right, what you overrode, and what's left.
|
||||
|
||||
## Notes / limitations
|
||||
|
||||
- Fidelity is "final state + ordered action log", not a per-keystroke visual replay
|
||||
(no intermediate full-state snapshots are stored). The final lyrics are shown with
|
||||
AI-corrected words tagged (`ai_corrected`, `original_text`, `timing_estimated`).
|
||||
- If a job had its outputs deleted (admin "delete outputs"), stems may be gone and
|
||||
audio won't load — the lyrics/action-log still work.
|
||||
@@ -4,6 +4,21 @@ Operational runbooks for known production issues.
|
||||
|
||||
---
|
||||
|
||||
## CI "Deploy - Publish to PyPI" fails: "Project size too large"
|
||||
|
||||
**Cause:** PyPI caps total project size at 10 GB. Each `karaoke-gen` release is a
|
||||
~62 MiB wheel (bundled 33-locale frontend) auto-published on every merge, so the
|
||||
project refills the cap every few months. Only the public `pip install` publish
|
||||
step fails — Cloud Run and the GCE encoding worker (pulls the wheel from GCS) are
|
||||
unaffected.
|
||||
|
||||
**Fix:** prune old releases per the retention policy. A monthly workflow
|
||||
(`pypi-prune-reminder.yml`) opens/updates a tracking issue with a paste-in
|
||||
deletion snippet, or run `python scripts/prune_pypi_releases.py` yourself. Full
|
||||
runbook: **[docs/PYPI-STORAGE-PRUNE.md](PYPI-STORAGE-PRUNE.md)**.
|
||||
|
||||
---
|
||||
|
||||
## Job stuck at `downloading_audio` status
|
||||
|
||||
**Cause:** Before v0.130.0, audio downloads ran as FastAPI BackgroundTasks. Cloud Run would terminate "idle" instances mid-download. Since v0.130.0, downloads use a Cloud Run Job (`audio-download-job`) and a Cloud Scheduler recovery job runs every 5 minutes to fail stuck downloads automatically.
|
||||
|
||||
@@ -0,0 +1,431 @@
|
||||
# Toward Fully-Automated Review (skip lyrics review + instrumental selection when confident)
|
||||
|
||||
**Status:** Design / research program. Started 2026-08-25.
|
||||
**Author:** Andrew (spec) + agent (design).
|
||||
**Worktree:** `karaoke-gen-full-auto-review`
|
||||
|
||||
---
|
||||
|
||||
## The goal (Andrew's words, verbatim spec)
|
||||
|
||||
> Ideally I'd like to make the karaoke-gen system even more automated, potentially _fully_
|
||||
> automated (skipping the lyrics review and instrumental selection processes entirely) for songs
|
||||
> where for both decisions, we have enough heuristics in place to be pretty confident there are no
|
||||
> potential issues warranting human input.
|
||||
>
|
||||
> However, to actually reach that confidence bar is non-trivial without risking sloppy releases
|
||||
> (which was originally the whole point of the lyrics review UI still being a manual human step).
|
||||
>
|
||||
> Please help me reach that level of automation, starting out with the easy cases where both synced
|
||||
> lyrics are perfect and there's no subjectivity in the backing vocals decision. Then once we have a
|
||||
> couple of working fully auto examples, we can start reviewing every job I complete the
|
||||
> review+select process for, and for each record:
|
||||
> - exactly what did I correct manually in the lyrics review process, and why
|
||||
> - what did I hear when I previewed the backing vocals, how did i make the decision about backing
|
||||
> vocals vs. clean instrumental.
|
||||
>
|
||||
> once we've recorded the output of me making at least 10 tracks, recording my answers for both of
|
||||
> those diligently, in detail, via interactive claude session where I can both describe and share
|
||||
> screenshots... then we can start brainstorming what types of automated checks and (post-AI
|
||||
> correction) heuristic fixes we might be able to apply to fully "solve" (fully automate with
|
||||
> confidence) more whole classes of tracks in the lyrics review. and brainstorm how we could fully
|
||||
> automate the backing vocals decision, turn it into a simple "retain backing vocals where possible?"
|
||||
> (yes/no/review) toggle option made up-front during job submission (defaulting to on).
|
||||
|
||||
Context: Andrew is currently submitting Vocal Star **tenant** test jobs. This applies to **both**
|
||||
public and tenant sides of the product.
|
||||
|
||||
---
|
||||
|
||||
## Guiding principle: shadow-first, never sloppy
|
||||
|
||||
The review UI exists precisely to prevent sloppy releases. So we do **not** flip a switch and hope.
|
||||
The rollout is:
|
||||
|
||||
1. **Shadow** — compute an "auto-approvability" verdict on *every* job at the review gate, record it,
|
||||
but keep sending the job to human review as normal. No behaviour change, zero release risk.
|
||||
2. **Record** — for every job Andrew reviews, capture (a) exactly what he changed in the lyrics and
|
||||
why, (b) what he heard in the backing-vocals preview and how he decided. Store alongside the shadow
|
||||
verdict + all signals that existed at gate time.
|
||||
3. **Validate** — over ≥10 tracks, check the core hypothesis: **does a "would auto-approve" verdict
|
||||
reliably coincide with "Andrew changed nothing / made a non-subjective clean call"?** Tune
|
||||
thresholds against this real ground truth.
|
||||
4. **Enforce (narrow)** — only once validated, let the gate actually skip review for the provably-easy
|
||||
intersection, starting maximally conservative and widening class-by-class as the corpus grows.
|
||||
|
||||
This gives Andrew the "couple of working fully-auto examples" he asked to start with (the narrow safe
|
||||
intersection can be enforced early), while the recording program de-risks widening it.
|
||||
|
||||
---
|
||||
|
||||
## What the system already gives us (investigation results)
|
||||
|
||||
### Lyrics confidence signals (all already in `jobs/{id}/lyrics/corrections.json`)
|
||||
|
||||
`CorrectionResult` (`karaoke_gen/lyrics_transcriber/types.py:609`) serialized per job. Auto-correction
|
||||
is **disabled** in prod, so `corrected_segments` ≈ raw AudioShake transcription and `corrections_made`
|
||||
≈ 0. Useful fields:
|
||||
|
||||
- `original_segments` — raw transcription (words + timings + ids).
|
||||
- `anchor_sequences[]` — runs of transcribed words that matched reference lyrics, each with its own
|
||||
`confidence` and `reference_positions` (which sources agreed).
|
||||
- `gap_sequences[]` — the **uncertain regions** between anchors (transcribed words with no confident
|
||||
reference match). Few/short gaps ⇒ high confidence.
|
||||
- `metadata.rejected_sources` — per reference source: `relevance`, `matched_words`, `total_words`.
|
||||
Strong multi-source agreement is the best proxy for "these lyrics are truly right."
|
||||
- `metadata.anchor_sequences_count`, `gap_sequences_count`, `total_words`.
|
||||
- Per-word `confidence` — **only present for Whisper**, absent for AudioShake (prod). Treat as optional.
|
||||
|
||||
**Derived gate signals** (mirroring `frontend/components/lyrics-review/CorrectionMetrics.tsx:92-99`):
|
||||
- `anchor_word_fraction` = anchored words / total words → want ≈ 1.0
|
||||
- `uncorrected_gap_fraction` = gap words not corrected / total → want ≈ 0.0
|
||||
- `reference_agreement` = ≥N sources with high `matched_words/total_words`
|
||||
|
||||
⚠️ **Trap:** the top-level `CorrectionResult.confidence` is `1.0` whenever correction is *disabled*
|
||||
(`controller.py:593-594`), not because lyrics are perfect. Never gate on it.
|
||||
|
||||
**Strongest "easy case" of all:** a user/tenant-supplied **synced** reference (LRC) that the
|
||||
transcription matches at ~100% anchor coverage with zero gaps. Vocal Star jobs frequently ship their
|
||||
own instrumental + known-good lyrics — a prime full-auto candidate class.
|
||||
|
||||
### Backing-vocals signals (already in `state_data.backing_vocals_analysis`)
|
||||
|
||||
`AudioAnalyzer` (`karaoke_gen/instrumental_review/analyzer.py`) analyses the isolated
|
||||
`backing_vocals.flac` stem: `has_audible_content`, `audible_percentage`, per-segment
|
||||
`avg/peak_amplitude_db`, and a `recommended_selection` (CLEAN / WITH_BACKING; **never** REVIEW_NEEDED).
|
||||
|
||||
- **Non-subjective case:** `has_audible_content == False` ⇒ there are no backing vocals to retain ⇒
|
||||
clean is unambiguously correct. Safe to auto-decide today.
|
||||
- **Subjective case:** audible backing content exists → clean-vs-with is a taste/quality call
|
||||
("does it sound good / help singers / is it just vocal bleed?"). This is what the recording program
|
||||
must characterise before we can automate it. The current energy heuristic cannot: it has no measure
|
||||
of backing-vocal *quality* or of the delta between the two mixes.
|
||||
|
||||
### Where review happens / the insertion point
|
||||
|
||||
- `screens_worker.py:214` unconditionally transitions every job → `AWAITING_REVIEW`. **This is where an
|
||||
auto-skip gate goes.** The `AWAITING_REVIEW → REVIEW_COMPLETE` transition is already legal
|
||||
(`job.py:152`).
|
||||
- `POST /api/review/{id}/complete` (`review.py:472`) is what a human submit does: writes
|
||||
`corrections_updated.json` (only if there are edits), sets `state_data.instrumental_selection`,
|
||||
transitions to `REVIEW_COMPLETE`, triggers render. An auto-path must replicate this — including
|
||||
supplying a default `instrumental_selection` (the selection requirement is enforced only in the HTTP
|
||||
endpoint, not the state machine).
|
||||
- Render consumes `state_data.instrumental_selection` (`clean`|`with_backing`|`custom`); default when
|
||||
absent is already `clean` (`video_worker.py:108`).
|
||||
|
||||
### Existing "what changed" records (insufficient for our purpose)
|
||||
|
||||
- `review_sessions` `changed_words[]` (`review_session.py:14`) — per-word diff, **no why**.
|
||||
- `annotations.json` `CorrectionAnnotation` (`review.py:1345`) — has `agentic_agreed`, **no free-text
|
||||
why, nothing about backing vocals.**
|
||||
|
||||
Neither captures *reasoning*, and nothing captures the backing-vocals listening decision. **That gap is
|
||||
the core of the recording program.**
|
||||
|
||||
---
|
||||
|
||||
## Plan
|
||||
|
||||
### Phase 0 — Recording + shadow-scoring harness (foundation, zero release risk)
|
||||
|
||||
A **plain-files + script** tool (honouring "meta-tooling = plain files + slash commands, never a new
|
||||
UI"). No frontend, no production code-path change.
|
||||
|
||||
**0a. `AutoApprovabilityScorer` (pure function, shared module).** Input: `corrections.json` +
|
||||
`backing_vocals_analysis`. Output: structured verdict per axis —
|
||||
`lyrics: {verdict: auto|review, signals:{anchor_word_fraction, uncorrected_gap_fraction,
|
||||
reference_agreement, total_words, has_synced_reference, ...}, reasons:[...]}` and
|
||||
`backing: {verdict: clean|with|review, signals:{has_audible_content, audible_percentage, loud_segments,
|
||||
...}, reasons:[...]}`. Starts with deliberately conservative thresholds. Fully unit-tested against
|
||||
fixtures. This same module later powers the real gate — build it once, use it in shadow first.
|
||||
|
||||
**0b. `scripts/review_capture.py` (the recording tool).** Given a completed/ reviewed job id:
|
||||
- Pulls `corrections.json` + `corrections_updated.json` + `backing_vocals_analysis` (+ chosen
|
||||
`instrumental_selection`) from GCS/Firestore (read-only; works under `claude-readonly` ADC).
|
||||
- Computes the **structured lyrics diff** (word-text edits, timing nudges, splits/merges, insertions,
|
||||
deletions) = exactly what Andrew changed.
|
||||
- Runs the shadow scorer and prints the verdict + signals next to what Andrew *actually* did.
|
||||
- Emits a per-job record and appends to a corpus.
|
||||
|
||||
**0c. The corpus** (`docs/automation-corpus/` or similar, in-repo, plain files):
|
||||
- `jobs/{job_id}.md` — human-readable: song, signals, shadow verdict, the diff, and Andrew's dictated
|
||||
**why** (lyrics) + **backing-vocals reasoning** (what he heard, how he decided). Screenshots welcome.
|
||||
- `corpus.jsonl` — one machine-readable row per job for later threshold calibration.
|
||||
- `README.md` — running tally toward the ≥10-track target + emerging patterns.
|
||||
|
||||
**0d. Interactive flow** (this is the "via interactive claude session" Andrew described): after Andrew
|
||||
finishes a review, we run the tool, look at the diff + signals together, and he dictates the reasoning;
|
||||
the agent writes it into the corpus. Screenshots pasted into the session get referenced.
|
||||
|
||||
**0e. (optional, tiny) shadow logging in prod** — write the scorer's verdict into
|
||||
`processing_metadata.auto_approvability` at the `screens_worker` gate, without changing behaviour, so
|
||||
we accumulate verdicts on jobs even when we don't run the capture tool. Deferred until 0a-0d prove out.
|
||||
|
||||
### Phase 1 — Narrow, conservative enforcement (the "couple of fully-auto examples")
|
||||
|
||||
Once a handful of jobs in the corpus show the safe intersection firing correctly, enable **actual**
|
||||
auto-skip in `screens_worker` for that intersection **only**:
|
||||
- Lyrics: synced reference present AND anchor_word_fraction ≥ (high) AND uncorrected_gap_fraction ≈ 0.
|
||||
- Backing: `has_audible_content == False` → auto-select `clean`.
|
||||
- Everything else → human review, unchanged.
|
||||
- Guardrails: feature-flagged (env), tenant-scoped opt-in first (Vocal Star), full audit trail in
|
||||
`processing_metadata`, and a kill switch. Auto-approved jobs still get every downstream QC that exists.
|
||||
|
||||
### Phase 2 — Widen by class (after ≥10 recorded tracks)
|
||||
|
||||
Brainstorm + build **post-AI-correction heuristic fixes** and **checks** that let whole classes pass
|
||||
without human input, driven by patterns in the corpus (e.g. common mechanical corrections Andrew makes
|
||||
that we can auto-apply and then re-verify; classes of gap that are reliably safe to accept).
|
||||
|
||||
### Phase 3 — Backing-vocals up-front toggle
|
||||
|
||||
Add `retain_backing_vocals: yes|no|review` (default `yes`) to submission (`URLSubmissionRequest` /
|
||||
`UploadSubmissionRequest` → `JobCreate` → `state_data`). Semantics:
|
||||
- `no` → force `clean`, skip instrumental step.
|
||||
- `yes` → retain backing **where the (improved) analysis says it's safe**, else fall back per policy.
|
||||
- `review` → today's human behaviour.
|
||||
Requires a better backing-vocal quality signal than the current energy threshold — the corpus reasoning
|
||||
is what tells us what "sounds good enough to retain" actually means.
|
||||
|
||||
---
|
||||
|
||||
## Day-1 validation (scorer + capture harness, 2026-08-25)
|
||||
|
||||
Built the shared scorer (`backend/services/auto_approval/`), the review-diff, and
|
||||
`scripts/review_capture.py`, then shadow-scanned 30 recent completed jobs (read-only):
|
||||
|
||||
- **1/30 would fully auto-approve today** — `56411c70` Nat King Cole "Never Let Me Go":
|
||||
100% anchor, 0 gaps, **0 lyric edits**, no audible backing → clean. Independently the
|
||||
scorer said AUTO. That's the first genuine fully-auto example, with no false positives in
|
||||
the batch.
|
||||
- **The predictive hypothesis broadly holds:** high anchor / low gap ⇒ few edits; low anchor
|
||||
⇒ many edits (e.g. 61.6% anchor → heavy correction). But it is *not* perfectly monotonic —
|
||||
some ~95-98% jobs needed only a handful of edits, one 94% job needed 269. This is exactly
|
||||
why the reasoning corpus is needed: to learn *which* edits the high-coverage jobs still need.
|
||||
- **Key threshold finding → applied:** job `79c4f60c` "Clarity" scored 99.6% anchor with a
|
||||
**single gap word**, which turned out to be a real mis-transcription the reviewer fixed
|
||||
(`I` → `High`). A gap word is by definition a word with no confident reference match — where
|
||||
errors hide. So the AUTO tier was tightened from "≤1% gap" to **zero unresolved gaps**
|
||||
(`AUTO_MAX_GAP_FRACTION = 0.0`). This demotes Clarity to `near-miss`/review while keeping
|
||||
Nat King Cole as AUTO. Regression test: `test_single_gap_word_blocks_auto`.
|
||||
- **Diff quality:** the review UI re-keys a word's id when its text is replaced but preserves
|
||||
its timing/line, so text corrections first appeared as delete+insert. The diff now pairs
|
||||
them into clean **replacements** (`Carl → Karl`, `they're → their`, `you've → you`).
|
||||
|
||||
Deliverables this session (all tested, 21 unit tests):
|
||||
`backend/services/auto_approval/{models,scorer,lyrics_diff}.py`,
|
||||
`scripts/review_capture.py`, corpus scaffold at workspace-root `docs/automation-corpus/`.
|
||||
|
||||
## Session 2 update (2026-08-25) — replay tool + corrected baseline
|
||||
|
||||
Andrew refined the plan: instead of capturing via offline markdown diffs, **replay the
|
||||
real review UIs** for past completed jobs (full audio/backing previews from GCS) and
|
||||
narrate the decisions, then walk the **20 most-recent `admin@nomadkaraoke.com` jobs**.
|
||||
|
||||
**Critical correction to the lyrics baseline.** AI auto-correct is doing the heavy
|
||||
lifting (proactive suggestions, accepted in the review UI). The **authoritative record
|
||||
of what happened is the `edit_log_*.json`** (ordered, typed ops: `ai_suggestion_accept`
|
||||
/ `ai_suggestion_reject` / manual `word_*` / `timing_change`), plus `ai_corrected` /
|
||||
`original_text` / `timing_estimated` provenance baked into saved words. My earlier raw
|
||||
`corrections.json → corrections_updated.json` id-diff was misleading (word-id
|
||||
regeneration inflated del/ins). **Right baseline = post-AI; the interesting signal =
|
||||
residual manual edits + AI rejections (⚠️ superseded: session-3 established these are the auto-apply's own conflict resolution, NOT human decisions — see session-4 update) + timing.**
|
||||
|
||||
Findings from the 20 admin jobs (edit_log counts): AI solves lyrics outright on several
|
||||
(0 manual, 0 reject: d508adb6, 69ca7c1e, 507513ba, b5a7b8aa, 35ed9697, f986dfe5); AI
|
||||
rejections cluster the failure modes (f247364e=15, 44622ffa=5, 8e465dc7=4); residual
|
||||
manual concentrates in a few (a4dcaa21=17, 95d8e844=12). **⚠️ Zero `timing_change` ops
|
||||
logged across all 20** despite timing being a stated axis — open question for the sessions.
|
||||
|
||||
**Built + verified end-to-end against real prod data (read-only):**
|
||||
- Backend replay: `GET /correction-data?replay=true` (full-auth only) skips the status
|
||||
gate + transition and attaches the `edit_log`. `review.py`.
|
||||
- Dev audio proxy: `REVIEW_AUDIO_PROXY=1` streams review audio **bytes** (local user ADC
|
||||
can't sign GCS URLs; impersonating the backend SA is denied and granting it is a GCP
|
||||
write we won't make). New `GET /{job}/dev-audio` (prod-inert). Wired into
|
||||
correction-data, instrumental-analysis, `_stream_audio`, waveform.
|
||||
- Frontend replay: `?replay=1` bypasses the state gate (admin), passes `isReadOnly` to
|
||||
the already-wired `LyricsAnalyzer` + new `isReadOnly` on `InstrumentalSelector`, and
|
||||
renders a **ReplayActionLog** panel (AI✓/AI✗/manual/timing). `client.tsx`.
|
||||
- Run locally: `./scripts/run-replay-local.sh` + `cd frontend && npm run dev`. See
|
||||
`docs/REPLAY.md`. Job queue: private corpus `docs/automation-corpus/REVIEW-QUEUE.md`.
|
||||
- Tests: 5 new backend (replay gate/auth + dev-audio inert), 61 review-suite pass; 21
|
||||
scorer/diff tests pass; frontend changed files typecheck clean.
|
||||
|
||||
**Remaining (post-sessions):** refine AI-vs-manual attribution into the corpus
|
||||
(edit_log-driven), design timing-adjustment detection (incl. vocal-audio signal for
|
||||
cut-off sustained words), and the backing-vocals decider + up-front toggle
|
||||
(retain-where-possible / clean / review).
|
||||
|
||||
## Open questions / decisions
|
||||
|
||||
- **Corpus location & format** — `docs/automation-corpus/` in this repo vs workspace-level. (Leaning
|
||||
in-repo so it travels with the code that consumes it.)
|
||||
- **How much to enforce early** — stay in pure shadow until ≥N corpus jobs, or enable the ultra-narrow
|
||||
intersection as soon as it's proven on 2-3 jobs (Andrew's "couple of working examples").
|
||||
- **Public vs tenant first** — tenant (Vocal Star, own instrumental + known lyrics) is the safest place
|
||||
to enable narrow enforcement first.
|
||||
|
||||
---
|
||||
|
||||
## Key file/line index (for implementers)
|
||||
|
||||
| Concern | Location |
|
||||
|---|---|
|
||||
| Correction data model | `karaoke_gen/lyrics_transcriber/types.py:609` (`CorrectionResult`) |
|
||||
| Confidence/metadata computation | `karaoke_gen/lyrics_transcriber/correction/corrector.py:203-256` |
|
||||
| `confidence=1.0`-when-disabled trap | `karaoke_gen/lyrics_transcriber/core/controller.py:593-669` |
|
||||
| Review gate (insertion point) | `backend/workers/screens_worker.py:214` |
|
||||
| Human review-complete behaviour to mirror | `backend/api/routes/review.py:472-604` |
|
||||
| Legal auto transition | `backend/models/job.py:152` (`AWAITING_REVIEW→REVIEW_COMPLETE`) |
|
||||
| BV energy analysis + recommendation | `karaoke_gen/instrumental_review/analyzer.py:80-165, 380-409` |
|
||||
| BV analysis invocation + storage | `backend/workers/screens_worker.py:533-637`, `state_data.backing_vocals_analysis` |
|
||||
| Instrumental selection → stem mapping | `backend/workers/video_worker.py:1341-1380,1438-1464` |
|
||||
| Submission-time options | `backend/models/requests.py:8-40`, `backend/models/job.py:540-609` (`JobCreate`) |
|
||||
| Existing "what changed" records | `backend/models/review_session.py:14`, `backend/api/routes/review.py:1345` |
|
||||
|
||||
---
|
||||
|
||||
## Session 4 update (2026-08-27) — shadow gate WIRED + scorer v0.2.0
|
||||
|
||||
The shadow scorer is now wired into the pipeline (`screens_worker._record_auto_approval_shadow`,
|
||||
called just before the AWAITING_REVIEW transition; non-fatal; writes
|
||||
`processing_metadata.auto_approval_shadow`). Scorer v0.2.0 adds, from the 20-job corpus findings:
|
||||
|
||||
- **P3 vocalization gate** (runs of ≥5 vocalization tokens / multi-second "Ooh"s) and
|
||||
**P8 phantom gate** (words >5s; stretched short parenthetical lines) — never-auto classes that
|
||||
override everything.
|
||||
- **AI-suggestion awareness**: the proactive auto-correct cache
|
||||
(`jobs/{id}/lyrics/auto_correct_cache/`) is loaded at scoring time; gap words *covered* by a
|
||||
suggestion are auto-fixed on review load, so confidence keys off the **uncovered** remainder.
|
||||
New AUTO tier `ai-resolved`: synced ref + anchor ≥90% + uncovered ≤2% and ≤6 words + no gates.
|
||||
|
||||
Calibration vs the 20-job corpus (full table in the private corpus,
|
||||
`docs/automation-corpus/scorer-calibration-2026-08-27.md`): **safety 100%** (all truly-human jobs
|
||||
gated), lyrics auto 3/20, overall auto 1/20. Raw gap counts demonstrably do NOT separate AI-solved
|
||||
from human-needed jobs; suggestion coverage does.
|
||||
|
||||
Next per SYNTHESIS build order: collect shadow verdicts on live traffic; build the Pattern 4
|
||||
leading-connective auto-fixer (+P1 dedupe, P5 reference-majority); then revisit thresholds and
|
||||
begin enforcement (tenant jobs first).
|
||||
|
||||
---
|
||||
|
||||
## Session 4b update (2026-08-27, same session) — ENFORCEMENT SHIPPED
|
||||
|
||||
Andrew's directive: *"keep driving towards eventually shipping fully auto processing, on by
|
||||
default, for all gen users, only showing the lyrics and/or instrumental review screens when one
|
||||
or the other is unsolved / definitely needs human review"* → shipped the framework + the
|
||||
narrow fully-confident class:
|
||||
|
||||
- **`Job.review_mode`** (`"auto"` default | `"always_review"`, admin-PATCH-editable) — the
|
||||
autonomy/review-level setting. Legacy `non_interactive` is untouched (CLI packaging semantics;
|
||||
never gated the cloud review).
|
||||
- **`backend/services/auto_approval/apply.py`** — faithful server-side port of the review UI's
|
||||
on-load auto-apply (`autoCorrectApply.ts` + `autoCorrectConflicts.ts` + `acceptAll`):
|
||||
replace/insert_after/delete ops, timing distribution, word provenance flags, conflict-group
|
||||
winners by consensus→confidence. Plus `find_suspicious_duplicates` (the P1 self-conflict
|
||||
duplicate-word signature, reference-aware).
|
||||
- **`backend/services/auto_approval/executor.py`** — `maybe_auto_complete_review(job_id, trigger)`
|
||||
called from `screens_worker` (pre-AWAITING_REVIEW) and `audio_worker` (post-analysis, for
|
||||
audio-lags-lyrics ordering). Scores + records `processing_metadata.auto_approval` on EVERY job;
|
||||
enforces only when: flag on + review_mode=auto + not made-for-you + no existing/custom
|
||||
instrumental + `overall_auto` + audio complete + clean stem present. Enforce = apply cached AI
|
||||
suggestions server-side → sanity checks (stale/duplicates/empty ⇒ abort to review) →
|
||||
`corrections_updated.json` → instrumental=clean → clear progress keys →
|
||||
GENERATING_SCREENS→REVIEW_COMPLETE (new legal edge; skips the review notification entirely) →
|
||||
trigger render worker. FAIL-SAFE: every anomaly/exception falls back to normal human review.
|
||||
- **Backing-analysis-error trap fixed**: a failed analysis stores `has_audible_content=None`,
|
||||
which previously read as `False` ("no audible content") in the scorer — would have wrongly
|
||||
auto-picked clean. Now treated as analysis-absent → review.
|
||||
- Kill switch: `AUTO_APPROVAL_ENFORCE_ENABLED=false` (scoring/recording continues).
|
||||
|
||||
Expected initial auto rate ~5% of jobs (1/20 in the calibration corpus): lyrics must be
|
||||
synced-perfect or ai-resolved AND backing must be non-subjectively clean. Widening comes from
|
||||
build-order #2-#4 (P4 fixer, vocalization detector already gating, backing decider).
|
||||
|
||||
## Session 5 update (2026-08-28) — Phase 2A: deterministic P4/P1/P5 fixers (v0.203.0)
|
||||
|
||||
Build-order item #2 shipped: the three mechanical residual-edit classes from the corpus are now
|
||||
**deterministic suggestion generators inside the auto-correct pipeline** (not executor hacks), so
|
||||
one mechanism feeds the review UI's on-load auto-apply, the executor's server-side apply, the
|
||||
scorer's gap-coverage signal, and the proactive cache.
|
||||
|
||||
- **`backend/services/auto_correct/deterministic.py`** (new) — pure generators keyed off
|
||||
`corrections.json` gap/anchor alignment:
|
||||
- **P4 leading-connective delete**: segment starts with And/But/So/Oh/A, the word is a gap
|
||||
word, and no reference source's reading of that gap contains it → emit `delete` (+ a
|
||||
`replace` re-capitalizing the next word when lowercase). Guard: skipped when the next word is
|
||||
a vocalization token (an "Oh- whoa," run is musical judgement, corpus 5c80991d).
|
||||
- **P5 reference-majority replace**: a gap whose transcription contains an implausible proper
|
||||
noun (capitalized mid-line token absent from every reference) and where ≥2/3 of reference
|
||||
sources agree on the same reading → replace with the majority reading. The red flag is
|
||||
REQUIRED — plain 2/3 majority over-fires on gaps the human deliberately left (6d0640fa
|
||||
"though"→"dog", explicit-lyrics rewrite). Spelling-variant guard: a red-flag token
|
||||
string-similar (≥0.75) to a reference token is a transliteration/truncation ("Crick"~
|
||||
"Cricket", "Projectorinsky"~"Projektorinski") whose gap alignment is often junk → skip
|
||||
(that's the LLM's fix).
|
||||
- Per-source gap readings come from the gap's own `reference_word_ids`, else are derived by
|
||||
walking the reference stream past the surrounding anchors (the 6d0640fa "Come here," case —
|
||||
the aligner had empty alignments for 2 of 3 sources).
|
||||
- **P1 self-conflict grouping at source** — `service._assign_conflict_groups` (extracted, reused
|
||||
post-integration) now also unions an `insert_after` with any suggestion targeting/anchored on
|
||||
the same word whose new_text shares a token: the f6439692 "insert you're + replace fire→fire,
|
||||
you're → 'you're you're'" signature becomes a pick-one conflict group (winner by consensus→
|
||||
confidence picks the 0.95 replace — correct). Executor's `find_suspicious_duplicates` abort
|
||||
stays as belt-and-braces.
|
||||
- Pipeline: `suggest(..., correction_data=None)` — proactive worker passes corrections.json in;
|
||||
the review route lets the service fetch it (best-effort). Deterministic suggestions identical
|
||||
to an LLM one just tag it (`models += ["deterministic"]`); new ones append; conflict groups are
|
||||
recomputed over the combined set. Suggestion-cache key bumped to v2 (old cached results predate
|
||||
the fixers).
|
||||
- **Corpus validation** (private validate_scorer.py, extended with FIXER assertions): safety
|
||||
still 100% (all MUST_NOT_AUTO stay review; gates unchanged). P4 fires on all six corpus
|
||||
examples; P5 reproduces Andrew's one ref-majority edit ("yo Mick,"→"Come here,") and fires
|
||||
nowhere it must not. **6d0640fa (Miguel) now scores lyrics=auto + clean backing → would fully
|
||||
auto-ship WITH the human's exact edit applied**; ae0cd7e8 (Samson corpus job) now has its P4
|
||||
edits actually applied when auto-shipping. `ai-resolved` caps deliberately NOT loosened
|
||||
(69ca7c1e still 14 uncovered words — needs more coverage, not looser caps).
|
||||
|
||||
## Session 6 update (2026-08-28) — Phase 2B: 3-stem backing decider (v0.204.0)
|
||||
|
||||
Build-order item #4 shipped (decider + signals; enforcement shadow-first):
|
||||
|
||||
- **`karaoke_gen/instrumental_review/stem_comparison.py`** (new, pure pydub) — compares the
|
||||
backing / lead / full-vocals stems: audible coverage per stem + coverage ratio, envelope
|
||||
Pearson correlations (backing↔vocals, backing↔lead), median audible levels, lead-overlap
|
||||
fraction, within-run flatness. Wired into `_analyze_backing_vocals` (screens_worker →
|
||||
AudioAnalysisService) → stored as `backing_vocals_analysis.stem_comparison` on every new job.
|
||||
- **Scorer v0.3.0** — `score_backing` decides the pink-present branch (previously always
|
||||
review): confident **WITH_BACKING** (non-subjective keep) unless one of the corpus-validated
|
||||
"pink but don't keep" modes fires: backing-stem-IS-the-lead (covR ≥0.80 + corr ≥0.80 +
|
||||
backing more present than lead — the decisive discriminator; the dB-margin idea nearly
|
||||
misfired on a genuine keep), noise-floor signature (median ≤ −35 dB over ≥15% of track,
|
||||
corr ≤0.05 — REVIEW, marginal per corpus), narrow bleed rule (≤3% audible, lead overlap
|
||||
≥0.95 — d508adb6's genuine 0.89-overlap harmonies must stay keepable).
|
||||
- **Corpus validation (validate_backing_decider.py, private; ~2.4 GB stems cached locally):
|
||||
13/14 true keeps → confident WITH_BACKING — including BOTH jobs the human under-kept
|
||||
(44622ffa, 35ed9697): the decider beats the human's quick review. 95d8e844 (marginal
|
||||
grungegaze) → review. All clean-correct jobs → clean. 1d45b286 (catastrophic
|
||||
backing-is-lead) → review. Zero unsafe outcomes.**
|
||||
- **Executor**: WITH_BACKING verdict enforces `instrumental_selection="with_backing"` ONLY
|
||||
behind `AUTO_APPROVAL_BACKING_KEEP_ENABLED` (default **false** — shadow-first per plan);
|
||||
while off, such jobs record blocker `backing_keep_disabled` + full verdict/signals in
|
||||
`processing_metadata.auto_approval` for prod shadow calibration alongside human picks.
|
||||
Requires the `instrumental_with_backing` stem (blocker `no_with_backing_stem`).
|
||||
- Flip-on procedure: review shadow verdicts vs human picks for a while, then set
|
||||
`AUTO_APPROVAL_BACKING_KEEP_ENABLED=true` on the backend service. The Cher-class jobs
|
||||
(lyrics solved, gated only by audible backing — 46201da4) then become fully auto.
|
||||
|
||||
## Session 7 update (2026-08-28 evening) — Phase 2D: user-supplied-instrumental jobs auto-complete (v0.205.0)
|
||||
|
||||
Tenant/bulk jobs (and any job with `existing_instrumental_gcs_path` or a `custom_instrumental`
|
||||
stem) previously carried the `custom_instrumental` enforcement blocker. But these jobs have NO
|
||||
instrumental decision — the human flow completes them with `instrumental_selection="custom"`
|
||||
(validated in review.py complete; video worker prefers the user-provided source). Executor now:
|
||||
confident lyrics alone ⇒ auto-complete with selection="custom"
|
||||
(`enforcement_basis="lyrics_only_custom_instrumental"` recorded in the payload; backing verdict
|
||||
moot). Non-custom jobs unchanged (`overall_auto`). Per-job opt-out stays `review_mode=
|
||||
"always_review"`; per-tenant default config is future work (workstream C/D follow-up).
|
||||
This makes tenant bulk uploads the highest-auto-rate population (B2B throughput).
|
||||
@@ -0,0 +1,147 @@
|
||||
# Full-Auto Review — Session Handoff (2026-08-27)
|
||||
|
||||
Comprehensive handoff for a fresh Claude session picking up the "fully-automated review" initiative.
|
||||
Read this + the two design docs + the private corpus, then continue from **§8 Next steps**.
|
||||
|
||||
- **Initiative goal (Andrew's spec):** make karaoke-gen able to SKIP the manual lyrics-review +
|
||||
instrumental-selection steps for tracks where we're confident it's safe — without sloppy releases.
|
||||
Start with easy cases, record real review decisions, then build heuristics + gating.
|
||||
- **Worktree:** `<workspace>/karaoke-gen-full-auto-review`
|
||||
**Branch:** `feat/sess-20260825-0000-full-auto-review` (all work UNCOMMITTED).
|
||||
- **Design docs:** `docs/archive/2026-08-25-full-auto-review-design.md` (original plan + session-2 update),
|
||||
this handoff, `docs/REPLAY.md` (how to run the replay tool).
|
||||
- **Corpus (PRIVATE, workspace root — NOT in the public repo):**
|
||||
`<workspace>/docs/automation-corpus/ (private, outside this repo)` →
|
||||
`SYNTHESIS.md` (★ read first), `lyrics-manual-edit-patterns.md`, `backing-vocals-decision-logic.md`,
|
||||
`REVIEW-QUEUE.md`, `jobs/*.md` (20 per-job records), `snapshots/`.
|
||||
|
||||
---
|
||||
|
||||
## 1. TL;DR of what happened across 3 sessions
|
||||
|
||||
- **Session 1:** built the offline `AutoApprovabilityScorer` + review-diff + a capture script + corpus
|
||||
scaffold; validated against 30 real jobs.
|
||||
- **Session 2:** built the **replay tool** — reopen the real lyrics/instrumental review UIs read-only for
|
||||
COMPLETED jobs, with audio, running LOCALLY against prod data (read-only).
|
||||
- **Session 3 (this one):** walked all **20** most-recent `the admin account` jobs in the replay UI
|
||||
with Andrew, recording his reasoning → produced the full **pattern catalogue + SYNTHESIS.md**. Also
|
||||
hardened the replay tool (nav bar, Post-AI toggle, audio seeking) and fixed several reconstruction bugs.
|
||||
|
||||
## 2. ★ The key conceptual reframe (read this or you'll misread everything)
|
||||
|
||||
**AI lyric suggestions AUTO-APPLY on load** (`frontend/hooks/useAutoCorrect.ts` `autoApplyOnLoad` →
|
||||
`acceptAll(true)`). Andrew never manually reviews them. Therefore in a job's `edit_log`:
|
||||
- `ai_suggestion_accept` / `ai_suggestion_reject` = the **auto-apply's own conflict resolution**, NOT
|
||||
human decisions. **Ignore AI✗ counts as a human signal.** (Jobs I first flagged as "15-rejection
|
||||
goldmines" are actually near-pure-AI wins.)
|
||||
- **Only the non-`ai_suggestion` ops are Andrew's** (`word_change/word_delete/word_add/segment_*/
|
||||
timing_change/find_replace`). Those are the real residual work.
|
||||
|
||||
So the goal is NOT "skip a manual step" — it's **"per track, is the auto-applied result safe to ship, or
|
||||
does it need a human glance?"** 8/20 jobs had zero human edits.
|
||||
|
||||
## 3. The findings (see SYNTHESIS.md for full detail)
|
||||
|
||||
**Lyrics — 3-tier strategy:**
|
||||
- **★ MASTER GATE = post-AI confidence score** (anchor coverage + gap fraction/count + #corrections +
|
||||
phantom/absurd-duration flags). Low → human; high → auto-ship. This is *exactly* what
|
||||
`backend/services/auto_approval/scorer.py` already computes — Andrew reinvented it independently.
|
||||
- **Auto-fix classes:** **P4** leading connective/interjection over-insertion (`And`/`Oh`/`A`, seen 6× —
|
||||
biggest win); **P5** reference-majority (≥2/3) resolution; **P1** dedupe AI self-conflicting suggestions.
|
||||
- **Gate→human (never auto):** **P3** vocalization sections (da-da-dun/woo-woo — dominates heavy-manual
|
||||
jobs); **P6** missed line; **P8** phantom/hallucinated lines (absurd durations).
|
||||
- **Defer:** **P7** trailing parenthetical backing bits → delete + extend last word (= the real timing
|
||||
axis; detect via lead-vocal audio energy after the transcribed end-time).
|
||||
|
||||
**Backing:** no-pink → clean (always right in data); pink → **KEEP** (human UNDER-keeps — 2/8 clean picks
|
||||
were wrong). Bias to keep. "Pink but don't keep" needs **3-stem analysis** (mixed/lead/backing): lead
|
||||
bleed (ae0cd7e8), backing-stem-IS-lead when lead quiet/reverby (1d45b286, catastrophic if kept),
|
||||
flat-noise pink (95d8e844). Maps to the up-front toggle `retain-where-possible(default)/clean/review`.
|
||||
|
||||
## 4. Code built (all in the worktree, UNCOMMITTED)
|
||||
|
||||
New:
|
||||
- `backend/services/auto_approval/{__init__,models,scorer,lyrics_diff}.py` — the shadow scorer +
|
||||
review-diff. Pure, tested. Will power the real gate at `screens_worker.py:214` later.
|
||||
- `backend/tests/services/auto_approval/{test_scorer,test_lyrics_diff}.py` (21 tests).
|
||||
- `scripts/review_capture.py` — offline per-job corpus record generator (superseded in practice by the
|
||||
replay UI, but still works).
|
||||
- `scripts/run-replay-local.sh` — one-command local replay backend.
|
||||
- `docs/REPLAY.md`, `docs/archive/2026-08-25-full-auto-review-design.md`.
|
||||
|
||||
Modified (the replay tool):
|
||||
- `backend/api/routes/review.py` — `GET /correction-data?replay=true` (admin/owner only): serves review
|
||||
data for ANY status (skips the status gate + the AWAITING→IN_REVIEW transition), attaches the parsed
|
||||
`edit_log` + a reconstructed `post_ai_segments` ("post-AI, pre-human" state). Plus a **dev-only audio
|
||||
byte-proxy** (`GET /{job}/dev-audio`, gated by env `REVIEW_AUDIO_PROXY`, supports HTTP Range) so review
|
||||
audio plays locally without GCS URL-signing. Helpers: `_reconstruct_post_ai_segments`, `_load_edit_log`,
|
||||
`_dev_audio_url`, `_ranged_response`, `_dev_audio_proxy_enabled`. Prod behaviour unchanged (flag off).
|
||||
- `backend/tests/test_routes_review.py` — +5 tests (replay gate/auth, dev-audio inert). 61 pass.
|
||||
- Frontend: `frontend/app/[locale]/app/jobs/[[...slug]]/client.tsx` (replay mode via `?replay=1`:
|
||||
bypass state gate for admin, `isReadOnly`, `ReplayNavBar` Prev/Next+Lyrics/Instrumental via `queue`
|
||||
URL param, `ReplayActionLog` panel, Post-AI/Final toggle), `components/instrumental-review/
|
||||
InstrumentalSelector.tsx` (+`isReadOnly` prop), `lib/api.ts` (+`replay` opt), `lib/lyrics-review/
|
||||
types.ts` (+`replay` fields). Changed files typecheck clean.
|
||||
|
||||
**Tests:** `python -m pytest backend/tests/services/auto_approval/ backend/tests/test_routes_review.py`
|
||||
→ 82 pass. Full `make test` NOT yet run. No version bump yet. Not PR'd.
|
||||
|
||||
## 5. How to resume the local replay environment
|
||||
|
||||
Backend + frontend may still be running from this session (check `curl localhost:8000/api/health` and
|
||||
`localhost:3000`). To (re)start:
|
||||
```bash
|
||||
cd <workspace>/karaoke-gen-full-auto-review
|
||||
./scripts/run-replay-local.sh # backend :8000, REAL prod data (read-only), REVIEW_AUDIO_PROXY on
|
||||
# in another terminal:
|
||||
cd frontend && npm run dev # :3000
|
||||
```
|
||||
Then in the browser: `localStorage.setItem('karaoke_access_token','replay-local-token')`, reload, and open:
|
||||
```
|
||||
http://localhost:3000/en/app/jobs?baseApiUrl=http://127.0.0.1:8000&replay=1&queue=<comma-ids>#/<jobId>/review
|
||||
```
|
||||
The 20-job `queue=` string is in `REVIEW-QUEUE.md` / the session transcript. Requires `gcloud auth
|
||||
application-default login` with READ access to Firestore `jobs` + GCS `karaoke-gen-storage-nomadkaraoke`.
|
||||
**Driving it in Playwright:** the Playwright browser is shared with Andrew (he can interact with the same
|
||||
window). You can extract his live in-browser edits via a React fiber full-tree walk (see transcript for the
|
||||
snippet) — needed because read-only blocks *save*, not in-UI editing.
|
||||
|
||||
## 6. Gotchas / caveats (IMPORTANT)
|
||||
|
||||
- **Don't trust the Post-AI reconstruction blindly.** It had 3 bugs this session (multi-word-replace
|
||||
"cram", dropped words, split-word identical timing) that briefly misled Andrew into thinking the AI had
|
||||
bugs it didn't. All fixed, but: **treat `corrections_updated.json` (final) as ground truth**; use the
|
||||
reconstruction/edit_log for *what changed*, not exact values.
|
||||
- **edit_log is not always complete** — it can miss segment-level deletions (e.g. 33453fa0's phantom-line
|
||||
deletes aren't in its log though the final has them removed). Use raw→final diff for completeness.
|
||||
- **Same-job reload doesn't re-fetch** after a backend change (SPA); do a hard reload (Cmd+Shift+R).
|
||||
- **Prod bucket = `karaoke-gen-storage-nomadkaraoke`** (config default `karaoke-gen-storage` is overridden
|
||||
by env in prod). Prod Firestore collection = `jobs`.
|
||||
- **GCP is read-only for this workspace** (claude-readonly ADC / here it was admin@ ADC but no
|
||||
Token-Creator). Can't sign GCS URLs locally (hence the dev-audio byte-proxy) and can't impersonate the
|
||||
backend SA. Don't attempt IAM/Pulumi writes.
|
||||
- **Public repo:** never commit customer emails / the private corpus into `karaoke-gen`. Corpus lives at
|
||||
workspace root on purpose.
|
||||
|
||||
## 7. What's PR-ready vs not
|
||||
|
||||
The scorer/diff/tests and the replay tool are self-contained and green. Before PR: run full `make test`,
|
||||
bump `pyproject.toml` version, `/docs-review`, `/coderabbit`. The dev-audio proxy + replay param are
|
||||
prod-inert (env/flag gated) so shipping them is low-risk, but confirm the `?replay=true` admin-gating and
|
||||
that `REVIEW_AUDIO_PROXY` is unset in prod. (Frontend `?replay=1` is admin-only via the existing gate.)
|
||||
|
||||
## 8. ★ Next steps (build order, from SYNTHESIS.md §4)
|
||||
|
||||
1. **Confidence gate (shadow → enforce).** Wire `auto_approval/scorer.py` into `screens_worker.py:214` in
|
||||
SHADOW mode (record verdict in `processing_metadata`, no behaviour change); validate its verdict
|
||||
against the 20-job corpus; then enforce (auto-ship high-confidence, route rest to human). Add the new
|
||||
signals: phantom/absurd-duration (P8), vocalization detector (P3).
|
||||
2. **Pattern 4 auto-fixer** (leading connective/interjection) — validate against the 6 examples in the
|
||||
corpus. Then **P1 dedupe** + **P5 reference-majority** in the AI-correct step.
|
||||
3. **Vocalization detector (P3)** → force human review (also feeds the gate).
|
||||
4. **Backing decider + 3-stem analysis** (bias-to-keep; reject bleed / lead-misclassification /
|
||||
flat-noise) → ship the up-front `retain backing vocals?` toggle (default retain-where-possible).
|
||||
5. **Timing: trailing-word extension via lead-vocal audio** (P7 + end-time-too-early) — later.
|
||||
|
||||
No new transcription model needed for 1–4; hard problems are *gated*, not solved. Start with #1 (validates
|
||||
the whole thesis cheaply) unless Andrew redirects.
|
||||
@@ -0,0 +1,106 @@
|
||||
# Full-Auto Review — Workstream C implementation plan (2026-08-29)
|
||||
|
||||
Single PR covering C1 (per-screen skip), C2 (server-side pre-apply), C3 (submission UI).
|
||||
Ships via full /shipit to prod (Andrew's call, 2026-08-29). Cold-start context:
|
||||
`docs/archive/2026-08-29-full-auto-review-workstream-c-handoff.md` (workspace root).
|
||||
|
||||
## The verdict data (already stored on every job)
|
||||
|
||||
`processing_metadata.auto_approval` (written by `executor.maybe_auto_complete_review`) =
|
||||
`verdict.to_dict()` + extras. Relevant fields:
|
||||
- `backing.verdict` ∈ {clean, with_backing, review}; `backing.non_subjective` (bool)
|
||||
- `lyrics.verdict` ∈ {auto, review}; `lyrics.tier`
|
||||
- `custom_instrumental` (bool), `enforcement_blockers`, `mode`, `overall_auto`
|
||||
|
||||
`GET /api/jobs/{id}` returns the full `Job` (response_model=Job) incl. `processing_metadata`
|
||||
— already in the HTTP response, just not declared on the frontend TS `Job` type.
|
||||
|
||||
## Shared helper (both C1 and executor use it)
|
||||
|
||||
`backend/services/auto_approval/instrumental.py` (new):
|
||||
- `resolve_auto_instrumental(job, settings) -> Optional[str]` — the ONE place that maps a
|
||||
stored verdict → "clean" | "with_backing" | "custom" | None:
|
||||
- custom instrumental present → "custom"
|
||||
- backing.verdict == clean AND non_subjective → "clean"
|
||||
- backing.verdict == with_backing AND non_subjective AND backing_keep_enabled → "with_backing"
|
||||
- else None (not confidently resolvable → human must pick)
|
||||
Plus a `backing_preference` override (C3): "clean" forces clean, "review" suppresses.
|
||||
- `auto_approval_summary(job, settings) -> dict` — compact block for the correction-data
|
||||
response: `{backing: {verdict, confident, resolved_selection}, lyrics: {verdict, confident}}`.
|
||||
|
||||
Executor's `keep_backing`/selection logic (executor.py ~142-238) refactored to call this so
|
||||
there is a single source of truth.
|
||||
|
||||
## C2 — Server-side pre-apply (kills the on-load race)
|
||||
|
||||
Refactor `executor._build_auto_corrections` → extract `apply.py::build_applied_segments(
|
||||
corrections, ai_suggestions)` returning `{aborted}` | `{segments, applied_ids, rejected_ids}`
|
||||
(the stale/empty/duplicate sanity checks). Both executor (enforce) and the new pre-apply call it.
|
||||
|
||||
New `backend/services/auto_approval/pre_apply.py::ensure_and_pre_apply(job_id)`:
|
||||
1. ensure the proactive suggestion cache exists — if missing and proactive enabled, call
|
||||
`process_proactive_auto_correct(job_id)` (already bounded 180s); fail-open.
|
||||
2. load suggestions + corrections.json, `build_applied_segments`.
|
||||
3. write `corrections_updated.json` (new baseline) with
|
||||
`metadata.auto_approval = {pre_applied: true, applied_suggestion_ids, rejected_suggestion_ids,
|
||||
applied_at, suggestions: [...]}` (suggestions carried for the UI panel display).
|
||||
4. `update_file_url(job_id, 'lyrics', 'corrections_updated', ...)`.
|
||||
Best-effort: any failure leaves corrections_updated absent → frontend falls back to today's
|
||||
client-side auto-apply. Never blocks the review-ready transition beyond the bounded timeout.
|
||||
|
||||
`screens_worker` (after the executor call ~220, when outcome != auto_completed, BEFORE the
|
||||
AWAITING_REVIEW transition/notification): `await ensure_and_pre_apply(job_id)`. Lyrics-only, so
|
||||
independent of audio state (audio-lags case is fine). Executor always applies from RAW
|
||||
corrections.json, so no double-apply — it's idempotent w.r.t. corrections_updated.
|
||||
|
||||
Frontend: correction-data already prefers corrections_updated.json → the review UI loads the
|
||||
final state in ONE event. `useAutoCorrect` gains a `preApplied` arg; when set, autoRun/autoApply
|
||||
are OFF and the panel shows applied/rejected suggestions read-only + a "Re-run AI" escape.
|
||||
Normal manual word editing is unaffected (that's the per-suggestion escape). Backward compatible:
|
||||
no marker → today's behavior.
|
||||
|
||||
## C1 — Per-screen skip
|
||||
|
||||
Backend:
|
||||
- `complete_review` accepts `instrumental_selection == "auto"` → `resolve_auto_instrumental`;
|
||||
None → 400 (client must send an explicit pick). CLI/tenant clients get skip for free.
|
||||
- correction-data response gains `auto_approval` summary block.
|
||||
Frontend:
|
||||
- LyricsAnalyzer `handleSubmitToServer` (1044-1071): new branch — backing confidently
|
||||
resolvable (`data.auto_approval.backing.confident`) and not read-only → `completeReview(...,
|
||||
'auto', ...)` and DO NOT navigate to the instrumental screen. Escape hatch: a "review
|
||||
instrumental anyway" link in ReviewChangesModal that forces the old hash-nav path.
|
||||
- Mirror case (lyrics auto + backing needs review — Cher class): `JobRouterClient` redirects
|
||||
`#/{id}/review` → `#/{id}/instrumental` when the verdict says lyrics confident + backing not
|
||||
(needs `auto_approval` on the frontend Job type / getJob). Instrumental-only complete uses the
|
||||
pre-applied corrections (already the default via corrections_updated.json).
|
||||
|
||||
## C3 — Submission UI (review-mode + retain-backing)
|
||||
|
||||
Backend:
|
||||
- Add `review_mode: str = "auto"` to request models that lack it (URLSubmissionRequest,
|
||||
CreateJobFromUrlRequest, CreateJobWithUploadUrlsRequest, AudioSearchRequest,
|
||||
CreateFromSearchRequest, BulkSettings) + pass `review_mode=body.review_mode` into each
|
||||
`JobCreate(...)`. `JobManager.create_job` already forwards it to `Job`.
|
||||
- New `backing_preference: str = "auto"` (auto=retain-where-possible | clean | review) on
|
||||
Job/JobCreate; copy in job_manager; consume in `resolve_auto_instrumental` / scorer gate.
|
||||
Validate values in the admin PATCH allow-list too.
|
||||
Frontend:
|
||||
- GuidedJobFlow: review-mode radio (VisibilityStep) + retain-backing select (CustomizeStep);
|
||||
plumb into createJobFromUrl / createJobWithUploadUrls / createJobFromSearch bodies; reset in
|
||||
resetFlow. i18n keys under `jobFlow` → `translate.py --target all` (33 locales).
|
||||
|
||||
## Tests
|
||||
- Backend unit: `resolve_auto_instrumental` matrix; complete-endpoint "auto" resolution + 400;
|
||||
pre_apply build/persist + fail-open; screens_worker pre-apply call; request-model review_mode
|
||||
plumbing.
|
||||
- Frontend Jest: useAutoCorrect preApplied (no auto-run), LyricsAnalyzer skip branch, router
|
||||
mirror redirect.
|
||||
- i18n completeness (CI enforces).
|
||||
- `make test` + the two private corpus validators (validate_scorer / validate_backing_decider)
|
||||
stay green.
|
||||
|
||||
## Definition of done
|
||||
Auto by default; when a human is needed they see exactly ONE prepared screen with everything
|
||||
applied; submission exposes autonomy + backing prefs in 33 locales. Then update memory +
|
||||
CHANGELOG, retire the handoff docs, /backlog-finish the INBOX items.
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState, useCallback } from "react"
|
||||
import { useEffect, useState, useCallback, useRef } from "react"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { api, Job, createLyricsReviewApiClient, lyricsReviewApi } from "@/lib/api"
|
||||
import { Spinner } from "@/components/ui/spinner"
|
||||
@@ -55,6 +55,13 @@ export function JobRouterClient() {
|
||||
typeof window !== 'undefined' ? window.location.hash : ''
|
||||
)
|
||||
|
||||
// Replay mode: read-only re-open of a COMPLETED job's review UI for the
|
||||
// fully-automated-review recording program. Enabled via ?replay=1 (admin only).
|
||||
const [isReplay] = useState(() =>
|
||||
typeof window !== 'undefined' &&
|
||||
new URLSearchParams(window.location.search).get('replay') === '1'
|
||||
)
|
||||
|
||||
// Listen for hash changes
|
||||
useEffect(() => {
|
||||
const handleHashChange = () => {
|
||||
@@ -125,9 +132,11 @@ export function JobRouterClient() {
|
||||
return
|
||||
}
|
||||
|
||||
// Check job is in correct state
|
||||
// Check job is in correct state.
|
||||
// Replay mode (admin only) bypasses the state gate so a COMPLETED job's
|
||||
// review UI can be re-opened read-only.
|
||||
const expectedStates = getExpectedStates(routeType)
|
||||
if (!expectedStates.includes(job.status)) {
|
||||
if (!(isReplay && isAdmin) && !expectedStates.includes(job.status)) {
|
||||
setAccessState({
|
||||
status: "wrong_state",
|
||||
currentState: job.status,
|
||||
@@ -152,7 +161,7 @@ export function JobRouterClient() {
|
||||
}
|
||||
|
||||
checkAccess()
|
||||
}, [inLocalMode, jobId, routeType, user, authLoading, hasHydrated])
|
||||
}, [inLocalMode, jobId, routeType, user, authLoading, hasHydrated, isReplay])
|
||||
|
||||
// Loading state
|
||||
if (accessState.status === "loading") {
|
||||
@@ -281,23 +290,36 @@ export function JobRouterClient() {
|
||||
if (currentRouteType === "instrumental") {
|
||||
return (
|
||||
<CrashReportBoundary source="instrumental-review" backHref="/app">
|
||||
<InstrumentalReviewWrapper job={job} isLocalMode={inLocalMode} />
|
||||
<InstrumentalReviewWrapper job={job} isLocalMode={inLocalMode} isReplay={isReplay} />
|
||||
</CrashReportBoundary>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<CrashReportBoundary source="lyrics-review" backHref="/app">
|
||||
<LyricsReviewWrapper job={job} isLocalMode={inLocalMode} />
|
||||
<LyricsReviewWrapper job={job} isLocalMode={inLocalMode} isReplay={isReplay} />
|
||||
</CrashReportBoundary>
|
||||
)
|
||||
}
|
||||
|
||||
// Lyrics Review Component Wrapper
|
||||
function LyricsReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMode?: boolean }) {
|
||||
function LyricsReviewWrapper({ job, isLocalMode = false, isReplay = false }: { job: Job; isLocalMode?: boolean; isReplay?: boolean }) {
|
||||
const [correctionData, setCorrectionData] = useState<CorrectionData | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
// Replay: toggle between the final lyrics and the "post-AI, pre-human" state so
|
||||
// manual edits are obvious. Reset whenever the job changes.
|
||||
const [showPostAi, setShowPostAi] = useState(false)
|
||||
useEffect(() => { setShowPostAi(false) }, [job.job_id])
|
||||
|
||||
// DEV-ONLY: `&edit=1` makes a replay session editable so the review UI (incl. Tap To Sync)
|
||||
// can be exercised against REAL job data + audio locally. Ignored in production builds — replay
|
||||
// stays strictly read-only there.
|
||||
const replayEditable =
|
||||
isReplay &&
|
||||
process.env.NODE_ENV !== 'production' &&
|
||||
typeof window !== 'undefined' &&
|
||||
new URLSearchParams(window.location.search).get('edit') === '1'
|
||||
|
||||
// Create the API client for this job
|
||||
const apiClient = createLyricsReviewApiClient(job.job_id)
|
||||
@@ -308,7 +330,7 @@ function LyricsReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMo
|
||||
try {
|
||||
setIsLoading(true)
|
||||
setError(null)
|
||||
const data = await lyricsReviewApi.getCorrectionData(job.job_id)
|
||||
const data = await lyricsReviewApi.getCorrectionData(job.job_id, { replay: isReplay })
|
||||
setCorrectionData(data)
|
||||
} catch (err) {
|
||||
console.error("Failed to load correction data:", err)
|
||||
@@ -318,7 +340,26 @@ function LyricsReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMo
|
||||
}
|
||||
}
|
||||
loadData()
|
||||
}, [job.job_id])
|
||||
}, [job.job_id, isReplay])
|
||||
|
||||
// Per-screen skip — mirror case (C1): when the lyrics are confidently
|
||||
// auto-resolved but only the backing decision needs a human, skip the lyrics
|
||||
// screen entirely and jump straight to the instrumental screen. The server
|
||||
// pre-applied the corrections, so completing the instrumental alone finalizes
|
||||
// the whole job. Real review flow only (never replay / local).
|
||||
const willSkipToInstrumental = Boolean(
|
||||
!isReplay &&
|
||||
!isLocalMode &&
|
||||
correctionData?.auto_approval?.lyrics?.confident &&
|
||||
!correctionData?.auto_approval?.backing?.confident &&
|
||||
!correctionData?.auto_approval?.custom_instrumental
|
||||
)
|
||||
const mirrorRedirectedRef = useRef(false)
|
||||
useEffect(() => {
|
||||
if (!willSkipToInstrumental || mirrorRedirectedRef.current) return
|
||||
mirrorRedirectedRef.current = true
|
||||
window.location.hash = `/${job.job_id}/instrumental`
|
||||
}, [willSkipToInstrumental, job.job_id])
|
||||
|
||||
// File load handler (opens file picker for local file)
|
||||
const handleFileLoad = useCallback(() => {
|
||||
@@ -366,6 +407,18 @@ function LyricsReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMo
|
||||
)
|
||||
}
|
||||
|
||||
// Mirror-case redirect in flight — don't flash the lyrics screen.
|
||||
if (willSkipToInstrumental) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<div className="text-center">
|
||||
<Spinner className="w-8 h-8 mx-auto mb-4" />
|
||||
<p className="text-muted-foreground">Lyrics auto-verified — loading instrumental review...</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background">
|
||||
{/* App Header - matches old frontend's AppHeader */}
|
||||
@@ -386,7 +439,9 @@ function LyricsReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMo
|
||||
alt="Nomad Karaoke"
|
||||
style={{ height: 40 }}
|
||||
/>
|
||||
<h1 className="text-lg font-bold">Lyrics Transcription Review</h1>
|
||||
<h1 className="text-lg font-bold">
|
||||
{isReplay ? (replayEditable ? "Lyrics Review — Replay (editable · dev)" : "Lyrics Review — Replay (read-only)") : "Lyrics Transcription Review"}
|
||||
</h1>
|
||||
{(job.artist || job.title) && (
|
||||
<span className="text-xs md:text-sm text-muted-foreground truncate">
|
||||
{[job.artist, job.title].filter(Boolean).join(" - ")}
|
||||
@@ -397,13 +452,44 @@ function LyricsReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMo
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{isReplay && <ReplayNavBar jobId={job.job_id} screen="review" />}
|
||||
{isReplay && (
|
||||
<ReplayActionLog
|
||||
editLog={correctionData.replay?.edit_log ?? null}
|
||||
instrumentalSelection={correctionData.replay?.instrumental_selection ?? null}
|
||||
jobStatus={correctionData.replay?.job_status ?? job.status}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isReplay && correctionData.replay?.has_manual_edits && correctionData.replay?.post_ai_segments && (
|
||||
<div className="mx-4 mt-2 flex items-center gap-2 rounded-lg border border-amber-400/40 bg-amber-50/40 dark:bg-amber-900/10 px-3 py-2 text-sm">
|
||||
<span className="text-muted-foreground">Viewing lyrics:</span>
|
||||
<button
|
||||
className={`px-3 py-1 rounded font-medium ${!showPostAi ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground hover:bg-muted/70"}`}
|
||||
onClick={() => setShowPostAi(false)}
|
||||
>Final (my result)</button>
|
||||
<button
|
||||
className={`px-3 py-1 rounded font-medium ${showPostAi ? "bg-amber-500 text-white" : "bg-muted text-muted-foreground hover:bg-muted/70"}`}
|
||||
onClick={() => setShowPostAi(true)}
|
||||
>Post-AI (pre-human)</button>
|
||||
<span className="text-xs text-muted-foreground ml-1">
|
||||
{showPostAi ? "← what the AI produced, before your manual edits" : "← your final version"}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<main className="px-4 py-2">
|
||||
<LyricsAnalyzer
|
||||
data={correctionData}
|
||||
key={showPostAi ? "postai" : "final"}
|
||||
data={
|
||||
showPostAi && correctionData.replay?.post_ai_segments
|
||||
? { ...correctionData, corrected_segments: correctionData.replay.post_ai_segments }
|
||||
: correctionData
|
||||
}
|
||||
onFileLoad={handleFileLoad}
|
||||
onShowMetadata={handleShowMetadata}
|
||||
apiClient={apiClient}
|
||||
isReadOnly={false}
|
||||
isReadOnly={isReplay && !replayEditable}
|
||||
audioHash={correctionData.metadata?.audio_hash || job.audio_hash || job.job_id}
|
||||
isLocalMode={isLocalMode}
|
||||
jobId={job.job_id}
|
||||
@@ -414,12 +500,140 @@ function LyricsReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMo
|
||||
)
|
||||
}
|
||||
|
||||
// Instrumental Review Component Wrapper
|
||||
// The InstrumentalSelector component handles its own data fetching and submission
|
||||
// It uses the appropriate API based on isLocalMode
|
||||
function InstrumentalReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMode?: boolean }) {
|
||||
/**
|
||||
* ReplayNavBar — replay-only navigation: toggle Lyrics⇄Instrumental for the current
|
||||
* job, and step Prev/Next through the job list (passed as a comma-separated `queue`
|
||||
* URL param). All navigation is hash-only (`#/<id>/<screen>`), so the query params
|
||||
* (baseApiUrl, replay, queue) are preserved and the app re-renders via hashchange.
|
||||
*/
|
||||
function ReplayNavBar({ jobId, screen }: { jobId: string; screen: "review" | "instrumental" }) {
|
||||
const queue = (typeof window !== "undefined"
|
||||
? new URLSearchParams(window.location.search).get("queue")
|
||||
: null)?.split(",").map((s) => s.trim()).filter(Boolean) ?? []
|
||||
const idx = queue.indexOf(jobId)
|
||||
const prev = idx > 0 ? queue[idx - 1] : null
|
||||
const next = idx >= 0 && idx < queue.length - 1 ? queue[idx + 1] : null
|
||||
const go = (id: string, s: "review" | "instrumental") => { window.location.hash = `#/${id}/${s}` }
|
||||
|
||||
const tabCls = (active: boolean) =>
|
||||
`px-3 py-1 rounded text-sm font-medium ${active ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground hover:bg-muted/70"}`
|
||||
const navCls = (enabled: boolean) =>
|
||||
`px-3 py-1 rounded text-sm font-medium border ${enabled ? "hover:bg-muted" : "opacity-40 cursor-not-allowed"}`
|
||||
|
||||
return (
|
||||
<InstrumentalSelector job={job} isLocalMode={isLocalMode} />
|
||||
<div className="mx-4 mt-2 flex items-center gap-2 rounded-lg border bg-card px-3 py-2">
|
||||
<span className="text-xs text-muted-foreground mr-1">Replay:</span>
|
||||
<button className={tabCls(screen === "review")} onClick={() => go(jobId, "review")}>Lyrics</button>
|
||||
<button className={tabCls(screen === "instrumental")} onClick={() => go(jobId, "instrumental")}>Instrumental</button>
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<button className={navCls(!!prev)} disabled={!prev} onClick={() => prev && go(prev, "review")}>← Prev</button>
|
||||
{idx >= 0 && queue.length > 0 && (
|
||||
<span className="text-xs text-muted-foreground tabular-nums">{idx + 1} / {queue.length}</span>
|
||||
)}
|
||||
<button className={navCls(!!next)} disabled={!next} onClick={() => next && go(next, "review")}>Next job →</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* ReplayActionLog — read-only summary of the reviewer's ordered edit_log for a
|
||||
* completed job, shown in replay mode so Andrew can narrate what he did and why.
|
||||
* Distinguishes AI-accepted / AI-rejected / manual / timing ops. Internal admin
|
||||
* tool (English-only, like /admin).
|
||||
*/
|
||||
function ReplayActionLog({
|
||||
editLog,
|
||||
instrumentalSelection,
|
||||
jobStatus,
|
||||
}: {
|
||||
editLog: import("@/lib/lyrics-review/types").EditLog | null
|
||||
instrumentalSelection: string | null
|
||||
jobStatus: string
|
||||
}) {
|
||||
const [collapsed, setCollapsed] = useState(false)
|
||||
const entries = editLog?.entries ?? []
|
||||
|
||||
const counts = entries.reduce(
|
||||
(acc, e) => {
|
||||
if (e.operation === "ai_suggestion_accept") acc.aiAccept++
|
||||
else if (e.operation === "ai_suggestion_reject") acc.aiReject++
|
||||
else if (e.operation === "timing_change") acc.timing++
|
||||
else if (e.operation === "ai_suggestion_run" || e.operation === "ai_suggestion_undo") acc.other++
|
||||
else acc.manual++
|
||||
return acc
|
||||
},
|
||||
{ aiAccept: 0, aiReject: 0, manual: 0, timing: 0, other: 0 }
|
||||
)
|
||||
|
||||
const badge = (op: string): { label: string; cls: string } => {
|
||||
if (op === "ai_suggestion_accept") return { label: "AI ✓", cls: "bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300" }
|
||||
if (op === "ai_suggestion_reject") return { label: "AI ✗", cls: "bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-300" }
|
||||
if (op === "timing_change") return { label: "timing", cls: "bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300" }
|
||||
if (op.startsWith("ai_suggestion")) return { label: op.replace("ai_suggestion_", "AI "), cls: "bg-muted text-muted-foreground" }
|
||||
return { label: "manual", cls: "bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300" }
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-4 my-2 rounded-lg border bg-card">
|
||||
<button
|
||||
onClick={() => setCollapsed((c) => !c)}
|
||||
className="w-full flex items-center justify-between px-4 py-2 text-sm font-medium"
|
||||
>
|
||||
<span>
|
||||
Replay — actions in this review:{" "}
|
||||
<span className="text-green-700 dark:text-green-400">{counts.aiAccept} AI accepted</span>,{" "}
|
||||
<span className="text-red-700 dark:text-red-400">{counts.aiReject} AI rejected</span>,{" "}
|
||||
<span className="text-amber-700 dark:text-amber-400">{counts.manual} manual</span>,{" "}
|
||||
<span className="text-blue-700 dark:text-blue-400">{counts.timing} timing</span>
|
||||
{" · instrumental: "}
|
||||
<code>{instrumentalSelection ?? "—"}</code>
|
||||
{" · status: "}
|
||||
<code>{jobStatus}</code>
|
||||
</span>
|
||||
<span className="text-muted-foreground">{collapsed ? "▸ show" : "▾ hide"}</span>
|
||||
</button>
|
||||
{!collapsed && (
|
||||
<div className="max-h-64 overflow-y-auto border-t px-2 py-2 text-xs">
|
||||
{entries.length === 0 && (
|
||||
<p className="px-2 py-1 text-muted-foreground">
|
||||
No edit log recorded for this job.
|
||||
</p>
|
||||
)}
|
||||
<ol className="space-y-0.5">
|
||||
{entries.map((e, i) => {
|
||||
const b = badge(e.operation)
|
||||
const cat = (e.details?.category as string) || (e.details?.gap_category as string) || ""
|
||||
return (
|
||||
<li key={e.id || i} className="flex items-start gap-2 px-2 py-1 rounded hover:bg-muted/50">
|
||||
<span className="text-muted-foreground tabular-nums w-6 text-right">{i + 1}</span>
|
||||
<span className={`shrink-0 rounded px-1.5 py-0.5 text-[10px] font-medium ${b.cls}`}>{b.label}</span>
|
||||
<span className="flex-1 break-words">
|
||||
{e.text_before && <span className="line-through text-muted-foreground">{e.text_before}</span>}
|
||||
{e.text_before && e.text_after && <span className="mx-1">→</span>}
|
||||
{e.text_after && <span className="font-medium">{e.text_after}</span>}
|
||||
{!e.text_before && !e.text_after && <span className="text-muted-foreground">{e.operation}</span>}
|
||||
{cat && <span className="ml-2 text-muted-foreground">[{cat}]</span>}
|
||||
</span>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ol>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Instrumental Review Component Wrapper
|
||||
// The InstrumentalSelector component handles its own data fetching and submission
|
||||
// It uses the appropriate API based on isLocalMode
|
||||
function InstrumentalReviewWrapper({ job, isLocalMode = false, isReplay = false }: { job: Job; isLocalMode?: boolean; isReplay?: boolean }) {
|
||||
return (
|
||||
<>
|
||||
{isReplay && <ReplayNavBar jobId={job.job_id} screen="instrumental" />}
|
||||
<InstrumentalSelector job={job} isLocalMode={isLocalMode} isReadOnly={isReplay} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -27,6 +27,8 @@ import { InstrumentalGuidancePanel } from "./InstrumentalGuidancePanel"
|
||||
interface InstrumentalSelectorProps {
|
||||
job: Job
|
||||
isLocalMode?: boolean
|
||||
/** Replay/read-only: load + play audio but hide submit and all mutating actions. */
|
||||
isReadOnly?: boolean
|
||||
}
|
||||
|
||||
type ZoomLevel = 1 | 2 | 4
|
||||
@@ -48,7 +50,7 @@ function formatTime(seconds: number): string {
|
||||
return `${mins}:${secs.toString().padStart(2, "0")}`
|
||||
}
|
||||
|
||||
export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalSelectorProps) {
|
||||
export function InstrumentalSelector({ job, isLocalMode = false, isReadOnly = false }: InstrumentalSelectorProps) {
|
||||
const router = useRouter()
|
||||
const t = useTranslations('instrumentalReview')
|
||||
const audioRef = useRef<HTMLAudioElement>(null)
|
||||
@@ -157,9 +159,16 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
setAnalysisData(analysis)
|
||||
setWaveformData(waveform)
|
||||
|
||||
// Set initial selection based on recommendation
|
||||
const recommended = analysis.analysis.recommended_selection
|
||||
setSelectedOption(recommended === "clean" ? "clean" : "with_backing")
|
||||
// Set initial selection. In replay/read-only, reflect the ACTUAL saved
|
||||
// choice; otherwise seed from the analyzer's recommendation.
|
||||
const savedSelection = (job as { state_data?: { instrumental_selection?: string } })
|
||||
.state_data?.instrumental_selection
|
||||
if (isReadOnly && (savedSelection === "clean" || savedSelection === "with_backing" || savedSelection === "custom")) {
|
||||
setSelectedOption(savedSelection as InstrumentalSelectionType)
|
||||
} else {
|
||||
const recommended = analysis.analysis.recommended_selection
|
||||
setSelectedOption(recommended === "clean" ? "clean" : "with_backing")
|
||||
}
|
||||
|
||||
// Set duration from waveform data
|
||||
const dur = waveform.duration_seconds ?? waveform.duration ?? 0
|
||||
@@ -177,7 +186,7 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
}
|
||||
|
||||
fetchData()
|
||||
}, [job.job_id, isLocalMode, waitingForAudio])
|
||||
}, [job.job_id, isLocalMode, waitingForAudio, isReadOnly, job])
|
||||
|
||||
// Keyboard shortcuts
|
||||
useEffect(() => {
|
||||
@@ -737,7 +746,8 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
|
||||
{/* Bottom section */}
|
||||
<div className="flex flex-col lg:flex-row gap-2 md:gap-3 flex-shrink-0">
|
||||
{/* Left column: Custom Mix + Alternate Instrumental */}
|
||||
{/* Left column: Custom Mix + Alternate Instrumental (editing only) */}
|
||||
{!isReadOnly && (
|
||||
<div className="flex flex-col gap-2 md:gap-3 lg:flex-1 lg:min-w-0">
|
||||
<MuteRegionEditor
|
||||
regions={muteRegions}
|
||||
@@ -773,6 +783,7 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Right column: Selection panel */}
|
||||
<div className="w-full lg:w-[340px] lg:flex-shrink-0 bg-card border border-border rounded-lg p-3 flex flex-col gap-2">
|
||||
@@ -787,16 +798,22 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
muteRegionsCount={muteRegions.length}
|
||||
backingVocalAnalysis={analysisData?.analysis}
|
||||
/>
|
||||
<Button
|
||||
id="submit-btn"
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitting}
|
||||
size="lg"
|
||||
className="mt-auto w-full min-h-[44px] text-base font-semibold"
|
||||
>
|
||||
<Check className="w-5 h-5 mr-2" />
|
||||
{isSubmitting ? t('submitting') : t('confirmContinue')}
|
||||
</Button>
|
||||
{isReadOnly ? (
|
||||
<div className="mt-auto w-full rounded-md border border-border bg-muted/40 px-3 py-2 text-center text-sm">
|
||||
Replay — chosen instrumental: <code className="font-semibold">{selectedOption}</code>
|
||||
</div>
|
||||
) : (
|
||||
<Button
|
||||
id="submit-btn"
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitting}
|
||||
size="lg"
|
||||
className="mt-auto w-full min-h-[44px] text-base font-semibold"
|
||||
>
|
||||
<Check className="w-5 h-5 mr-2" />
|
||||
{isSubmitting ? t('submitting') : t('confirmContinue')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -13,7 +13,7 @@ import { SongInfoStep } from "./steps/SongInfoStep"
|
||||
import { AudioSourceStep } from "./steps/AudioSourceStep"
|
||||
import { VisibilityStep } from "./steps/VisibilityStep"
|
||||
import { CustomizeStep } from "./steps/CustomizeStep"
|
||||
import type { ColorOverrides } from "./steps/CustomizeStep"
|
||||
import type { ColorOverrides, ReviewMode, BackingPreference } from "./steps/CustomizeStep"
|
||||
|
||||
interface GuidedJobFlowProps {
|
||||
onJobCreated: () => void
|
||||
@@ -109,6 +109,9 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
const [displayTitle, setDisplayTitle] = useState("")
|
||||
const [isPrivate, setIsPrivate] = useState(false)
|
||||
const [requiresAudioEdit, setRequiresAudioEdit] = useState(false)
|
||||
// Full-auto review (workstream C): up-front autonomy + backing-vocals preference.
|
||||
const [reviewMode, setReviewMode] = useState<ReviewMode>("auto")
|
||||
const [backingPreference, setBackingPreference] = useState<BackingPreference>("auto")
|
||||
|
||||
// Custom style state
|
||||
const [karaokeBackground, setKaraokeBackground] = useState<File | null>(null)
|
||||
@@ -171,13 +174,20 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
const response = await api.createJobFromUrl(pendingUrl, effectiveArtist, effectiveTitle, {
|
||||
is_private: isPrivate,
|
||||
requires_audio_edit: requiresAudioEdit || undefined,
|
||||
review_mode: reviewMode,
|
||||
backing_preference: backingPreference,
|
||||
})
|
||||
createdJobId = response.job_id
|
||||
} else if (audioSource === "upload" && pendingFile) {
|
||||
// Upload fallback path — upload and create job now with visibility from Step 3
|
||||
const response = await api.uploadJobSmart(
|
||||
pendingFile, effectiveArtist, effectiveTitle,
|
||||
{ is_private: isPrivate, requires_audio_edit: requiresAudioEdit || undefined },
|
||||
{
|
||||
is_private: isPrivate,
|
||||
requires_audio_edit: requiresAudioEdit || undefined,
|
||||
review_mode: reviewMode,
|
||||
backing_preference: backingPreference,
|
||||
},
|
||||
)
|
||||
createdJobId = response.job_id
|
||||
} else if (searchSessionId && selectedResultIndex !== null) {
|
||||
@@ -191,6 +201,8 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
display_title: displayTitle.trim() || undefined,
|
||||
is_private: isPrivate,
|
||||
requires_audio_edit: requiresAudioEdit || undefined,
|
||||
review_mode: reviewMode,
|
||||
backing_preference: backingPreference,
|
||||
})
|
||||
createdJobId = response.job_id
|
||||
} else {
|
||||
@@ -247,6 +259,8 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
setDisplayTitle("")
|
||||
setIsPrivate(false)
|
||||
setRequiresAudioEdit(false)
|
||||
setReviewMode("auto")
|
||||
setBackingPreference("auto")
|
||||
setKaraokeBackground(null)
|
||||
setIntroBackground(null)
|
||||
setColorOverrides({})
|
||||
@@ -546,6 +560,10 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
onIntroBackgroundChange={setIntroBackground}
|
||||
colorOverrides={colorOverrides}
|
||||
onColorOverridesChange={setColorOverrides}
|
||||
reviewMode={reviewMode}
|
||||
onReviewModeChange={setReviewMode}
|
||||
backingPreference={backingPreference}
|
||||
onBackingPreferenceChange={setBackingPreference}
|
||||
onConfirm={handleConfirm}
|
||||
onBack={() => setStep(3)}
|
||||
isSubmitting={isSubmitting}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useTranslations } from 'next-intl'
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { ArrowLeft, Loader2, Palette, Image as ImageIcon, Paintbrush } from "lucide-react"
|
||||
import { ArrowLeft, Loader2, Palette, Image as ImageIcon, Paintbrush, Sparkles } from "lucide-react"
|
||||
import { TitleCardPreview } from "../TitleCardPreview"
|
||||
import { KaraokeBackgroundPreview } from "../KaraokeBackgroundPreview"
|
||||
import { ImageUploadField } from "../ImageUploadField"
|
||||
@@ -17,6 +17,9 @@ export interface ColorOverrides {
|
||||
unsung_lyrics_color?: string
|
||||
}
|
||||
|
||||
export type ReviewMode = "auto" | "always_review"
|
||||
export type BackingPreference = "auto" | "clean" | "review"
|
||||
|
||||
interface CustomizeStepProps {
|
||||
artist: string
|
||||
title: string
|
||||
@@ -31,6 +34,10 @@ interface CustomizeStepProps {
|
||||
onIntroBackgroundChange: (file: File | null) => void
|
||||
colorOverrides: ColorOverrides
|
||||
onColorOverridesChange: (overrides: ColorOverrides) => void
|
||||
reviewMode: ReviewMode
|
||||
onReviewModeChange: (value: ReviewMode) => void
|
||||
backingPreference: BackingPreference
|
||||
onBackingPreferenceChange: (value: BackingPreference) => void
|
||||
onConfirm: () => void
|
||||
onBack: () => void
|
||||
isSubmitting: boolean
|
||||
@@ -194,6 +201,86 @@ function BgModeToggle({
|
||||
)
|
||||
}
|
||||
|
||||
/** Full-auto review (workstream C): up-front autonomy + backing-vocals choice.
|
||||
* Rendered on the final step so it applies to every audio source. */
|
||||
function ProcessingOptions({
|
||||
reviewMode,
|
||||
onReviewModeChange,
|
||||
backingPreference,
|
||||
onBackingPreferenceChange,
|
||||
disabled,
|
||||
t,
|
||||
}: {
|
||||
reviewMode: ReviewMode
|
||||
onReviewModeChange: (v: ReviewMode) => void
|
||||
backingPreference: BackingPreference
|
||||
onBackingPreferenceChange: (v: BackingPreference) => void
|
||||
disabled?: boolean
|
||||
t: ReturnType<typeof useTranslations>
|
||||
}) {
|
||||
const pill = (active: boolean) =>
|
||||
`flex-1 px-3 py-2 rounded-md border text-xs font-medium transition-colors ${
|
||||
active
|
||||
? 'border-[var(--brand-pink)] text-[var(--text)]'
|
||||
: 'border-[var(--card-border)] text-[var(--text-muted)] hover:border-[var(--text-muted)]'
|
||||
}`
|
||||
const pillStyle = (active: boolean) => ({
|
||||
backgroundColor: active ? 'rgba(255,122,204,0.05)' : 'var(--secondary)',
|
||||
})
|
||||
return (
|
||||
<div
|
||||
className="space-y-4 rounded-lg border p-4"
|
||||
style={{ borderColor: 'var(--card-border)', backgroundColor: 'rgba(255,255,255,0.02)' }}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Sparkles className="w-4 h-4" style={{ color: 'var(--brand-pink)' }} />
|
||||
<h3 className="text-sm font-semibold" style={{ color: 'var(--text)' }}>
|
||||
{t('processingOptions')}
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
{t('reviewModeLabel')}
|
||||
</Label>
|
||||
<div className="flex gap-2">
|
||||
<button type="button" disabled={disabled} className={pill(reviewMode === 'auto')}
|
||||
style={pillStyle(reviewMode === 'auto')} onClick={() => onReviewModeChange('auto')}>
|
||||
{t('reviewModeAuto')}
|
||||
</button>
|
||||
<button type="button" disabled={disabled} className={pill(reviewMode === 'always_review')}
|
||||
style={pillStyle(reviewMode === 'always_review')} onClick={() => onReviewModeChange('always_review')}>
|
||||
{t('reviewModeAlways')}
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
|
||||
{reviewMode === 'auto' ? t('reviewModeAutoHint') : t('reviewModeAlwaysHint')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
{t('backingPrefLabel')}
|
||||
</Label>
|
||||
<div className="flex gap-2">
|
||||
<button type="button" disabled={disabled} className={pill(backingPreference === 'auto')}
|
||||
style={pillStyle(backingPreference === 'auto')} onClick={() => onBackingPreferenceChange('auto')}>
|
||||
{t('backingPrefAuto')}
|
||||
</button>
|
||||
<button type="button" disabled={disabled} className={pill(backingPreference === 'clean')}
|
||||
style={pillStyle(backingPreference === 'clean')} onClick={() => onBackingPreferenceChange('clean')}>
|
||||
{t('backingPrefClean')}
|
||||
</button>
|
||||
<button type="button" disabled={disabled} className={pill(backingPreference === 'review')}
|
||||
style={pillStyle(backingPreference === 'review')} onClick={() => onBackingPreferenceChange('review')}>
|
||||
{t('backingPrefReview')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function CustomizeStep({
|
||||
artist,
|
||||
title,
|
||||
@@ -208,6 +295,10 @@ export function CustomizeStep({
|
||||
onIntroBackgroundChange,
|
||||
colorOverrides,
|
||||
onColorOverridesChange,
|
||||
reviewMode,
|
||||
onReviewModeChange,
|
||||
backingPreference,
|
||||
onBackingPreferenceChange,
|
||||
onConfirm,
|
||||
onBack,
|
||||
isSubmitting,
|
||||
@@ -361,6 +452,15 @@ export function CustomizeStep({
|
||||
{t('defaultsToSearchValues')}
|
||||
</p>
|
||||
|
||||
<ProcessingOptions
|
||||
reviewMode={reviewMode}
|
||||
onReviewModeChange={onReviewModeChange}
|
||||
backingPreference={backingPreference}
|
||||
onBackingPreferenceChange={onBackingPreferenceChange}
|
||||
disabled={disabled || isSubmitting}
|
||||
t={t}
|
||||
/>
|
||||
|
||||
<Button
|
||||
onClick={onConfirm}
|
||||
disabled={disabled || isSubmitting}
|
||||
@@ -634,6 +734,15 @@ export function CustomizeStep({
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<ProcessingOptions
|
||||
reviewMode={reviewMode}
|
||||
onReviewModeChange={onReviewModeChange}
|
||||
backingPreference={backingPreference}
|
||||
onBackingPreferenceChange={onBackingPreferenceChange}
|
||||
disabled={disabled || isSubmitting}
|
||||
t={t}
|
||||
/>
|
||||
|
||||
{/* Create button */}
|
||||
<Button
|
||||
onClick={onConfirm}
|
||||
|
||||
@@ -72,6 +72,7 @@ export default function AutoCorrectPanel({
|
||||
revertAll,
|
||||
rejectAll,
|
||||
isPendingAndStale,
|
||||
isPreApplied,
|
||||
} = controller
|
||||
|
||||
// Details are opened on demand from the toolbar button.
|
||||
@@ -109,7 +110,11 @@ export default function AutoCorrectPanel({
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{!isReadOnly && acceptedCount > 0 && (
|
||||
{/* Pre-applied server-side (C2): the corrections were baked into the
|
||||
loaded data before this screen opened, so client-side revert/undo
|
||||
(which needs in-session undo info) is not available — editing a word
|
||||
directly is the escape. Only offered for client-applied suggestions. */}
|
||||
{!isReadOnly && !isPreApplied && acceptedCount > 0 && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
@@ -257,7 +262,7 @@ export default function AutoCorrectPanel({
|
||||
<Badge variant="outline" className="text-[10px] text-green-600">
|
||||
{t('accepted')}
|
||||
</Badge>
|
||||
{!isReadOnly && (
|
||||
{!isReadOnly && !isPreApplied && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
|
||||
@@ -60,6 +60,8 @@ const TapButton = memo(function TapButton({
|
||||
|
||||
interface EditTimelineSectionProps {
|
||||
words: Word[]
|
||||
/** Neighbouring segments' words, drawn greyed/read-only in the timeline padding for context. */
|
||||
contextWords?: Word[]
|
||||
startTime: number
|
||||
endTime: number
|
||||
currentTime?: number
|
||||
@@ -75,6 +77,7 @@ interface EditTimelineSectionProps {
|
||||
|
||||
export default function EditTimelineSection({
|
||||
words,
|
||||
contextWords,
|
||||
startTime,
|
||||
endTime,
|
||||
currentTime,
|
||||
@@ -108,6 +111,7 @@ export default function EditTimelineSection({
|
||||
<div>
|
||||
<TimelineEditor
|
||||
words={words}
|
||||
contextWords={contextWords}
|
||||
startTime={startTime}
|
||||
endTime={endTime}
|
||||
onWordUpdate={onWordUpdate}
|
||||
|
||||
@@ -61,8 +61,9 @@ import GapNavigator from './GapNavigator'
|
||||
import AutoCorrectModal from './AutoCorrectModal'
|
||||
import AutoCorrectPanel from './AutoCorrectPanel'
|
||||
import { useAutoCorrect } from '@/hooks/useAutoCorrect'
|
||||
import type { AiSuggestion } from '@/lib/api/autoCorrect'
|
||||
import { getWordsFromIds } from '@/lib/lyrics-review/utils/wordUtils'
|
||||
import { applyOffsetToCorrectionData, applyOffsetToSegment } from '@/lib/lyrics-review/utils/timingUtils'
|
||||
import { applyOffsetToCorrectionData, applyOffsetToSegment, applyOffsetToWord } from '@/lib/lyrics-review/utils/timingUtils'
|
||||
import { VocalsAudioDataLoader } from './VocalsAudioDataLoader'
|
||||
|
||||
// Add type for window augmentation
|
||||
@@ -89,6 +90,10 @@ interface ApiClient {
|
||||
message?: string
|
||||
preview_hash?: string
|
||||
}>
|
||||
getPreviewVideoStatus: (hash: string) => Promise<{
|
||||
status: string
|
||||
message?: string
|
||||
}>
|
||||
getPreviewVideoUrl: (hash: string) => string
|
||||
completeReview: () => Promise<{ status: string; job_status: string; message: string }>
|
||||
// Review session methods (optional - available in cloud mode)
|
||||
@@ -156,6 +161,11 @@ export default function LyricsAnalyzer({
|
||||
const [timingOffsetMs, setTimingOffsetMs] = useState(0)
|
||||
const [reviewMode, setReviewMode] = useState(false)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
// Per-screen skip (C1): when the backing decision is confidently auto-resolved,
|
||||
// completing the lyrics review finishes the job and the instrumental screen is
|
||||
// never shown. The reviewer can opt back in via a "review instrumental anyway"
|
||||
// toggle in the finish modal (the verdict is confident, not infallible).
|
||||
const [reviewInstrumentalAnyway, setReviewInstrumentalAnyway] = useState(false)
|
||||
|
||||
const [vocalsAudioUrl, setVocalsAudioUrl] = useState<string | null>(null)
|
||||
|
||||
@@ -237,6 +247,21 @@ export default function LyricsAnalyzer({
|
||||
setHistoryIndex(0)
|
||||
}, [])
|
||||
|
||||
// Server-side pre-apply (C2): when the backend applied the AI corrections
|
||||
// before the review-ready notification, `initialData` already carries them and
|
||||
// marks `metadata.auto_approval.pre_applied`. In that case the UI must NOT
|
||||
// auto-run/auto-apply again (no in-browser race) — it just displays what was
|
||||
// applied. Keyed on the marker only (not live edits) so it doesn't churn.
|
||||
const preApplied = useMemo(() => {
|
||||
const m = initialData.metadata?.auto_approval
|
||||
if (isReadOnly || isLocalMode || !m?.pre_applied || !Array.isArray(m.suggestions)) return null
|
||||
return {
|
||||
suggestions: m.suggestions as unknown as AiSuggestion[],
|
||||
appliedIds: m.applied_suggestion_ids ?? [],
|
||||
rejectedIds: m.rejected_suggestion_ids ?? [],
|
||||
}
|
||||
}, [initialData.metadata?.auto_approval, isReadOnly, isLocalMode])
|
||||
|
||||
// AI auto-correct suggestions (opt-in; nothing runs unless triggered)
|
||||
const autoCorrect = useAutoCorrect({
|
||||
jobId,
|
||||
@@ -249,11 +274,24 @@ export default function LyricsAnalyzer({
|
||||
// corrected lyrics (= clicking "Accept All"). The backend pre-generates +
|
||||
// caches suggestions 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),
|
||||
autoApplyOnLoad: !isReadOnly && !isLocalMode && Boolean(jobId),
|
||||
// jobId exists (the request needs one). Also skipped when the server already
|
||||
// pre-applied (C2) — the corrections are already in the loaded data.
|
||||
autoRunOnLoad: !isReadOnly && !isLocalMode && Boolean(jobId) && !preApplied,
|
||||
autoApplyOnLoad: !isReadOnly && !isLocalMode && Boolean(jobId) && !preApplied,
|
||||
preApplied,
|
||||
})
|
||||
|
||||
// Per-screen skip (C1): when the backing decision is confidently auto-resolved
|
||||
// by the server, completing the lyrics review finishes the whole job (with the
|
||||
// server-resolved instrumental selection) and the instrumental screen is never
|
||||
// shown. Custom / uploaded-instrumental jobs keep the existing skip path.
|
||||
const autoInstrumentalConfident =
|
||||
!isReadOnly &&
|
||||
!isLocalMode &&
|
||||
Boolean(jobId) &&
|
||||
!hasExistingInstrumental &&
|
||||
Boolean(data.auto_approval?.backing?.confident)
|
||||
|
||||
// Close the run modal once suggestions arrive (panel takes over)
|
||||
useEffect(() => {
|
||||
if (autoCorrect.status === 'reviewing') {
|
||||
@@ -1051,6 +1089,23 @@ export default function LyricsAnalyzer({
|
||||
console.error('Failed to complete review with uploaded instrumental:', err)
|
||||
toast.error('Failed to start video generation. Please try again.')
|
||||
}
|
||||
} else if (autoInstrumentalConfident && !reviewInstrumentalAnyway && jobId) {
|
||||
// Per-screen skip (C1): the backing decision was confidently auto-resolved
|
||||
// -> complete the review now with "auto" (the backend resolves it from the
|
||||
// stored verdict) and skip the instrumental screen entirely.
|
||||
toast.success('Lyrics saved! Instrumental auto-selected, generating video...')
|
||||
try {
|
||||
const correctionData = await lyricsReviewApi.getCorrectionData(jobId)
|
||||
await lyricsReviewApi.completeReview(jobId, correctionData, 'auto', isDuet)
|
||||
setShowSuccess(true)
|
||||
setCountdown(3)
|
||||
} catch (err) {
|
||||
// Fall back to the manual instrumental screen if auto-resolution fails
|
||||
// (e.g. the verdict wasn't resolvable server-side) — never strand the user.
|
||||
console.error('Auto instrumental selection failed, falling back to review:', err)
|
||||
toast('Please choose your instrumental to finish.')
|
||||
window.location.hash = `/${jobId}/instrumental`
|
||||
}
|
||||
} else if (isLocalMode) {
|
||||
// Local mode: Show transition message, navigation handled by browser/server
|
||||
toast.success('Lyrics saved! Loading instrumental review...')
|
||||
@@ -1070,7 +1125,7 @@ export default function LyricsAnalyzer({
|
||||
toast.error('Failed to submit corrections. Please try again.')
|
||||
setIsSubmitting(false) // Reset on error so user can retry
|
||||
}
|
||||
}, [apiClient, data, timingOffsetMs, editLog, isLocalMode, jobId, hasExistingInstrumental])
|
||||
}, [apiClient, data, timingOffsetMs, editLog, isLocalMode, jobId, hasExistingInstrumental, isDuet, autoInstrumentalConfident, reviewInstrumentalAnyway])
|
||||
|
||||
// Play segment handler
|
||||
const handlePlaySegment = useCallback(
|
||||
@@ -1330,6 +1385,27 @@ export default function LyricsAnalyzer({
|
||||
return timingOffsetMs !== 0 ? applyOffsetToCorrectionData(data, timingOffsetMs) : data
|
||||
}, [data, timingOffsetMs])
|
||||
|
||||
// Words from OTHER segments that sit near the segment being edited, so the Edit Segment
|
||||
// timeline can show them as greyed read-only context in its ±padding. Kept to a small window
|
||||
// around the segment (the timeline filters again to its exact view); offset-applied to match.
|
||||
const editContextWords = useMemo(() => {
|
||||
if (!editModalSegment) return []
|
||||
const seg = editModalSegment.segment
|
||||
const segStart = seg.start_time ?? 0
|
||||
const segEnd = seg.end_time ?? segStart
|
||||
const lo = segStart - 2
|
||||
const hi = segEnd + 2
|
||||
const nearby: Word[] = []
|
||||
data.corrected_segments.forEach((s, i) => {
|
||||
if (i === editModalSegment.index) return
|
||||
s.words.forEach((w) => {
|
||||
if (w.start_time === null || w.end_time === null) return
|
||||
if (w.end_time >= lo && w.start_time <= hi) nearby.push(w)
|
||||
})
|
||||
})
|
||||
return timingOffsetMs !== 0 ? nearby.map((w) => applyOffsetToWord(w, timingOffsetMs)) : nearby
|
||||
}, [editModalSegment, data.corrected_segments, timingOffsetMs])
|
||||
|
||||
// Timing offset handlers
|
||||
const handleOpenTimingOffsetModal = useCallback(() => {
|
||||
setIsTimingOffsetModalOpen(true)
|
||||
@@ -1570,6 +1646,7 @@ export default function LyricsAnalyzer({
|
||||
onMergeSegment={handleMergeSegment}
|
||||
onPlaySegment={handlePlaySegment}
|
||||
currentTime={currentAudioTime}
|
||||
contextWords={editContextWords}
|
||||
originalTranscribedSegment={
|
||||
editModalSegment?.segment &&
|
||||
editModalSegment?.index !== null &&
|
||||
@@ -1596,7 +1673,11 @@ export default function LyricsAnalyzer({
|
||||
apiClient={apiClient}
|
||||
timingOffsetMs={timingOffsetMs}
|
||||
isDuet={isDuet}
|
||||
completesReview={hasExistingInstrumental}
|
||||
completesReview={hasExistingInstrumental || (autoInstrumentalConfident && !reviewInstrumentalAnyway)}
|
||||
autoInstrumentalConfident={autoInstrumentalConfident}
|
||||
autoInstrumentalSelection={data.auto_approval?.backing?.resolved_selection ?? null}
|
||||
reviewInstrumentalAnyway={reviewInstrumentalAnyway}
|
||||
onToggleReviewInstrumental={setReviewInstrumentalAnyway}
|
||||
/>
|
||||
|
||||
<AddLyricsModal
|
||||
|
||||
@@ -8,12 +8,22 @@ import { Loader2 } from 'lucide-react'
|
||||
import { CorrectionData } from '@/lib/lyrics-review/types'
|
||||
import { applyOffsetToCorrectionData } from '@/lib/lyrics-review/utils/timingUtils'
|
||||
|
||||
const POLL_INTERVAL_MS = 3000
|
||||
// Cold-starting a fallback encoder VM can take 2-3 minutes; give up after 5.
|
||||
const ENCODE_TIMEOUT_MS = 5 * 60 * 1000
|
||||
// After this long, explain the wait (an encoder VM is probably cold-starting).
|
||||
const SLOW_ENCODE_THRESHOLD_MS = 30 * 1000
|
||||
|
||||
interface ApiClient {
|
||||
generatePreviewVideo: (data: CorrectionData, isDuet?: boolean) => Promise<{
|
||||
status: string
|
||||
message?: string
|
||||
preview_hash?: string
|
||||
}>
|
||||
getPreviewVideoStatus: (hash: string) => Promise<{
|
||||
status: string
|
||||
message?: string
|
||||
}>
|
||||
getPreviewVideoUrl: (hash: string) => string
|
||||
}
|
||||
|
||||
@@ -26,6 +36,12 @@ interface PreviewVideoSectionProps {
|
||||
isDuet?: boolean
|
||||
}
|
||||
|
||||
type PreviewState =
|
||||
| { status: 'generating' }
|
||||
| { status: 'encoding'; slow: boolean }
|
||||
| { status: 'ready'; videoUrl: string }
|
||||
| { status: 'error'; error: string }
|
||||
|
||||
export default function PreviewVideoSection({
|
||||
apiClient,
|
||||
isModalOpen,
|
||||
@@ -35,84 +51,122 @@ export default function PreviewVideoSection({
|
||||
isDuet,
|
||||
}: PreviewVideoSectionProps) {
|
||||
const t = useTranslations('lyricsReview.previewVideo')
|
||||
const [previewState, setPreviewState] = useState<{
|
||||
status: 'loading' | 'warming_up' | 'ready' | 'error'
|
||||
videoUrl?: string
|
||||
error?: string
|
||||
}>({ status: 'loading' })
|
||||
const [previewState, setPreviewState] = useState<PreviewState>({ status: 'generating' })
|
||||
const [retryNonce, setRetryNonce] = useState(0)
|
||||
|
||||
// Generate preview when modal opens
|
||||
// Generate preview when modal opens (or when Retry is clicked).
|
||||
// The POST returns quickly: "success" when the video already exists (cache
|
||||
// hit / local render), or "generating" when encoding continues on a GCE
|
||||
// worker — in that case we poll the status endpoint until the mp4 exists.
|
||||
useEffect(() => {
|
||||
if (isModalOpen && apiClient) {
|
||||
const generatePreview = async () => {
|
||||
setPreviewState({ status: 'loading' })
|
||||
if (!isModalOpen || !apiClient) return
|
||||
|
||||
let cancelled = false
|
||||
let pollTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
const sleep = (ms: number) =>
|
||||
new Promise<void>((resolve) => {
|
||||
pollTimer = setTimeout(resolve, ms)
|
||||
})
|
||||
|
||||
const setReady = (hash: string) => {
|
||||
setPreviewState({ status: 'ready', videoUrl: apiClient.getPreviewVideoUrl(hash) })
|
||||
}
|
||||
|
||||
const pollUntilReady = async (hash: string) => {
|
||||
const startedAt = Date.now()
|
||||
while (!cancelled) {
|
||||
await sleep(POLL_INTERVAL_MS)
|
||||
if (cancelled) return
|
||||
if (Date.now() - startedAt > ENCODE_TIMEOUT_MS) {
|
||||
setPreviewState({ status: 'error', error: t('timedOut') })
|
||||
return
|
||||
}
|
||||
try {
|
||||
// Apply timing offset if needed
|
||||
const dataToPreview =
|
||||
timingOffsetMs !== 0
|
||||
? applyOffsetToCorrectionData(updatedData, timingOffsetMs)
|
||||
: updatedData
|
||||
|
||||
const response = await apiClient.generatePreviewVideo(dataToPreview, isDuet)
|
||||
|
||||
if (response.status === 'worker_starting') {
|
||||
setPreviewState({
|
||||
status: 'warming_up',
|
||||
error: response.message,
|
||||
})
|
||||
const result = await apiClient.getPreviewVideoStatus(hash)
|
||||
if (cancelled) return
|
||||
if (result.status === 'ready') {
|
||||
setReady(hash)
|
||||
return
|
||||
}
|
||||
|
||||
if (response.status === 'error') {
|
||||
setPreviewState({
|
||||
status: 'error',
|
||||
error: response.message || 'Failed to generate preview video',
|
||||
})
|
||||
if (result.status === 'error') {
|
||||
setPreviewState({ status: 'error', error: result.message || t('failed') })
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
// Transient poll failure (network blip) — keep polling until timeout
|
||||
}
|
||||
setPreviewState({
|
||||
status: 'encoding',
|
||||
slow: Date.now() - startedAt > SLOW_ENCODE_THRESHOLD_MS,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (!response.preview_hash) {
|
||||
setPreviewState({
|
||||
status: 'error',
|
||||
error: 'No preview hash received from server',
|
||||
})
|
||||
return
|
||||
}
|
||||
const generatePreview = async () => {
|
||||
setPreviewState({ status: 'generating' })
|
||||
try {
|
||||
// Apply timing offset if needed
|
||||
const dataToPreview =
|
||||
timingOffsetMs !== 0
|
||||
? applyOffsetToCorrectionData(updatedData, timingOffsetMs)
|
||||
: updatedData
|
||||
|
||||
const videoUrl = apiClient.getPreviewVideoUrl(response.preview_hash)
|
||||
setPreviewState({
|
||||
status: 'ready',
|
||||
videoUrl,
|
||||
})
|
||||
} catch (error) {
|
||||
const response = await apiClient.generatePreviewVideo(dataToPreview, isDuet)
|
||||
if (cancelled) return
|
||||
|
||||
if (response.status === 'error' || !response.preview_hash) {
|
||||
setPreviewState({
|
||||
status: 'error',
|
||||
error: (error as Error).message || 'Failed to generate preview video',
|
||||
error: response.message || t('failed'),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (response.status === 'generating') {
|
||||
setPreviewState({ status: 'encoding', slow: false })
|
||||
await pollUntilReady(response.preview_hash)
|
||||
return
|
||||
}
|
||||
|
||||
setReady(response.preview_hash)
|
||||
} catch (error) {
|
||||
if (!cancelled) {
|
||||
setPreviewState({
|
||||
status: 'error',
|
||||
error: (error as Error).message || t('failed'),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
generatePreview()
|
||||
}
|
||||
}, [isModalOpen, apiClient, updatedData, timingOffsetMs, isDuet])
|
||||
|
||||
generatePreview()
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
if (pollTimer) clearTimeout(pollTimer)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- `t` is not referentially stable across renders
|
||||
}, [isModalOpen, apiClient, updatedData, timingOffsetMs, isDuet, retryNonce])
|
||||
|
||||
if (!apiClient) return null
|
||||
|
||||
return (
|
||||
<div className="mb-4">
|
||||
{previewState.status === 'loading' && (
|
||||
{previewState.status === 'generating' && (
|
||||
<div className="flex items-center gap-3 p-4">
|
||||
<Loader2 className="h-5 w-5 animate-spin" />
|
||||
<span>{t('generating')}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{previewState.status === 'warming_up' && (
|
||||
{previewState.status === 'encoding' && (
|
||||
<div className="flex flex-col items-center justify-center p-8 text-center">
|
||||
<div className="h-8 w-8 animate-spin rounded-full border-4 border-gray-200 border-t-blue-500 mb-4" />
|
||||
<p className="text-sm text-gray-600">
|
||||
{t('startingEncoder')}
|
||||
</p>
|
||||
<p className="text-sm">{t('encoding')}</p>
|
||||
{previewState.slow && (
|
||||
<p className="mt-2 text-sm text-gray-600">{t('startingEncoder')}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -123,15 +177,15 @@ export default function PreviewVideoSection({
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setPreviewState({ status: 'loading' })}
|
||||
onClick={() => setRetryNonce((n) => n + 1)}
|
||||
>
|
||||
Retry
|
||||
{t('retry')}
|
||||
</Button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{previewState.status === 'ready' && previewState.videoUrl && (
|
||||
{previewState.status === 'ready' && (
|
||||
<div className="w-full">
|
||||
<video
|
||||
ref={videoRef as RefObject<HTMLVideoElement>}
|
||||
|
||||
@@ -6,8 +6,14 @@ import { cn } from '@/lib/utils'
|
||||
import { WaveformVisualizer } from './WaveformVisualizer'
|
||||
import { VocalsAudioDataLoaderContext } from './VocalsAudioDataLoader'
|
||||
|
||||
// Seconds of context shown (and playable) on each side of the segment in the Edit Segment
|
||||
// timeline. Exported so the modal's play/stop range matches the visible padded view.
|
||||
export const TIMELINE_PAD_SECONDS = 1
|
||||
|
||||
interface TimelineEditorProps {
|
||||
words: Word[]
|
||||
/** Neighbouring segments' words, drawn greyed/read-only where they fall in the padded view. */
|
||||
contextWords?: Word[]
|
||||
startTime: number
|
||||
endTime: number
|
||||
onWordUpdate: (index: number, updates: Partial<Word>) => void
|
||||
@@ -19,6 +25,7 @@ interface TimelineEditorProps {
|
||||
|
||||
export default function TimelineEditor({
|
||||
words,
|
||||
contextWords,
|
||||
startTime,
|
||||
endTime,
|
||||
onWordUpdate,
|
||||
@@ -38,6 +45,14 @@ export default function TimelineEditor({
|
||||
|
||||
const MIN_DURATION = 0.1 // Minimum word duration in seconds
|
||||
|
||||
// Show a little context on each side of the segment (greyed out) so the first word can be
|
||||
// dragged/synced earlier and the last word later, and so the surrounding waveform + any word
|
||||
// blocks that spill just outside the segment stay visible. The whole timeline maps this padded
|
||||
// "view domain" to 0–100%; the segment itself is the un-shaded band in the middle.
|
||||
const viewStart = Math.max(0, startTime - TIMELINE_PAD_SECONDS)
|
||||
const viewEnd = endTime + TIMELINE_PAD_SECONDS
|
||||
const viewDuration = viewEnd - viewStart
|
||||
|
||||
const checkCollision = (
|
||||
proposedStart: number,
|
||||
proposedEnd: number,
|
||||
@@ -79,18 +94,17 @@ export default function TimelineEditor({
|
||||
}
|
||||
|
||||
const timeToPosition = (time: number): number => {
|
||||
const duration = endTime - startTime
|
||||
const position = ((time - startTime) / duration) * 100
|
||||
const position = ((time - viewStart) / viewDuration) * 100
|
||||
return Math.max(0, Math.min(100, position))
|
||||
}
|
||||
|
||||
const generateTimelineMarks = () => {
|
||||
const marks = []
|
||||
const startSecond = Math.floor(startTime)
|
||||
const endSecond = Math.ceil(endTime)
|
||||
const startSecond = Math.floor(viewStart)
|
||||
const endSecond = Math.ceil(viewEnd)
|
||||
|
||||
for (let time = startSecond; time <= endSecond; time++) {
|
||||
if (time >= startTime && time <= endTime) {
|
||||
if (time >= viewStart && time <= viewEnd) {
|
||||
const position = timeToPosition(time)
|
||||
marks.push(
|
||||
<div key={time}>
|
||||
@@ -123,7 +137,7 @@ export default function TimelineEditor({
|
||||
if (word.start_time === null || word.end_time === null) return
|
||||
|
||||
const initialX = e.clientX - rect.left
|
||||
const initialTime = (initialX / rect.width) * (endTime - startTime)
|
||||
const initialTime = (initialX / rect.width) * viewDuration
|
||||
|
||||
setDragState({
|
||||
wordIndex,
|
||||
@@ -152,7 +166,7 @@ export default function TimelineEditor({
|
||||
|
||||
if (dragState.type === 'resize-right') {
|
||||
const initialWordDuration = dragState.word.end_time - dragState.word.start_time
|
||||
const initialWordWidth = (initialWordDuration / (endTime - startTime)) * width
|
||||
const initialWordWidth = (initialWordDuration / viewDuration) * width
|
||||
const pixelDelta = x - dragState.initialX
|
||||
const percentageMoved = pixelDelta / initialWordWidth
|
||||
const timeDelta = initialWordDuration * percentageMoved
|
||||
@@ -170,7 +184,7 @@ export default function TimelineEditor({
|
||||
})
|
||||
} else if (dragState.type === 'resize-left') {
|
||||
const initialWordDuration = dragState.word.end_time - dragState.word.start_time
|
||||
const initialWordWidth = (initialWordDuration / (endTime - startTime)) * width
|
||||
const initialWordWidth = (initialWordDuration / viewDuration) * width
|
||||
const pixelDelta = x - dragState.initialX
|
||||
const percentageMoved = pixelDelta / initialWordWidth
|
||||
const timeDelta = initialWordDuration * percentageMoved
|
||||
@@ -187,7 +201,7 @@ export default function TimelineEditor({
|
||||
end_time: currentWord.end_time,
|
||||
})
|
||||
} else if (dragState.type === 'move') {
|
||||
const pixelsPerSecond = width / (endTime - startTime)
|
||||
const pixelsPerSecond = width / viewDuration
|
||||
const pixelDelta = x - dragState.initialX
|
||||
const timeDelta = pixelDelta / pixelsPerSecond
|
||||
|
||||
@@ -195,7 +209,9 @@ export default function TimelineEditor({
|
||||
const proposedStart = dragState.word.start_time + timeDelta
|
||||
const proposedEnd = proposedStart + wordDuration
|
||||
|
||||
if (proposedStart < startTime || proposedEnd > endTime) return
|
||||
// Allow dragging a little outside the segment (into the padded view) so the first/last
|
||||
// word can extend the segment; updateSegment recomputes the segment bounds from the words.
|
||||
if (proposedStart < viewStart || proposedEnd > viewEnd) return
|
||||
if (checkCollision(proposedStart, proposedEnd, dragState.wordIndex, false)) return
|
||||
|
||||
onWordUpdate(dragState.wordIndex, {
|
||||
@@ -234,7 +250,7 @@ export default function TimelineEditor({
|
||||
if (rect.width <= 0) return
|
||||
|
||||
const x = e.clientX - rect.left
|
||||
const clickedPosition = (x / rect.width) * (endTime - startTime) + startTime
|
||||
const clickedPosition = (x / rect.width) * viewDuration + viewStart
|
||||
if (!Number.isFinite(clickedPosition)) return
|
||||
|
||||
onPlaySegment(clickedPosition)
|
||||
@@ -248,6 +264,18 @@ export default function TimelineEditor({
|
||||
onMouseUp={handleMouseUp}
|
||||
onMouseLeave={handleMouseUp}
|
||||
>
|
||||
{/* Out-of-segment padding: greyed bands on each side of the real segment. These sit above
|
||||
the waveform but below the word bars and are click-through so playback scrubbing still
|
||||
works. Boundary lines mark exactly where the current segment starts/ends. */}
|
||||
<div
|
||||
className="absolute inset-y-0 left-0 bg-muted-foreground/10 pointer-events-none z-[5] border-r border-dashed border-muted-foreground/40"
|
||||
style={{ width: `${timeToPosition(startTime)}%` }}
|
||||
/>
|
||||
<div
|
||||
className="absolute inset-y-0 right-0 bg-muted-foreground/10 pointer-events-none z-[5] border-l border-dashed border-muted-foreground/40"
|
||||
style={{ width: `${100 - timeToPosition(endTime)}%` }}
|
||||
/>
|
||||
|
||||
{/* Timeline ruler */}
|
||||
<div
|
||||
className="h-10 border-b border-border cursor-pointer"
|
||||
@@ -256,8 +284,8 @@ export default function TimelineEditor({
|
||||
{generateTimelineMarks()}
|
||||
</div>
|
||||
|
||||
{/* Playback cursor */}
|
||||
{showPlaybackIndicator && currentTime >= startTime && currentTime <= endTime && (
|
||||
{/* Playback cursor — visible across the padded view (incl. lead-in/out) */}
|
||||
{showPlaybackIndicator && currentTime >= viewStart && currentTime <= viewEnd && (
|
||||
<div
|
||||
className="absolute top-0 w-0.5 h-full bg-destructive pointer-events-none transition-[left] duration-100 z-10"
|
||||
style={{ left: `${timeToPosition(currentTime)}%` }}
|
||||
@@ -266,6 +294,34 @@ export default function TimelineEditor({
|
||||
|
||||
{/* Word blocks */}
|
||||
<div className="relative h-[30px]">
|
||||
{/* Neighbouring segments' words that fall in the padded view — greyed, read-only context. */}
|
||||
{(contextWords ?? []).map((word, index) => {
|
||||
if (word.start_time === null || word.end_time === null) return null
|
||||
if (word.end_time < viewStart || word.start_time > viewEnd) return null
|
||||
|
||||
const leftPosition = timeToPosition(word.start_time)
|
||||
const rightPosition = timeToPosition(word.end_time)
|
||||
const width = rightPosition - leftPosition
|
||||
|
||||
return (
|
||||
<div
|
||||
key={`ctx-${word.id ?? index}`}
|
||||
className={cn(
|
||||
'absolute bg-muted-foreground/25 text-muted-foreground rounded px-2 py-1',
|
||||
'select-none flex items-center text-sm font-sans pointer-events-none',
|
||||
'border border-dashed border-muted-foreground/40 overflow-hidden whitespace-nowrap'
|
||||
)}
|
||||
style={{
|
||||
left: `${leftPosition}%`,
|
||||
width: `${width}%`,
|
||||
maxWidth: `calc(${100 - leftPosition}%)`,
|
||||
}}
|
||||
title={`${word.text} (neighbouring segment)`}
|
||||
>
|
||||
{word.text}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{words.map((word, index) => {
|
||||
if (word.start_time === null || word.end_time === null) return null
|
||||
|
||||
@@ -317,8 +373,10 @@ export default function TimelineEditor({
|
||||
<VocalsAudioDataLoaderContext.Consumer>
|
||||
{({ audioData: vocalsAudioData }) => (
|
||||
vocalsAudioData && <WaveformVisualizer
|
||||
startTime={startTime}
|
||||
endTime={endTime}
|
||||
startTime={viewStart}
|
||||
endTime={viewEnd}
|
||||
fadeBeforeTime={startTime}
|
||||
fadeAfterTime={endTime}
|
||||
audioData={vocalsAudioData}
|
||||
className="w-[100%] h-[35px]"
|
||||
/>
|
||||
|
||||
@@ -8,6 +8,12 @@ export interface WaveformVisualizerProps extends Omit<HTMLProps<HTMLCanvasElemen
|
||||
endTime: number
|
||||
audioData: AudioData | null
|
||||
barColor?: string
|
||||
/** Bars whose time is before this are drawn faded (used to dim the out-of-segment lead-in). */
|
||||
fadeBeforeTime?: number
|
||||
/** Bars whose time is after this are drawn faded (used to dim the out-of-segment lead-out). */
|
||||
fadeAfterTime?: number
|
||||
/** Opacity applied to faded (out-of-segment) bars. */
|
||||
fadedOpacity?: number
|
||||
}
|
||||
|
||||
export const WaveformVisualizer = ({
|
||||
@@ -16,6 +22,9 @@ export const WaveformVisualizer = ({
|
||||
audioData,
|
||||
className,
|
||||
barColor = colors.yellow['500'],
|
||||
fadeBeforeTime,
|
||||
fadeAfterTime,
|
||||
fadedOpacity = 0.28,
|
||||
... canvasProps
|
||||
}: WaveformVisualizerProps) => {
|
||||
const containerRef = useRef<HTMLDivElement | null>(null)
|
||||
@@ -64,7 +73,16 @@ export const WaveformVisualizer = ({
|
||||
const audioData = readAudioData(startTime, endTime)
|
||||
if (!audioData) return
|
||||
|
||||
const windowDuration = endTime - startTime
|
||||
|
||||
for (let x = 0; x < ctx.canvas.width; x++) {
|
||||
// Dim bars that fall outside the segment (the padded lead-in/out context regions).
|
||||
const barTime = startTime + ((x + 0.5) / ctx.canvas.width) * windowDuration
|
||||
const isFaded =
|
||||
(fadeBeforeTime !== undefined && barTime < fadeBeforeTime) ||
|
||||
(fadeAfterTime !== undefined && barTime > fadeAfterTime)
|
||||
ctx.globalAlpha = isFaded ? fadedOpacity : 1
|
||||
|
||||
// Clamp the first pixel: (x - 0.5) is negative at x=0, and a negative
|
||||
// slice start would sample peaks from the end of the window instead.
|
||||
const dataPointIndex = Math.max(0, Math.floor((x - 0.5) / ctx.canvas.width * audioData.length))
|
||||
@@ -84,7 +102,9 @@ export const WaveformVisualizer = ({
|
||||
|
||||
ctx.fillRect(x, (ctx.canvas.height - barHeight) / 2, 1, barHeight)
|
||||
}
|
||||
}, [readAudioData, barColor])
|
||||
|
||||
ctx.globalAlpha = 1
|
||||
}, [readAudioData, barColor, fadeBeforeTime, fadeAfterTime, fadedOpacity])
|
||||
|
||||
// Re-render when the data (readAudioData is memoized on audioData), the window,
|
||||
// the canvas size, or the colour changes. audioData arrives asynchronously, so
|
||||
|
||||
Loaded 100 of 154 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user