Compare commits
No files matched your search
@@ -1243,7 +1243,7 @@ jobs:
|
||||
--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,AUDIO_SEPARATOR_API_URL=https://nomadkaraoke--audio-separator-api.modal.run,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" \
|
||||
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,SENDGRID_API_KEY=sendgrid-api-key: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,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest"
|
||||
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,SENDGRID_API_KEY=sendgrid-api-key: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,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest"
|
||||
|
||||
- name: Verify deployment and version
|
||||
run: |
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
| **Testing & code quality** | `docs/TESTING.md` |
|
||||
| API reference | `docs/API.md` |
|
||||
| Past learnings | `docs/LESSONS-LEARNED.md` |
|
||||
| **Operational runbooks** | `docs/TROUBLESHOOTING.md` |
|
||||
| **Product communication** | `docs/PRODUCT-COMMUNICATION-GUIDE.md` |
|
||||
| Brand style guide | `docs/BRAND-STYLE-GUIDE.md` |
|
||||
|
||||
@@ -128,15 +129,17 @@ EOF
|
||||
|
||||
### GCE Encoding Worker
|
||||
```bash
|
||||
# SSH to restart service (clears in-memory job queue)
|
||||
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
|
||||
--command="sudo systemctl restart encoding-worker"
|
||||
|
||||
# Check health
|
||||
# Check health (includes wheel_version)
|
||||
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
|
||||
--command="curl -s http://localhost:8080/health"
|
||||
|
||||
# Restart service (pick up new wheel after a deploy)
|
||||
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
|
||||
--command="sudo systemctl restart encoding-worker"
|
||||
```
|
||||
|
||||
For job stuck at `encoding` status, see [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md).
|
||||
|
||||
### What Doesn't Work
|
||||
- `gcloud auth print-identity-token` - Wrong token type for internal endpoints
|
||||
- Cloud Tasks without proper service account - Gets 401 from Cloud Run
|
||||
|
||||
@@ -35,6 +35,7 @@ from backend.services.audio_search_service import (
|
||||
NoResultsError,
|
||||
DownloadError,
|
||||
)
|
||||
from backend.services.flacfetch_client import get_flacfetch_client, FlacfetchServiceError
|
||||
from backend.services.youtube_download_service import (
|
||||
get_youtube_download_service,
|
||||
YouTubeDownloadError,
|
||||
@@ -382,8 +383,9 @@ async def _download_audio_and_trigger_workers(
|
||||
raise DownloadError(f"YouTube download failed: {e}")
|
||||
|
||||
elif source_name in ['RED', 'OPS']:
|
||||
# Torrent sources - must use remote flacfetch
|
||||
if not audio_search_service.is_remote_enabled():
|
||||
# Torrent sources - must use remote flacfetch (async, no event loop blocking)
|
||||
flacfetch_client = get_flacfetch_client()
|
||||
if not flacfetch_client:
|
||||
raise DownloadError(
|
||||
f"Cannot download from {source_name} without remote flacfetch service. "
|
||||
"Configure FLACFETCH_API_URL."
|
||||
@@ -393,31 +395,48 @@ async def _download_audio_and_trigger_workers(
|
||||
|
||||
if source_id:
|
||||
logger.info(f"Torrent download via download_by_id: {source_name} ID={source_id}")
|
||||
result = audio_search_service.download_by_id(
|
||||
download_id = await flacfetch_client.download_by_id(
|
||||
source_name=source_name,
|
||||
source_id=source_id,
|
||||
output_dir="",
|
||||
target_file=target_file,
|
||||
download_url=download_url,
|
||||
gcs_path=gcs_destination,
|
||||
)
|
||||
else:
|
||||
if not remote_search_id:
|
||||
raise DownloadError(
|
||||
f"No source_id or remote_search_id available for {source_name} download"
|
||||
)
|
||||
logger.info(f"Torrent download via search-based download")
|
||||
result = audio_search_service.download(
|
||||
download_id = await flacfetch_client.download(
|
||||
search_id=remote_search_id,
|
||||
result_index=selection_index,
|
||||
output_dir="",
|
||||
gcs_path=gcs_destination,
|
||||
remote_search_id=remote_search_id,
|
||||
)
|
||||
|
||||
# Extract GCS path from result
|
||||
audio_gcs_path = _extract_gcs_path(result.filepath)
|
||||
filename = os.path.basename(result.filepath)
|
||||
def log_progress(status):
|
||||
progress = status.get("progress", 0)
|
||||
speed = status.get("download_speed_kbps", 0)
|
||||
logger.debug(f"Download progress: {progress:.1f}% ({speed:.1f} KB/s)")
|
||||
|
||||
final_status = await flacfetch_client.wait_for_download(
|
||||
download_id,
|
||||
timeout=600,
|
||||
progress_callback=log_progress,
|
||||
)
|
||||
|
||||
filepath = final_status.get("gcs_path") or final_status.get("output_path")
|
||||
if not filepath:
|
||||
raise DownloadError("Remote download completed but no file path returned")
|
||||
|
||||
audio_gcs_path = _extract_gcs_path(filepath)
|
||||
filename = os.path.basename(filepath)
|
||||
logger.info(f"Torrent download complete: {audio_gcs_path}")
|
||||
|
||||
elif source_name == 'Spotify':
|
||||
# Spotify downloads - use audio_search_service
|
||||
if not audio_search_service.is_remote_enabled():
|
||||
# Spotify downloads - use async FlacfetchClient directly (no event loop blocking)
|
||||
flacfetch_client = get_flacfetch_client()
|
||||
if not flacfetch_client:
|
||||
raise DownloadError(
|
||||
f"Cannot download from Spotify without remote flacfetch service. "
|
||||
"Configure FLACFETCH_API_URL."
|
||||
@@ -426,25 +445,40 @@ async def _download_audio_and_trigger_workers(
|
||||
gcs_destination = f"uploads/{job_id}/audio/"
|
||||
logger.info(f"Spotify download: source_id={source_id}")
|
||||
|
||||
result = audio_search_service.download_by_id(
|
||||
download_id = await flacfetch_client.download_by_id(
|
||||
source_name=source_name,
|
||||
source_id=source_id,
|
||||
output_dir="",
|
||||
download_url=download_url,
|
||||
gcs_path=gcs_destination,
|
||||
)
|
||||
|
||||
audio_gcs_path = _extract_gcs_path(result.filepath)
|
||||
filename = os.path.basename(result.filepath)
|
||||
def log_progress(status):
|
||||
progress = status.get("progress", 0)
|
||||
speed = status.get("download_speed_kbps", 0)
|
||||
logger.debug(f"Download progress: {progress:.1f}% ({speed:.1f} KB/s)")
|
||||
|
||||
final_status = await flacfetch_client.wait_for_download(
|
||||
download_id,
|
||||
timeout=600,
|
||||
progress_callback=log_progress,
|
||||
)
|
||||
|
||||
filepath = final_status.get("gcs_path") or final_status.get("output_path")
|
||||
if not filepath:
|
||||
raise DownloadError("Remote download completed but no file path returned")
|
||||
|
||||
audio_gcs_path = _extract_gcs_path(filepath)
|
||||
filename = os.path.basename(filepath)
|
||||
logger.info(f"Spotify download complete: {audio_gcs_path}")
|
||||
|
||||
else:
|
||||
# Unknown source - try generic download
|
||||
# Unknown source - try generic download (run sync code in thread to avoid blocking)
|
||||
logger.warning(f"Unknown source type: {source_name}, attempting generic download")
|
||||
temp_dir = tempfile.mkdtemp(prefix=f"audio_download_{job_id}_")
|
||||
|
||||
try:
|
||||
result = audio_search_service.download(
|
||||
result = await asyncio.to_thread(
|
||||
audio_search_service.download,
|
||||
result_index=selection_index,
|
||||
output_dir=temp_dir,
|
||||
remote_search_id=remote_search_id,
|
||||
@@ -494,7 +528,7 @@ async def _download_audio_and_trigger_workers(
|
||||
worker_service.trigger_lyrics_worker(job_id)
|
||||
)
|
||||
|
||||
except DownloadError as e:
|
||||
except (DownloadError, FlacfetchServiceError) as e:
|
||||
logger.error(f"Download failed for job {job_id}: {e}")
|
||||
job_manager.fail_job(job_id, f"Audio download failed: {e}")
|
||||
except Exception as e:
|
||||
@@ -734,7 +768,7 @@ async def search_audio(
|
||||
audio_search_service = get_audio_search_service()
|
||||
|
||||
try:
|
||||
search_results = audio_search_service.search(body.artist, body.title)
|
||||
search_results = await audio_search_service.search_async(body.artist, body.title)
|
||||
except NoResultsError as e:
|
||||
job_manager.fail_job(job_id, f"No audio sources found for: {body.artist} - {body.title}")
|
||||
raise HTTPException(
|
||||
@@ -867,9 +901,9 @@ async def search_audio(
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except (InsufficientCreditsError, RateLimitExceededError):
|
||||
raise
|
||||
except Exception as e:
|
||||
if isinstance(e, (InsufficientCreditsError, RateLimitExceededError)):
|
||||
raise
|
||||
logger.error(f"Error in audio search: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@@ -644,6 +644,55 @@ async def submit_corrections(
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/{job_id}/edit-log")
|
||||
async def submit_edit_log(
|
||||
job_id: str,
|
||||
edit_log: Dict[str, Any],
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> dict:
|
||||
"""
|
||||
Store an edit log from a lyrics review session.
|
||||
|
||||
Edit logs capture what edits users made and optional feedback on why,
|
||||
for use as training data to improve transcription models.
|
||||
|
||||
Stored to GCS as jobs/{job_id}/lyrics/edit_log_{session_id}.json.
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to modify this job")
|
||||
|
||||
session_id = edit_log.get("session_id", "unknown")
|
||||
entries = edit_log.get("entries", [])
|
||||
feedback_count = sum(1 for e in entries if e.get("feedback") and e["feedback"].get("reason") != "no_response")
|
||||
|
||||
try:
|
||||
storage = StorageService()
|
||||
gcs_path = f"jobs/{job_id}/lyrics/edit_log_{session_id}.json"
|
||||
storage.upload_json(gcs_path, edit_log)
|
||||
|
||||
job_manager.update_state_data(job_id, 'last_edit_log_path', gcs_path)
|
||||
job_manager.update_state_data(job_id, 'last_edit_log_session', session_id)
|
||||
|
||||
logger.info(
|
||||
f"Job {job_id}: Edit log saved — {len(entries)} entries, "
|
||||
f"{feedback_count} with feedback, session {session_id}"
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"entries_count": len(entries),
|
||||
"feedback_count": feedback_count,
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error saving edit log for job {job_id}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/{job_id}/create-custom-instrumental")
|
||||
async def create_custom_instrumental(
|
||||
job_id: str,
|
||||
@@ -1655,6 +1704,7 @@ async def cleanup_distribution(
|
||||
# Clean up Dropbox
|
||||
brand_code = state_data.get('brand_code')
|
||||
dropbox_path = getattr(job, 'dropbox_path', None)
|
||||
dropbox_cleaned = False
|
||||
if brand_code and dropbox_path:
|
||||
try:
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
@@ -1664,6 +1714,7 @@ async def cleanup_distribution(
|
||||
folder_name = f"{brand_code} - {base_name}"
|
||||
full_path = f"{dropbox_path}/{folder_name}"
|
||||
success = dropbox.delete_folder(full_path)
|
||||
dropbox_cleaned = success
|
||||
results["dropbox"] = {
|
||||
"status": "success" if success else "failed",
|
||||
"path": full_path
|
||||
@@ -1675,25 +1726,92 @@ async def cleanup_distribution(
|
||||
results["dropbox"] = {"status": "error", "error": str(e)}
|
||||
|
||||
# Clean up Google Drive
|
||||
# Use tracked file IDs if available; otherwise fall back to searching by brand code.
|
||||
# This handles old jobs where gdrive_files was not persisted (e.g., uploaded before
|
||||
# file ID tracking was implemented, or when GDrive upload silently failed and a
|
||||
# previous test run left files behind).
|
||||
gdrive_files = state_data.get('gdrive_files')
|
||||
if gdrive_files:
|
||||
gdrive_folder_id = getattr(job, 'gdrive_folder_id', None)
|
||||
gdrive_cleaned = False
|
||||
|
||||
if gdrive_files or (gdrive_folder_id and brand_code):
|
||||
try:
|
||||
from backend.services.gdrive_service import get_gdrive_service
|
||||
gdrive = get_gdrive_service()
|
||||
if gdrive.is_configured:
|
||||
# gdrive_files is a dict like {"mp4": "file_id", "mp4_720p": "file_id", "cdg": "file_id"}
|
||||
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
|
||||
delete_results = gdrive.delete_files(file_ids)
|
||||
all_success = all(delete_results.values())
|
||||
results["gdrive"] = {
|
||||
"status": "success" if all_success else "partial",
|
||||
"files": delete_results
|
||||
}
|
||||
file_ids: list = []
|
||||
gdrive_method = None # track how files were located for response
|
||||
|
||||
if gdrive_files and isinstance(gdrive_files, dict):
|
||||
# Fast path: delete using tracked file IDs from state_data
|
||||
file_ids = [v for v in gdrive_files.values() if v]
|
||||
logger.info(
|
||||
f"GDrive cleanup for job {job_id}: "
|
||||
f"using {len(file_ids)} tracked file IDs"
|
||||
)
|
||||
|
||||
if not file_ids and gdrive_folder_id and brand_code:
|
||||
# Fallback: search by brand code prefix in CDG/, MP4/, MP4-720p/ subfolders.
|
||||
# Handles jobs where gdrive_files was not tracked (old jobs, or jobs where
|
||||
# GDrive upload succeeded but file IDs were lost).
|
||||
logger.info(
|
||||
f"GDrive cleanup for job {job_id}: "
|
||||
f"no tracked file IDs, searching by brand_code '{brand_code}'"
|
||||
)
|
||||
file_ids = gdrive.find_files_by_brand_code(gdrive_folder_id, brand_code)
|
||||
gdrive_method = "brand_code_search"
|
||||
|
||||
if file_ids:
|
||||
delete_results = gdrive.delete_files(file_ids)
|
||||
all_success = all(delete_results.values())
|
||||
gdrive_cleaned = all_success
|
||||
results["gdrive"] = {
|
||||
"status": "success" if all_success else "partial",
|
||||
"files": delete_results,
|
||||
}
|
||||
if gdrive_method:
|
||||
results["gdrive"]["method"] = gdrive_method
|
||||
else:
|
||||
gdrive_cleaned = True # Nothing to delete
|
||||
results["gdrive"] = {
|
||||
"status": "skipped",
|
||||
"reason": "no files found to delete",
|
||||
}
|
||||
else:
|
||||
results["gdrive"] = {"status": "failed", "reason": "Google Drive credentials not configured"}
|
||||
results["gdrive"] = {
|
||||
"status": "failed",
|
||||
"reason": "Google Drive credentials not configured",
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"Error cleaning up Google Drive for job {job_id}: {e}", exc_info=True)
|
||||
logger.error(
|
||||
f"Error cleaning up Google Drive for job {job_id}: {e}", exc_info=True
|
||||
)
|
||||
results["gdrive"] = {"status": "error", "error": str(e)}
|
||||
else:
|
||||
if not gdrive_folder_id:
|
||||
results["gdrive"]["reason"] = "no gdrive_folder_id on job and no tracked file IDs"
|
||||
|
||||
# Recycle the brand code so it can be reused — but only after GDrive is confirmed clean.
|
||||
# If we recycle before GDrive cleanup, a new job could claim the same brand code and
|
||||
# collide with leftover files on GDrive (duplicate brand code in public share).
|
||||
if dropbox_cleaned and brand_code and gdrive_cleaned:
|
||||
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)
|
||||
results["dropbox"]["recycled_brand_code"] = True
|
||||
logger.info(f"Recycled brand code {brand_code} after full distribution cleanup")
|
||||
except (ValueError, Exception) as e:
|
||||
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
|
||||
results["dropbox"]["recycled_brand_code"] = False
|
||||
elif dropbox_cleaned and brand_code:
|
||||
logger.warning(
|
||||
f"Brand code {brand_code} NOT recycled: GDrive cleanup did not confirm success "
|
||||
f"(gdrive_cleaned={gdrive_cleaned}). Brand code will remain reserved to prevent "
|
||||
f"collisions with leftover GDrive files."
|
||||
)
|
||||
|
||||
# Delete the job if requested
|
||||
if delete_job:
|
||||
|
||||
@@ -732,17 +732,41 @@ async def get_preview_video(
|
||||
@router.post("/{job_id}/v1/annotations")
|
||||
async def submit_annotation(
|
||||
job_id: str,
|
||||
annotation: Dict[str, Any],
|
||||
payload: Dict[str, Any],
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Submit a correction annotation for ML training data.
|
||||
|
||||
For now, just log and acknowledge - full annotation support
|
||||
would require a database.
|
||||
Submit correction annotations for ML training data.
|
||||
|
||||
Accepts either a single annotation dict or {"annotations": [...]} batch.
|
||||
Stores to GCS at jobs/{job_id}/lyrics/annotations.json.
|
||||
"""
|
||||
logger.info(f"Job {job_id}: Annotation submitted (logged but not stored)")
|
||||
return {"status": "success", "annotation_id": "stub"}
|
||||
annotations = payload.get("annotations", [payload]) if isinstance(payload, dict) else [payload]
|
||||
|
||||
try:
|
||||
storage = StorageService()
|
||||
gcs_path = f"jobs/{job_id}/lyrics/annotations.json"
|
||||
|
||||
# Merge with any existing annotations
|
||||
existing: list = []
|
||||
try:
|
||||
existing_data = storage.download_json(gcs_path)
|
||||
if isinstance(existing_data, list):
|
||||
existing = existing_data
|
||||
elif isinstance(existing_data, dict) and "annotations" in existing_data:
|
||||
existing = existing_data["annotations"]
|
||||
except Exception:
|
||||
pass # No existing file, start fresh
|
||||
|
||||
merged = existing + annotations
|
||||
storage.upload_json(gcs_path, {"annotations": merged})
|
||||
|
||||
logger.info(f"Job {job_id}: {len(annotations)} annotation(s) saved ({len(merged)} total)")
|
||||
return {"status": "success", "saved_count": len(annotations), "total_count": len(merged)}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error saving annotations: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/{job_id}/v1/annotations/stats")
|
||||
@@ -751,11 +775,18 @@ async def get_annotation_stats(
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Get annotation statistics."""
|
||||
return {
|
||||
"total_annotations": 0,
|
||||
"by_type": {},
|
||||
"message": "Annotation stats not yet implemented"
|
||||
}
|
||||
try:
|
||||
storage = StorageService()
|
||||
gcs_path = f"jobs/{job_id}/lyrics/annotations.json"
|
||||
data = storage.download_json(gcs_path)
|
||||
annotations = data.get("annotations", []) if isinstance(data, dict) else data
|
||||
by_type: Dict[str, int] = {}
|
||||
for a in annotations:
|
||||
atype = a.get("annotation_type", "unknown")
|
||||
by_type[atype] = by_type.get(atype, 0) + 1
|
||||
return {"total_annotations": len(annotations), "by_type": by_type}
|
||||
except Exception:
|
||||
return {"total_annotations": 0, "by_type": {}}
|
||||
|
||||
|
||||
@router.get("/{job_id}/instrumental-analysis")
|
||||
|
||||
@@ -612,13 +612,13 @@ class AudioSearchService:
|
||||
async def search_async(self, artist: str, title: str) -> List[AudioSearchResult]:
|
||||
"""
|
||||
Async version of search for use in async routes.
|
||||
|
||||
Note: Currently wraps sync search in executor. Future optimization
|
||||
could make this fully async.
|
||||
|
||||
Runs the sync search in a thread executor to avoid blocking
|
||||
the event loop.
|
||||
"""
|
||||
loop = asyncio.get_event_loop()
|
||||
loop = asyncio.get_running_loop()
|
||||
return await loop.run_in_executor(None, self.search, artist, title)
|
||||
|
||||
|
||||
async def download_async(
|
||||
self,
|
||||
result_index: int,
|
||||
@@ -630,10 +630,10 @@ class AudioSearchService:
|
||||
"""
|
||||
Async version of download for use in async routes.
|
||||
|
||||
Note: Currently wraps sync download in executor. Future optimization
|
||||
could make this fully async.
|
||||
Runs the sync download in a thread executor to avoid blocking
|
||||
the event loop.
|
||||
"""
|
||||
loop = asyncio.get_event_loop()
|
||||
loop = asyncio.get_running_loop()
|
||||
return await loop.run_in_executor(
|
||||
None,
|
||||
lambda: self.download(result_index, output_dir, output_filename, gcs_path, remote_search_id)
|
||||
@@ -651,8 +651,11 @@ class AudioSearchService:
|
||||
) -> AudioDownloadResult:
|
||||
"""
|
||||
Async version of download_by_id for use in async routes.
|
||||
|
||||
Runs the sync download_by_id in a thread executor to avoid blocking
|
||||
the event loop.
|
||||
"""
|
||||
loop = asyncio.get_event_loop()
|
||||
loop = asyncio.get_running_loop()
|
||||
return await loop.run_in_executor(
|
||||
None,
|
||||
lambda: self.download_by_id(
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
"""
|
||||
Brand code allocation service using Firestore atomic counters.
|
||||
|
||||
Replaces the previous Dropbox folder-scanning approach which was susceptible to
|
||||
TOCTOU race conditions when concurrent jobs read the same folder state.
|
||||
|
||||
Uses Firestore transactions to atomically allocate unique brand codes.
|
||||
Supports recycling numbers when E2E cleanup deletes test brand codes.
|
||||
"""
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from google.cloud import firestore
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
BRAND_CODE_COUNTERS_COLLECTION = "brand_code_counters"
|
||||
|
||||
# Singleton instance
|
||||
_brand_code_service: Optional["BrandCodeService"] = None
|
||||
|
||||
|
||||
class BrandCodeService:
|
||||
"""Atomic brand code allocation using Firestore counters."""
|
||||
|
||||
def __init__(self, db: Optional[firestore.Client] = None):
|
||||
if db is None:
|
||||
self.db = firestore.Client(project=settings.google_cloud_project)
|
||||
else:
|
||||
self.db = db
|
||||
|
||||
def allocate_brand_code(self, prefix: str, dropbox_path: str) -> str:
|
||||
"""
|
||||
Atomically allocate the next brand code for a given prefix.
|
||||
|
||||
Uses a Firestore transaction to ensure no two concurrent callers
|
||||
receive the same number. If recycled numbers are available (from
|
||||
E2E cleanup), the smallest recycled number is reused first.
|
||||
|
||||
On first use for a prefix, initializes the counter by scanning
|
||||
Dropbox to find the current max number.
|
||||
|
||||
Args:
|
||||
prefix: Brand prefix (e.g., "NOMAD" or "NOMADNP")
|
||||
dropbox_path: Dropbox path for one-time initialization scan
|
||||
|
||||
Returns:
|
||||
Brand code string (e.g., "NOMAD-1264")
|
||||
"""
|
||||
doc_ref = self.db.collection(BRAND_CODE_COUNTERS_COLLECTION).document(prefix)
|
||||
|
||||
@firestore.transactional
|
||||
def allocate_in_transaction(transaction):
|
||||
doc = doc_ref.get(transaction=transaction)
|
||||
|
||||
if not doc.exists:
|
||||
# First use — initialize from Dropbox scan
|
||||
next_number = self._get_initial_next_number(prefix, dropbox_path)
|
||||
allocated = next_number
|
||||
transaction.set(doc_ref, {
|
||||
"prefix": prefix,
|
||||
"next_number": next_number + 1,
|
||||
"recycled": [],
|
||||
"initialized_at": datetime.now(timezone.utc),
|
||||
"last_updated": datetime.now(timezone.utc),
|
||||
})
|
||||
return allocated
|
||||
|
||||
data = doc.to_dict()
|
||||
recycled = data.get("recycled", [])
|
||||
|
||||
if recycled:
|
||||
# Reuse smallest recycled number
|
||||
recycled.sort()
|
||||
allocated = recycled.pop(0)
|
||||
transaction.update(doc_ref, {
|
||||
"recycled": recycled,
|
||||
"last_updated": datetime.now(timezone.utc),
|
||||
})
|
||||
else:
|
||||
# Allocate next sequential number
|
||||
allocated = data["next_number"]
|
||||
transaction.update(doc_ref, {
|
||||
"next_number": allocated + 1,
|
||||
"last_updated": datetime.now(timezone.utc),
|
||||
})
|
||||
|
||||
return allocated
|
||||
|
||||
transaction = self.db.transaction()
|
||||
number = allocate_in_transaction(transaction)
|
||||
brand_code = f"{prefix}-{number:04d}"
|
||||
logger.info(f"Allocated brand code: {brand_code}")
|
||||
return brand_code
|
||||
|
||||
def recycle_brand_code(self, prefix: str, number: int) -> None:
|
||||
"""
|
||||
Return a brand code number to the recycled pool.
|
||||
|
||||
Called when E2E cleanup deletes a brand code's distribution.
|
||||
The number will be reused on the next allocation for this prefix.
|
||||
|
||||
Args:
|
||||
prefix: Brand prefix (e.g., "NOMAD")
|
||||
number: The numeric portion to recycle (e.g., 1234)
|
||||
"""
|
||||
doc_ref = self.db.collection(BRAND_CODE_COUNTERS_COLLECTION).document(prefix)
|
||||
|
||||
@firestore.transactional
|
||||
def recycle_in_transaction(transaction):
|
||||
doc = doc_ref.get(transaction=transaction)
|
||||
|
||||
if not doc.exists:
|
||||
# Counter doesn't exist yet — nothing to recycle into.
|
||||
# The number will naturally be below next_number when
|
||||
# the counter is initialized, so it would create a gap.
|
||||
# Just log and skip.
|
||||
logger.warning(
|
||||
f"Cannot recycle {prefix}-{number:04d}: counter doc doesn't exist"
|
||||
)
|
||||
return
|
||||
|
||||
data = doc.to_dict()
|
||||
next_number = data.get("next_number", 0)
|
||||
|
||||
if number <= 0 or number >= next_number:
|
||||
logger.warning(
|
||||
f"Cannot recycle {prefix}-{number:04d}: "
|
||||
f"invalid (next_number={next_number})"
|
||||
)
|
||||
return
|
||||
|
||||
recycled = data.get("recycled", [])
|
||||
|
||||
if number not in recycled:
|
||||
recycled.append(number)
|
||||
transaction.update(doc_ref, {
|
||||
"recycled": recycled,
|
||||
"last_updated": datetime.now(timezone.utc),
|
||||
})
|
||||
logger.info(f"Recycled brand code number: {prefix}-{number:04d}")
|
||||
else:
|
||||
logger.warning(f"Number {number} already in recycled pool for {prefix}")
|
||||
|
||||
transaction = self.db.transaction()
|
||||
recycle_in_transaction(transaction)
|
||||
|
||||
def _get_initial_next_number(self, prefix: str, dropbox_path: str) -> int:
|
||||
"""
|
||||
Scan Dropbox once to determine the starting next_number.
|
||||
|
||||
This is only called when the counter document doesn't exist yet
|
||||
(one-time migration from the old Dropbox-scanning approach).
|
||||
|
||||
Args:
|
||||
prefix: Brand prefix to scan for
|
||||
dropbox_path: Dropbox path containing organized folders
|
||||
|
||||
Returns:
|
||||
The next number to allocate (max existing + 1, minimum 1)
|
||||
"""
|
||||
try:
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
|
||||
dropbox = get_dropbox_service()
|
||||
if not dropbox.is_configured:
|
||||
logger.warning(
|
||||
f"Dropbox not configured for initialization of {prefix} counter, starting at 1"
|
||||
)
|
||||
return 1
|
||||
|
||||
folders = dropbox.list_folders(dropbox_path)
|
||||
pattern = re.compile(rf"^{re.escape(prefix)}-(\d{{4}})")
|
||||
|
||||
existing_nums: set[int] = set()
|
||||
for folder in folders:
|
||||
match = pattern.match(folder)
|
||||
if match:
|
||||
existing_nums.add(int(match.group(1)))
|
||||
|
||||
if existing_nums:
|
||||
next_num = max(existing_nums) + 1
|
||||
logger.info(
|
||||
f"Initialized {prefix} counter from Dropbox: "
|
||||
f"max existing={max(existing_nums)}, next_number={next_num}"
|
||||
)
|
||||
return next_num
|
||||
|
||||
logger.info(f"No existing {prefix} codes found in Dropbox, starting at 1")
|
||||
return 1
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to initialize {prefix} counter from Dropbox: {e}")
|
||||
raise
|
||||
|
||||
@staticmethod
|
||||
def parse_brand_code(brand_code: str) -> tuple[str, int]:
|
||||
"""
|
||||
Parse a brand code string into prefix and number.
|
||||
|
||||
Args:
|
||||
brand_code: e.g., "NOMAD-1234" or "NOMADNP-0012"
|
||||
|
||||
Returns:
|
||||
Tuple of (prefix, number), e.g., ("NOMAD", 1234)
|
||||
|
||||
Raises:
|
||||
ValueError: If brand_code doesn't match expected format
|
||||
"""
|
||||
match = re.match(r"^([A-Z]+)-(\d+)$", brand_code)
|
||||
if not match:
|
||||
raise ValueError(f"Invalid brand code format: {brand_code}")
|
||||
return match.group(1), int(match.group(2))
|
||||
|
||||
|
||||
def get_brand_code_service() -> BrandCodeService:
|
||||
"""Get or create the singleton BrandCodeService instance."""
|
||||
global _brand_code_service
|
||||
if _brand_code_service is None:
|
||||
_brand_code_service = BrandCodeService()
|
||||
return _brand_code_service
|
||||
@@ -111,6 +111,10 @@ class DropboxService:
|
||||
"""
|
||||
Calculate next brand code from existing folders, filling gaps in the sequence.
|
||||
|
||||
NOTE: This method is only used for one-time initialization of the Firestore
|
||||
counter (see brand_code_service.py). All runtime brand code allocation now
|
||||
goes through BrandCodeService.allocate_brand_code() for atomic safety.
|
||||
|
||||
Scans the folder for existing brand codes like "NOMAD-0001" and
|
||||
returns the first available code, filling any gaps left by deleted outputs.
|
||||
|
||||
|
||||
@@ -198,7 +198,24 @@ class EncodingService:
|
||||
if resp["status"] == 401:
|
||||
raise RuntimeError("Invalid API key for encoding worker")
|
||||
if resp["status"] == 409:
|
||||
raise RuntimeError(f"Encoding job {job_id} already exists")
|
||||
# Job already exists on worker — check if it already completed
|
||||
logger.warning(f"[job:{job_id}] GCE worker returned 409, checking job status")
|
||||
try:
|
||||
status = await self.get_job_status(job_id)
|
||||
job_status = status.get("status", "unknown")
|
||||
if job_status == "complete":
|
||||
logger.info(f"[job:{job_id}] Job already complete on GCE worker, returning cached result")
|
||||
return {"status": "cached", "job_id": job_id, "output_files": status.get("output_files")}
|
||||
elif job_status in ("pending", "running"):
|
||||
logger.info(f"[job:{job_id}] Job still in progress on GCE worker")
|
||||
return {"status": "in_progress", "job_id": job_id}
|
||||
else:
|
||||
raise RuntimeError(f"Encoding job {job_id} already exists with status: {job_status}")
|
||||
except RuntimeError as e:
|
||||
if "not found" in str(e).lower():
|
||||
# Job was in worker memory but got cleared (restart) — safe to raise original error
|
||||
raise RuntimeError(f"Encoding job {job_id} conflict: 409 but job not found on status check")
|
||||
raise
|
||||
if resp["status"] != 200:
|
||||
raise RuntimeError(f"Failed to submit encoding job: {resp['status']} - {resp['text']}")
|
||||
|
||||
@@ -331,7 +348,17 @@ class EncodingService:
|
||||
config = encoding_config or {"formats": ["mp4_4k", "mp4_720p"]}
|
||||
|
||||
# Submit the job
|
||||
await self.submit_encoding_job(job_id, input_gcs_path, output_gcs_path, config)
|
||||
submit_result = await self.submit_encoding_job(job_id, input_gcs_path, output_gcs_path, config)
|
||||
|
||||
# If cached, return immediately — encoding already done
|
||||
submit_status = submit_result.get("status")
|
||||
if submit_status == "cached":
|
||||
logger.info(f"[job:{job_id}] Encoding already cached, returning immediately")
|
||||
return {"status": "complete", "output_files": submit_result.get("output_files")}
|
||||
|
||||
# If in_progress, another request is encoding it — just wait for that
|
||||
if submit_status == "in_progress":
|
||||
logger.info(f"[job:{job_id}] Encoding already in progress, joining poll")
|
||||
|
||||
# Wait for completion
|
||||
return await self.wait_for_completion(
|
||||
|
||||
@@ -596,8 +596,18 @@ async def submit_encode_job(request: EncodeRequest, background_tasks: Background
|
||||
# Submit an encoding job
|
||||
job_id = request.job_id
|
||||
|
||||
# If job already exists, return cached result or current status
|
||||
if job_id in jobs:
|
||||
raise HTTPException(status_code=409, detail=f"Job {job_id} already exists")
|
||||
existing_job = jobs[job_id]
|
||||
if existing_job["status"] == "complete":
|
||||
# Return cached result - encoding already done
|
||||
return {"status": "cached", "job_id": job_id, "output_files": existing_job.get("output_files")}
|
||||
elif existing_job["status"] == "failed":
|
||||
# Previous attempt failed, allow retry by replacing the job
|
||||
pass
|
||||
else:
|
||||
# Job is still in progress
|
||||
return {"status": "in_progress", "job_id": job_id}
|
||||
|
||||
jobs[job_id] = {
|
||||
"job_id": job_id,
|
||||
|
||||
@@ -12,13 +12,19 @@ shared with YouTube credentials if scopes include drive.file.
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import ssl
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from tenacity import Retrying, stop_after_attempt, wait_exponential, retry_if_exception_type
|
||||
|
||||
from backend.config import get_settings
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Transient errors that indicate a stale HTTP connection (Cloud Run idle containers)
|
||||
TRANSIENT_ERRORS = (BrokenPipeError, ConnectionResetError, ConnectionError, ssl.SSLError)
|
||||
|
||||
|
||||
class GoogleDriveService:
|
||||
"""Google Drive operations using native API."""
|
||||
@@ -33,6 +39,11 @@ class GoogleDriveService:
|
||||
self._credentials_data: Optional[Dict[str, Any]] = None
|
||||
self._loaded = False
|
||||
|
||||
def _reset_service(self):
|
||||
"""Reset the cached Drive service to force a fresh connection on next use."""
|
||||
logger.info("Resetting Google Drive service connection")
|
||||
self._service = None
|
||||
|
||||
def _load_credentials(self) -> Optional[Dict[str, Any]]:
|
||||
"""Load OAuth credentials from Secret Manager."""
|
||||
if self._loaded:
|
||||
@@ -127,6 +138,9 @@ class GoogleDriveService:
|
||||
"""
|
||||
Get existing folder or create new one, return folder ID.
|
||||
|
||||
Retries on transient connection errors (BrokenPipeError, SSLError)
|
||||
that occur when Cloud Run containers sit idle between jobs.
|
||||
|
||||
Args:
|
||||
parent_id: Parent folder ID
|
||||
folder_name: Name of folder to find or create
|
||||
@@ -134,33 +148,41 @@ class GoogleDriveService:
|
||||
Returns:
|
||||
Folder ID
|
||||
"""
|
||||
logger.info(f"Looking for folder '{folder_name}' in parent {parent_id}")
|
||||
for attempt in Retrying(
|
||||
stop=stop_after_attempt(3),
|
||||
wait=wait_exponential(multiplier=1, min=2, max=8),
|
||||
retry=retry_if_exception_type(TRANSIENT_ERRORS),
|
||||
before_sleep=lambda retry_state: self._reset_service(),
|
||||
reraise=True,
|
||||
):
|
||||
with attempt:
|
||||
logger.info(f"Looking for folder '{folder_name}' in parent {parent_id}")
|
||||
|
||||
# Search for existing folder
|
||||
# Escape single quotes in folder name for Google Drive API query syntax
|
||||
escaped_folder_name = folder_name.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_folder_name}' and '{parent_id}' in parents "
|
||||
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
|
||||
)
|
||||
results = self.service.files().list(q=query, fields="files(id, name)").execute()
|
||||
# Search for existing folder
|
||||
# Escape single quotes in folder name for Google Drive API query syntax
|
||||
escaped_folder_name = folder_name.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_folder_name}' and '{parent_id}' in parents "
|
||||
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
|
||||
)
|
||||
results = self.service.files().list(q=query, fields="files(id, name)").execute()
|
||||
|
||||
if results.get("files"):
|
||||
folder_id = results["files"][0]["id"]
|
||||
logger.info(f"Found existing folder '{folder_name}': {folder_id}")
|
||||
return folder_id
|
||||
if results.get("files"):
|
||||
folder_id = results["files"][0]["id"]
|
||||
logger.info(f"Found existing folder '{folder_name}': {folder_id}")
|
||||
return folder_id
|
||||
|
||||
# Create folder
|
||||
logger.info(f"Creating new folder '{folder_name}'")
|
||||
metadata = {
|
||||
"name": folder_name,
|
||||
"mimeType": "application/vnd.google-apps.folder",
|
||||
"parents": [parent_id],
|
||||
}
|
||||
folder = self.service.files().create(body=metadata, fields="id").execute()
|
||||
folder_id = folder["id"]
|
||||
logger.info(f"Created folder '{folder_name}': {folder_id}")
|
||||
return folder_id
|
||||
# Create folder
|
||||
logger.info(f"Creating new folder '{folder_name}'")
|
||||
metadata = {
|
||||
"name": folder_name,
|
||||
"mimeType": "application/vnd.google-apps.folder",
|
||||
"parents": [parent_id],
|
||||
}
|
||||
folder = self.service.files().create(body=metadata, fields="id").execute()
|
||||
folder_id = folder["id"]
|
||||
logger.info(f"Created folder '{folder_name}': {folder_id}")
|
||||
return folder_id
|
||||
|
||||
def upload_file(
|
||||
self,
|
||||
@@ -172,6 +194,9 @@ class GoogleDriveService:
|
||||
"""
|
||||
Upload a file to a specific Drive folder.
|
||||
|
||||
Retries on transient connection errors (BrokenPipeError, SSLError)
|
||||
that occur when Cloud Run containers sit idle between jobs.
|
||||
|
||||
Args:
|
||||
local_path: Local file path
|
||||
parent_id: Parent folder ID in Google Drive
|
||||
@@ -183,49 +208,57 @@ class GoogleDriveService:
|
||||
"""
|
||||
from googleapiclient.http import MediaFileUpload
|
||||
|
||||
file_size = os.path.getsize(local_path)
|
||||
logger.info(
|
||||
f"Uploading {local_path} ({file_size / 1024 / 1024:.1f} MB) "
|
||||
f"as '{filename}' to folder {parent_id}"
|
||||
)
|
||||
for attempt in Retrying(
|
||||
stop=stop_after_attempt(3),
|
||||
wait=wait_exponential(multiplier=1, min=2, max=8),
|
||||
retry=retry_if_exception_type(TRANSIENT_ERRORS),
|
||||
before_sleep=lambda retry_state: self._reset_service(),
|
||||
reraise=True,
|
||||
):
|
||||
with attempt:
|
||||
file_size = os.path.getsize(local_path)
|
||||
logger.info(
|
||||
f"Uploading {local_path} ({file_size / 1024 / 1024:.1f} MB) "
|
||||
f"as '{filename}' to folder {parent_id}"
|
||||
)
|
||||
|
||||
# Determine MIME type
|
||||
ext = os.path.splitext(local_path)[1].lower()
|
||||
mime_types = {
|
||||
".mp4": "video/mp4",
|
||||
".mkv": "video/x-matroska",
|
||||
".zip": "application/zip",
|
||||
".flac": "audio/flac",
|
||||
".mp3": "audio/mpeg",
|
||||
".wav": "audio/wav",
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
}
|
||||
mime_type = mime_types.get(ext, "application/octet-stream")
|
||||
# Determine MIME type
|
||||
ext = os.path.splitext(local_path)[1].lower()
|
||||
mime_types = {
|
||||
".mp4": "video/mp4",
|
||||
".mkv": "video/x-matroska",
|
||||
".zip": "application/zip",
|
||||
".flac": "audio/flac",
|
||||
".mp3": "audio/mpeg",
|
||||
".wav": "audio/wav",
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
}
|
||||
mime_type = mime_types.get(ext, "application/octet-stream")
|
||||
|
||||
# Check for existing file with same name
|
||||
if replace_existing:
|
||||
# Escape single quotes in filename for Google Drive API query syntax
|
||||
escaped_filename = filename.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_filename}' and '{parent_id}' in parents and trashed=false"
|
||||
)
|
||||
results = self.service.files().list(q=query, fields="files(id)").execute()
|
||||
for existing_file in results.get("files", []):
|
||||
logger.info(f"Deleting existing file: {existing_file['id']}")
|
||||
self.service.files().delete(fileId=existing_file["id"]).execute()
|
||||
# Check for existing file with same name
|
||||
if replace_existing:
|
||||
# Escape single quotes in filename for Google Drive API query syntax
|
||||
escaped_filename = filename.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_filename}' and '{parent_id}' in parents and trashed=false"
|
||||
)
|
||||
results = self.service.files().list(q=query, fields="files(id)").execute()
|
||||
for existing_file in results.get("files", []):
|
||||
logger.info(f"Deleting existing file: {existing_file['id']}")
|
||||
self.service.files().delete(fileId=existing_file["id"]).execute()
|
||||
|
||||
# Upload file
|
||||
metadata = {"name": filename, "parents": [parent_id]}
|
||||
media = MediaFileUpload(local_path, mimetype=mime_type, resumable=True)
|
||||
# Upload file
|
||||
metadata = {"name": filename, "parents": [parent_id]}
|
||||
media = MediaFileUpload(local_path, mimetype=mime_type, resumable=True)
|
||||
|
||||
file_result = (
|
||||
self.service.files().create(body=metadata, media_body=media, fields="id").execute()
|
||||
)
|
||||
file_id = file_result["id"]
|
||||
logger.info(f"Successfully uploaded '{filename}': {file_id}")
|
||||
return file_id
|
||||
file_result = (
|
||||
self.service.files().create(body=metadata, media_body=media, fields="id").execute()
|
||||
)
|
||||
file_id = file_result["id"]
|
||||
logger.info(f"Successfully uploaded '{filename}': {file_id}")
|
||||
return file_id
|
||||
|
||||
def upload_to_public_share(
|
||||
self,
|
||||
@@ -308,6 +341,9 @@ class GoogleDriveService:
|
||||
"""
|
||||
Delete a file from Google Drive.
|
||||
|
||||
Retries on transient connection errors (BrokenPipeError, SSLError)
|
||||
that occur when Cloud Run containers sit idle between jobs.
|
||||
|
||||
Args:
|
||||
file_id: Google Drive file ID to delete
|
||||
|
||||
@@ -317,9 +353,17 @@ class GoogleDriveService:
|
||||
logger.info(f"Deleting Google Drive file: {file_id}")
|
||||
|
||||
try:
|
||||
self.service.files().delete(fileId=file_id).execute()
|
||||
logger.info(f"Successfully deleted file: {file_id}")
|
||||
return True
|
||||
for attempt in Retrying(
|
||||
stop=stop_after_attempt(3),
|
||||
wait=wait_exponential(multiplier=1, min=2, max=8),
|
||||
retry=retry_if_exception_type(TRANSIENT_ERRORS),
|
||||
before_sleep=lambda retry_state: self._reset_service(),
|
||||
reraise=True,
|
||||
):
|
||||
with attempt:
|
||||
self.service.files().delete(fileId=file_id).execute()
|
||||
logger.info(f"Successfully deleted file: {file_id}")
|
||||
return True
|
||||
except Exception as e:
|
||||
# Check if it's a 404 (already deleted)
|
||||
if hasattr(e, 'resp') and e.resp.status == 404:
|
||||
@@ -343,6 +387,85 @@ class GoogleDriveService:
|
||||
results[file_id] = self.delete_file(file_id)
|
||||
return results
|
||||
|
||||
def find_files_by_brand_code(self, root_folder_id: str, brand_code: str) -> list[str]:
|
||||
"""
|
||||
Search for files in public share subfolders matching a brand code prefix.
|
||||
|
||||
Used as a fallback when gdrive_files is not tracked in state_data (e.g., old
|
||||
jobs uploaded before file ID tracking was implemented, or jobs where GDrive
|
||||
upload succeeded but file IDs were not saved due to a bug).
|
||||
|
||||
Searches CDG/, MP4/, MP4-720p/ subfolders for files whose name starts with
|
||||
'{brand_code} - '.
|
||||
|
||||
Args:
|
||||
root_folder_id: Root Google Drive folder ID for the public share
|
||||
brand_code: Brand code prefix to search for (e.g., "NOMAD-1271")
|
||||
|
||||
Returns:
|
||||
List of file IDs found matching the brand code
|
||||
"""
|
||||
found_ids = []
|
||||
subfolders = ["CDG", "MP4", "MP4-720p"]
|
||||
search_errors: list[Exception] = []
|
||||
|
||||
for subfolder in subfolders:
|
||||
try:
|
||||
# Find the subfolder
|
||||
escaped_subfolder = subfolder.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_subfolder}' and '{root_folder_id}' in parents "
|
||||
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
|
||||
)
|
||||
results = self.service.files().list(
|
||||
q=query, fields="files(id, name)", supportsAllDrives=True,
|
||||
includeItemsFromAllDrives=True
|
||||
).execute()
|
||||
|
||||
if not results.get("files"):
|
||||
logger.debug(f"Subfolder '{subfolder}' not found in {root_folder_id}")
|
||||
continue
|
||||
|
||||
subfolder_id = results["files"][0]["id"]
|
||||
|
||||
# Search for files whose name starts with the brand code
|
||||
# Use contains for efficiency, then filter by exact prefix
|
||||
escaped_brand = brand_code.replace("'", "\\'")
|
||||
file_query = (
|
||||
f"name contains '{escaped_brand}' and '{subfolder_id}' in parents "
|
||||
f"and trashed=false"
|
||||
)
|
||||
file_results = self.service.files().list(
|
||||
q=file_query, fields="files(id, name)", supportsAllDrives=True,
|
||||
includeItemsFromAllDrives=True
|
||||
).execute()
|
||||
|
||||
for f in file_results.get("files", []):
|
||||
if f["name"].startswith(f"{brand_code} - "):
|
||||
found_ids.append(f["id"])
|
||||
logger.info(
|
||||
f"Found GDrive file to clean up in {subfolder}/: "
|
||||
f"{f['name']} ({f['id']})"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Error searching for brand_code '{brand_code}' in '{subfolder}': {e}",
|
||||
exc_info=True,
|
||||
)
|
||||
search_errors.append(e)
|
||||
|
||||
if search_errors:
|
||||
# Raise so the caller knows the search was incomplete.
|
||||
# This prevents the cleanup endpoint from treating an uncertain result
|
||||
# as "GDrive is clean" and incorrectly recycling the brand code.
|
||||
raise RuntimeError(
|
||||
f"GDrive brand_code search incomplete: "
|
||||
f"{len(search_errors)}/{len(subfolders)} subfolder(s) failed"
|
||||
)
|
||||
|
||||
return found_ids
|
||||
|
||||
|
||||
# Singleton instance
|
||||
_gdrive_service: Optional[GoogleDriveService] = None
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"""
|
||||
GDrive Validator Cloud Function client.
|
||||
|
||||
Lightweight HTTP client for invoking the gdrive-validator Cloud Function
|
||||
from the backend (e.g., after job completion). Uses OIDC authentication
|
||||
via the backend's service account.
|
||||
|
||||
Fire-and-forget pattern: never blocks or fails the caller.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
|
||||
import requests
|
||||
import google.auth.transport.requests
|
||||
import google.oauth2.id_token
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Cloud Function URL - set via environment variable
|
||||
GDRIVE_VALIDATOR_URL = os.environ.get("GDRIVE_VALIDATOR_URL", "")
|
||||
|
||||
|
||||
def trigger_gdrive_validation() -> dict | None:
|
||||
"""
|
||||
Invoke the GDrive validator Cloud Function.
|
||||
|
||||
Uses the backend service account's OIDC token for authentication.
|
||||
|
||||
Returns:
|
||||
Parsed JSON response from the function, or None on error.
|
||||
"""
|
||||
if not GDRIVE_VALIDATOR_URL:
|
||||
logger.debug("GDRIVE_VALIDATOR_URL not set, skipping GDrive validation trigger")
|
||||
return None
|
||||
|
||||
try:
|
||||
# Get OIDC token for the Cloud Function URL
|
||||
auth_request = google.auth.transport.requests.Request()
|
||||
token = google.oauth2.id_token.fetch_id_token(auth_request, GDRIVE_VALIDATOR_URL)
|
||||
|
||||
response = requests.post(
|
||||
GDRIVE_VALIDATOR_URL,
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=60,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
result = response.json()
|
||||
status = result.get("status", "unknown")
|
||||
|
||||
if status == "issues_found":
|
||||
logger.warning("GDrive validation found issues (notification sent)")
|
||||
elif status == "ok":
|
||||
logger.info("GDrive validation: all clear")
|
||||
else:
|
||||
logger.info(f"GDrive validation returned status: {status}")
|
||||
|
||||
return result
|
||||
|
||||
except Exception:
|
||||
logger.exception("Failed to trigger GDrive validation (non-fatal)")
|
||||
return None
|
||||
@@ -7,6 +7,7 @@ bugs in the state machine or trigger logic.
|
||||
Created as part of state machine robustness improvements (2026-02-02).
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import List, Dict, Any, Optional
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
@@ -104,6 +105,21 @@ def check_job_consistency(job: Job) -> List[str]:
|
||||
f"pending_with_input_media: has input_media_gcs_path but status=pending (may be stuck)"
|
||||
)
|
||||
|
||||
# Check: job stuck in encoding status beyond 50 minutes
|
||||
# Encoding timeout is 1 hour; if updated_at hasn't advanced in 50 min,
|
||||
# the poller likely died (e.g., Cloud Run deployment killed the instance)
|
||||
if status == JobStatus.ENCODING and job.updated_at:
|
||||
now = datetime.now(timezone.utc)
|
||||
updated_at = job.updated_at
|
||||
if updated_at.tzinfo is None:
|
||||
updated_at = updated_at.replace(tzinfo=timezone.utc)
|
||||
encoding_age = now - updated_at
|
||||
if encoding_age > timedelta(minutes=50):
|
||||
minutes = int(encoding_age.total_seconds() / 60)
|
||||
issues.append(
|
||||
f"encoding_stuck: status=encoding for {minutes} min without update (updated_at={updated_at.isoformat()})"
|
||||
)
|
||||
|
||||
return issues
|
||||
|
||||
|
||||
|
||||
@@ -115,6 +115,7 @@ class TestAudioSearchYouTubeFlow:
|
||||
async def test_torrent_download_does_not_use_youtube_service(self, mock_youtube_service, mock_services):
|
||||
"""
|
||||
When selecting a torrent result (RED/OPS), should NOT use YouTubeDownloadService.
|
||||
Should use FlacfetchClient directly instead.
|
||||
"""
|
||||
mock_job = mock_services['job_manager'].get_job.return_value
|
||||
mock_job.status = "awaiting_audio_selection"
|
||||
@@ -132,16 +133,22 @@ class TestAudioSearchYouTubeFlow:
|
||||
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
|
||||
# Mock audio_search_service for torrent download
|
||||
mock_audio_search_service = MagicMock()
|
||||
mock_audio_search_service.is_remote_enabled = MagicMock(return_value=True)
|
||||
mock_result = MagicMock()
|
||||
mock_result.filepath = "gs://bucket/uploads/test/audio/test.flac"
|
||||
mock_audio_search_service.download_by_id = MagicMock(return_value=mock_result)
|
||||
|
||||
# Mock FlacfetchClient for direct async download
|
||||
mock_flacfetch = MagicMock()
|
||||
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-test-123")
|
||||
mock_flacfetch.wait_for_download = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"gcs_path": "gs://bucket/uploads/test/audio/test.flac",
|
||||
})
|
||||
|
||||
with patch(
|
||||
'backend.api.routes.audio_search.get_youtube_download_service',
|
||||
return_value=mock_youtube_service
|
||||
), patch(
|
||||
'backend.api.routes.audio_search.get_flacfetch_client',
|
||||
return_value=mock_flacfetch
|
||||
), patch(
|
||||
'backend.api.routes.audio_search.job_manager',
|
||||
mock_services['job_manager']
|
||||
@@ -152,7 +159,6 @@ class TestAudioSearchYouTubeFlow:
|
||||
'backend.api.routes.audio_search.worker_service',
|
||||
mock_services['worker_service']
|
||||
):
|
||||
# Call the download function (now runs as background task, returns None)
|
||||
await _download_audio_and_trigger_workers(
|
||||
job_id="test_job_123",
|
||||
selection_index=0,
|
||||
@@ -162,8 +168,8 @@ class TestAudioSearchYouTubeFlow:
|
||||
# YouTubeDownloadService should NOT be called for torrent
|
||||
mock_youtube_service.download_by_id.assert_not_called()
|
||||
|
||||
# audio_search_service.download_by_id should be called instead
|
||||
mock_audio_search_service.download_by_id.assert_called_once()
|
||||
# FlacfetchClient.download_by_id should be called directly
|
||||
mock_flacfetch.download_by_id.assert_called_once()
|
||||
|
||||
|
||||
class TestDirectUrlSubmissionFlow:
|
||||
|
||||
@@ -1173,58 +1173,60 @@ class TestAudioSearchApiRouteDownload:
|
||||
|
||||
def test_remote_download_passes_gcs_path(self, mock_job_manager, mock_storage_service, mock_worker_service):
|
||||
"""
|
||||
Test that remote torrent downloads include GCS path for direct upload.
|
||||
Test that remote torrent downloads use FlacfetchClient directly with GCS path.
|
||||
|
||||
This was the bug: we were calling download() without gcs_path for
|
||||
torrent sources, causing flacfetch VM to return a local path that
|
||||
Cloud Run couldn't access.
|
||||
The route bypasses audio_search_service and calls flacfetch_client.download_by_id()
|
||||
directly to avoid event loop blocking.
|
||||
"""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
import asyncio
|
||||
|
||||
# Setup mock job with RED search result
|
||||
# Setup mock job with RED search result (includes source_id for download_by_id path)
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Unwanted',
|
||||
'artist': 'Avril Lavigne',
|
||||
'provider': 'RED', # Torrent source
|
||||
'provider': 'RED',
|
||||
'quality': 'FLAC 16bit CD',
|
||||
'source_id': 'torrent123',
|
||||
'target_file': 'Unwanted.flac',
|
||||
'url': '',
|
||||
}]
|
||||
}
|
||||
mock_job.audio_search_artist = 'Avril Lavigne'
|
||||
mock_job.audio_search_title = 'Unwanted'
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
# Create mock audio search service with remote client
|
||||
mock_audio_service = Mock()
|
||||
mock_audio_service.is_remote_enabled.return_value = True
|
||||
|
||||
# Mock download to return GCS path
|
||||
mock_download_result = Mock()
|
||||
mock_download_result.filepath = "gs://bucket/uploads/job123/audio/Avril Lavigne - Unwanted.flac"
|
||||
mock_audio_service.download.return_value = mock_download_result
|
||||
# Mock FlacfetchClient
|
||||
mock_flacfetch = Mock()
|
||||
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-123")
|
||||
mock_flacfetch.wait_for_download = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"gcs_path": "gs://bucket/uploads/job123/audio/Avril Lavigne - Unwanted.flac",
|
||||
})
|
||||
|
||||
# Run the async function
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job123",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job123",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# CRITICAL: Verify download was called with gcs_path for remote torrent source
|
||||
mock_audio_service.download.assert_called_once()
|
||||
call_kwargs = mock_audio_service.download.call_args.kwargs
|
||||
|
||||
# The gcs_path should be set for remote torrent downloads
|
||||
assert 'gcs_path' in call_kwargs
|
||||
# CRITICAL: Verify FlacfetchClient.download_by_id was called with gcs_path
|
||||
mock_flacfetch.download_by_id.assert_called_once()
|
||||
call_kwargs = mock_flacfetch.download_by_id.call_args.kwargs
|
||||
assert call_kwargs['gcs_path'] == "uploads/job123/audio/"
|
||||
assert call_kwargs['source_name'] == 'RED'
|
||||
assert call_kwargs['source_id'] == 'torrent123'
|
||||
|
||||
def test_youtube_remote_download_uses_youtube_service(self, mock_job_manager, mock_storage_service, mock_worker_service):
|
||||
"""
|
||||
@@ -1343,7 +1345,7 @@ class TestAudioSearchApiRouteDownload:
|
||||
mock_youtube_service.download_by_id.assert_called_once()
|
||||
|
||||
def test_handles_gcs_path_response_correctly(self, mock_job_manager, mock_storage_service, mock_worker_service):
|
||||
"""Test that GCS path responses are parsed correctly."""
|
||||
"""Test that GCS path responses from FlacfetchClient are parsed correctly."""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
import asyncio
|
||||
|
||||
@@ -1355,31 +1357,35 @@ class TestAudioSearchApiRouteDownload:
|
||||
'artist': 'Test Artist',
|
||||
'provider': 'RED',
|
||||
'quality': 'FLAC',
|
||||
'source_id': 'torrent789',
|
||||
'target_file': 'test.flac',
|
||||
'url': '',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
# Create mock audio search service
|
||||
mock_audio_service = Mock()
|
||||
mock_audio_service.is_remote_enabled.return_value = True
|
||||
|
||||
# Mock download to return full GCS path
|
||||
mock_download_result = Mock()
|
||||
mock_download_result.filepath = "gs://karaoke-gen-bucket/uploads/job789/audio/test.flac"
|
||||
mock_audio_service.download.return_value = mock_download_result
|
||||
# Mock FlacfetchClient returning full GCS path
|
||||
mock_flacfetch = Mock()
|
||||
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-789")
|
||||
mock_flacfetch.wait_for_download = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"gcs_path": "gs://karaoke-gen-bucket/uploads/job789/audio/test.flac",
|
||||
})
|
||||
|
||||
# Run the async function
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job789",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job789",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# Verify job was updated with correct GCS path (without gs://bucket/ prefix)
|
||||
update_calls = mock_job_manager.update_job.call_args_list
|
||||
@@ -1398,9 +1404,9 @@ class TestAudioSearchApiRouteDownload:
|
||||
|
||||
def test_torrent_download_requires_remote(self, mock_job_manager, mock_storage_service):
|
||||
"""
|
||||
Test that torrent sources (RED/OPS) require remote flacfetch.
|
||||
Test that torrent sources (RED/OPS) require remote flacfetch client.
|
||||
|
||||
When running as a background task, the error is caught and the job is failed.
|
||||
When get_flacfetch_client() returns None, the job should be failed.
|
||||
"""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
import asyncio
|
||||
@@ -1417,22 +1423,21 @@ class TestAudioSearchApiRouteDownload:
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
# Create mock audio search service WITHOUT remote client
|
||||
mock_audio_service = Mock()
|
||||
mock_audio_service.is_remote_enabled.return_value = False
|
||||
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
# The background task catches exceptions and fails the job
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_no_remote",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
# No flacfetch client configured
|
||||
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=None):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_no_remote",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# Verify the job was failed with an appropriate error message
|
||||
mock_job_manager.fail_job.assert_called_once()
|
||||
@@ -1564,27 +1569,35 @@ class TestAudioSearchApiRouteDownload:
|
||||
'artist': 'Artist',
|
||||
'provider': 'RED',
|
||||
'quality': 'FLAC',
|
||||
'source_id': 'torrent_w',
|
||||
'target_file': 'test.flac',
|
||||
'url': '',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_audio_service = Mock()
|
||||
mock_audio_service.is_remote_enabled.return_value = True
|
||||
mock_download_result = Mock()
|
||||
mock_download_result.filepath = "gs://bucket/uploads/job_w/audio/test.flac"
|
||||
mock_audio_service.download.return_value = mock_download_result
|
||||
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_w",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
# Mock FlacfetchClient
|
||||
mock_flacfetch = Mock()
|
||||
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-w")
|
||||
mock_flacfetch.wait_for_download = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"gcs_path": "gs://bucket/uploads/job_w/audio/test.flac",
|
||||
})
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_w",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# Both workers should be triggered
|
||||
mock_worker_service.trigger_audio_worker.assert_called_once_with("job_w")
|
||||
@@ -1609,26 +1622,32 @@ class TestAudioSearchApiRouteDownload:
|
||||
'artist': 'Artist',
|
||||
'provider': 'RED',
|
||||
'quality': 'FLAC',
|
||||
'source_id': 'torrent_err',
|
||||
'target_file': 'test.flac',
|
||||
'url': '',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_audio_service = Mock()
|
||||
mock_audio_service.is_remote_enabled.return_value = True
|
||||
mock_audio_service.download.side_effect = RuntimeError("Unexpected connection error")
|
||||
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
# Should not raise - background tasks catch all exceptions
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_err",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
# Mock FlacfetchClient that raises an error
|
||||
mock_flacfetch = Mock()
|
||||
mock_flacfetch.download_by_id = AsyncMock(side_effect=RuntimeError("Unexpected connection error"))
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
# Should not raise - background tasks catch all exceptions
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_err",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# Job should be failed with error message
|
||||
mock_job_manager.fail_job.assert_called_once()
|
||||
@@ -1636,3 +1655,502 @@ class TestAudioSearchApiRouteDownload:
|
||||
assert fail_args.args[0] == "job_err"
|
||||
assert "Unexpected connection error" in fail_args.args[1]
|
||||
|
||||
|
||||
class TestAsyncEventLoopFixes:
|
||||
"""
|
||||
Tests for the async event loop blocking fixes.
|
||||
|
||||
Verifies that:
|
||||
- Background tasks use FlacfetchClient async methods directly (RED/OPS/Spotify)
|
||||
- Background tasks use asyncio.to_thread for generic downloads
|
||||
- Search endpoint uses search_async instead of sync search
|
||||
- InsufficientCreditsError propagates as 402, not 500
|
||||
- FlacfetchServiceError is handled in background tasks
|
||||
"""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job_manager(self):
|
||||
with patch('backend.api.routes.audio_search.job_manager') as mock:
|
||||
yield mock
|
||||
|
||||
@pytest.fixture
|
||||
def mock_storage_service(self):
|
||||
with patch('backend.api.routes.audio_search.storage_service') as mock:
|
||||
yield mock
|
||||
|
||||
@pytest.fixture
|
||||
def mock_worker_service(self):
|
||||
with patch('backend.api.routes.audio_search.get_worker_service') as mock:
|
||||
worker = Mock()
|
||||
worker.trigger_audio_worker = AsyncMock()
|
||||
worker.trigger_lyrics_worker = AsyncMock()
|
||||
mock.return_value = worker
|
||||
yield worker
|
||||
|
||||
def test_spotify_download_uses_flacfetch_client_directly(
|
||||
self, mock_job_manager, mock_storage_service, mock_worker_service
|
||||
):
|
||||
"""Spotify downloads should use FlacfetchClient.download_by_id() directly."""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
import asyncio
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Blinding Lights',
|
||||
'artist': 'The Weeknd',
|
||||
'provider': 'Spotify',
|
||||
'quality': 'OGG 320kbps',
|
||||
'source_id': 'spotify:track:0VjIjW4GlUZAMYd2vXMi3b',
|
||||
'url': 'https://open.spotify.com/track/0VjIjW4GlUZAMYd2vXMi3b',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_audio_service = Mock()
|
||||
|
||||
mock_flacfetch = Mock()
|
||||
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-spotify-1")
|
||||
mock_flacfetch.wait_for_download = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"gcs_path": "gs://bucket/uploads/job_sp/audio/The Weeknd - Blinding Lights.ogg",
|
||||
})
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_sp",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# Verify FlacfetchClient was used directly (not audio_search_service)
|
||||
mock_flacfetch.download_by_id.assert_called_once()
|
||||
call_kwargs = mock_flacfetch.download_by_id.call_args.kwargs
|
||||
assert call_kwargs['source_name'] == 'Spotify'
|
||||
assert call_kwargs['source_id'] == 'spotify:track:0VjIjW4GlUZAMYd2vXMi3b'
|
||||
assert call_kwargs['gcs_path'] == 'uploads/job_sp/audio/'
|
||||
|
||||
mock_flacfetch.wait_for_download.assert_called_once()
|
||||
|
||||
# audio_search_service.download_by_id should NOT be called
|
||||
mock_audio_service.download_by_id.assert_not_called()
|
||||
|
||||
def test_spotify_download_requires_flacfetch_client(self, mock_job_manager, mock_storage_service):
|
||||
"""Spotify download should fail job when FlacfetchClient is not configured."""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
import asyncio
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Test',
|
||||
'artist': 'Test',
|
||||
'provider': 'Spotify',
|
||||
'quality': 'OGG',
|
||||
'source_id': 'spotify:track:abc',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_audio_service = Mock()
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=None):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_sp_err",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
mock_job_manager.fail_job.assert_called_once()
|
||||
assert "flacfetch" in mock_job_manager.fail_job.call_args.args[1].lower()
|
||||
|
||||
def test_generic_download_uses_asyncio_to_thread(self, mock_job_manager, mock_storage_service, mock_worker_service):
|
||||
"""Generic/unknown source downloads should use asyncio.to_thread to avoid blocking."""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
import asyncio
|
||||
import tempfile
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Test Song',
|
||||
'artist': 'Unknown Artist',
|
||||
'provider': 'SomeNewSource',
|
||||
'quality': 'MP3',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_audio_service = Mock()
|
||||
|
||||
# Create a temporary file to simulate a downloaded file
|
||||
tmp = tempfile.NamedTemporaryFile(suffix='.mp3', delete=False)
|
||||
tmp.write(b'fake audio data')
|
||||
tmp.close()
|
||||
|
||||
mock_download_result = Mock()
|
||||
mock_download_result.filepath = tmp.name
|
||||
|
||||
mock_audio_service.download.return_value = mock_download_result
|
||||
|
||||
with patch('backend.api.routes.audio_search.asyncio') as mock_asyncio:
|
||||
# Make to_thread return a coroutine that returns the mock result
|
||||
mock_asyncio.to_thread = AsyncMock(return_value=mock_download_result)
|
||||
mock_asyncio.gather = AsyncMock()
|
||||
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_generic",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# Verify asyncio.to_thread was called (not direct sync call)
|
||||
mock_asyncio.to_thread.assert_called_once()
|
||||
|
||||
# Cleanup
|
||||
import os
|
||||
try:
|
||||
os.unlink(tmp.name)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def test_red_download_without_source_id_uses_search_download(
|
||||
self, mock_job_manager, mock_storage_service, mock_worker_service
|
||||
):
|
||||
"""RED download without source_id should use flacfetch_client.download() with search_id."""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
import asyncio
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Test',
|
||||
'artist': 'Artist',
|
||||
'provider': 'RED',
|
||||
'quality': 'FLAC',
|
||||
# No source_id — triggers the search-based download path
|
||||
}],
|
||||
'remote_search_id': 'search-abc-123',
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_audio_service = Mock()
|
||||
|
||||
mock_flacfetch = Mock()
|
||||
mock_flacfetch.download = AsyncMock(return_value="dl-search-1")
|
||||
mock_flacfetch.wait_for_download = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"gcs_path": "gs://bucket/uploads/job_nosrc/audio/test.flac",
|
||||
})
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_nosrc",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# Should use flacfetch_client.download() (not download_by_id)
|
||||
mock_flacfetch.download.assert_called_once()
|
||||
call_kwargs = mock_flacfetch.download.call_args.kwargs
|
||||
assert call_kwargs['search_id'] == 'search-abc-123'
|
||||
assert call_kwargs['result_index'] == 0
|
||||
assert call_kwargs['gcs_path'] == 'uploads/job_nosrc/audio/'
|
||||
|
||||
def test_flacfetch_service_error_handled_in_background_task(
|
||||
self, mock_job_manager, mock_storage_service
|
||||
):
|
||||
"""FlacfetchServiceError should be caught and job should be failed."""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
from backend.services.flacfetch_client import FlacfetchServiceError
|
||||
import asyncio
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Test',
|
||||
'artist': 'Artist',
|
||||
'provider': 'OPS',
|
||||
'quality': 'FLAC',
|
||||
'source_id': 'ops123',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_audio_service = Mock()
|
||||
|
||||
mock_flacfetch = Mock()
|
||||
mock_flacfetch.download_by_id = AsyncMock(
|
||||
side_effect=FlacfetchServiceError("Connection refused")
|
||||
)
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_fserr",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
mock_job_manager.fail_job.assert_called_once()
|
||||
assert "Connection refused" in mock_job_manager.fail_job.call_args.args[1]
|
||||
|
||||
def test_wait_for_download_no_filepath_fails_job(
|
||||
self, mock_job_manager, mock_storage_service
|
||||
):
|
||||
"""If wait_for_download returns no filepath, job should be failed."""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
import asyncio
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Test',
|
||||
'artist': 'Artist',
|
||||
'provider': 'RED',
|
||||
'quality': 'FLAC',
|
||||
'source_id': 'torrent_nofp',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_audio_service = Mock()
|
||||
|
||||
# wait_for_download returns status without gcs_path or output_path
|
||||
mock_flacfetch = Mock()
|
||||
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-nofp")
|
||||
mock_flacfetch.wait_for_download = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
# No gcs_path or output_path
|
||||
})
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_nofp",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
mock_job_manager.fail_job.assert_called_once()
|
||||
assert "no file path" in mock_job_manager.fail_job.call_args.args[1].lower()
|
||||
|
||||
def test_spotify_wait_for_download_no_filepath_fails_job(
|
||||
self, mock_job_manager, mock_storage_service
|
||||
):
|
||||
"""Spotify: if wait_for_download returns no filepath, job should be failed."""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
import asyncio
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Test',
|
||||
'artist': 'Artist',
|
||||
'provider': 'Spotify',
|
||||
'quality': 'OGG',
|
||||
'source_id': 'spotify:track:nofp',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_audio_service = Mock()
|
||||
|
||||
mock_flacfetch = Mock()
|
||||
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-sp-nofp")
|
||||
mock_flacfetch.wait_for_download = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
})
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_sp_nofp",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
mock_job_manager.fail_job.assert_called_once()
|
||||
assert "no file path" in mock_job_manager.fail_job.call_args.args[1].lower()
|
||||
|
||||
def test_youtube_download_error_fails_job(
|
||||
self, mock_job_manager, mock_storage_service
|
||||
):
|
||||
"""YouTubeDownloadError should be caught and job failed."""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
from backend.services.youtube_download_service import YouTubeDownloadError
|
||||
import asyncio
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Deleted Video',
|
||||
'artist': 'Unknown',
|
||||
'provider': 'YouTube',
|
||||
'quality': 'Opus',
|
||||
'source_id': 'deleted123',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_audio_service = Mock()
|
||||
|
||||
mock_youtube_service = Mock()
|
||||
mock_youtube_service.download_by_id = AsyncMock(
|
||||
side_effect=YouTubeDownloadError("Video unavailable")
|
||||
)
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_youtube_download_service', return_value=mock_youtube_service):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_yt_err",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
mock_job_manager.fail_job.assert_called_once()
|
||||
assert "Video unavailable" in mock_job_manager.fail_job.call_args.args[1]
|
||||
|
||||
def test_youtube_no_video_id_fails_job(
|
||||
self, mock_job_manager, mock_storage_service
|
||||
):
|
||||
"""YouTube download with no source_id and no extractable video ID should fail."""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
import asyncio
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Bad Link',
|
||||
'artist': 'Unknown',
|
||||
'provider': 'YouTube',
|
||||
'quality': 'Opus',
|
||||
# No source_id
|
||||
'url': 'https://example.com/not-youtube',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_audio_service = Mock()
|
||||
|
||||
mock_youtube_service = Mock()
|
||||
mock_youtube_service._extract_video_id = Mock(return_value=None)
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_youtube_download_service', return_value=mock_youtube_service):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_yt_noid",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
mock_job_manager.fail_job.assert_called_once()
|
||||
assert "video ID" in mock_job_manager.fail_job.call_args.args[1] or \
|
||||
"No video" in mock_job_manager.fail_job.call_args.args[1]
|
||||
|
||||
|
||||
class TestSearchAsyncUsage:
|
||||
"""Tests that the search endpoint uses search_async instead of sync search."""
|
||||
|
||||
def test_search_async_uses_get_running_loop(self):
|
||||
"""search_async should use asyncio.get_running_loop() (not deprecated get_event_loop)."""
|
||||
import asyncio
|
||||
import inspect
|
||||
|
||||
source = inspect.getsource(AudioSearchService.search_async)
|
||||
assert 'get_running_loop' in source
|
||||
assert 'get_event_loop' not in source
|
||||
|
||||
def test_download_async_uses_get_running_loop(self):
|
||||
"""download_async should use asyncio.get_running_loop()."""
|
||||
import inspect
|
||||
|
||||
source = inspect.getsource(AudioSearchService.download_async)
|
||||
assert 'get_running_loop' in source
|
||||
assert 'get_event_loop' not in source
|
||||
|
||||
def test_download_by_id_async_uses_get_running_loop(self):
|
||||
"""download_by_id_async should use asyncio.get_running_loop()."""
|
||||
import inspect
|
||||
|
||||
source = inspect.getsource(AudioSearchService.download_by_id_async)
|
||||
assert 'get_running_loop' in source
|
||||
assert 'get_event_loop' not in source
|
||||
|
||||
def test_search_endpoint_calls_search_async(self):
|
||||
"""Verify the search endpoint source calls search_async, not sync search."""
|
||||
import inspect
|
||||
from backend.api.routes.audio_search import search_audio
|
||||
|
||||
source = inspect.getsource(search_audio)
|
||||
assert 'search_async' in source
|
||||
# Should NOT have a bare .search( call (which is sync)
|
||||
# But it may have search_async( which contains "search" — so check specifically
|
||||
# that search_async is used and not audio_search_service.search(
|
||||
assert 'await audio_search_service.search_async(' in source
|
||||
|
||||
|
||||
class TestInsufficientCreditsErrorPropagation:
|
||||
"""Test that InsufficientCreditsError propagates correctly as 402."""
|
||||
|
||||
def test_exception_handler_uses_isinstance(self):
|
||||
"""
|
||||
Verify the exception handler uses isinstance() for InsufficientCreditsError.
|
||||
|
||||
This is robust against class identity issues from module reloading.
|
||||
"""
|
||||
import inspect
|
||||
from backend.api.routes.audio_search import search_audio
|
||||
|
||||
source = inspect.getsource(search_audio)
|
||||
assert 'isinstance(e, (InsufficientCreditsError, RateLimitExceededError))' in source
|
||||
|
||||
@@ -0,0 +1,590 @@
|
||||
"""
|
||||
Tests for BrandCodeService - atomic brand code allocation via Firestore counters.
|
||||
|
||||
Tests cover:
|
||||
- Sequential allocation returns unique codes
|
||||
- Recycled numbers are reused (smallest first)
|
||||
- One-time initialization from Dropbox scan
|
||||
- Both NOMAD and NOMADNP prefixes work independently
|
||||
- Recycle then allocate round-trip
|
||||
- parse_brand_code utility
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock, MagicMock, patch
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import sys
|
||||
sys.modules.setdefault('google.cloud.firestore', MagicMock())
|
||||
sys.modules.setdefault('google.cloud.storage', MagicMock())
|
||||
|
||||
|
||||
def _make_doc_snapshot(exists, data=None):
|
||||
"""Create a mock Firestore document snapshot."""
|
||||
doc = Mock()
|
||||
doc.exists = exists
|
||||
if data:
|
||||
doc.to_dict.return_value = data
|
||||
return doc
|
||||
|
||||
|
||||
def _setup_service_and_mocks(mock_db, doc_snapshot):
|
||||
"""Common setup: create service with fake transactional decorator."""
|
||||
mock_doc_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_doc_ref
|
||||
mock_doc_ref.get.return_value = doc_snapshot
|
||||
|
||||
mock_transaction = Mock()
|
||||
mock_db.transaction.return_value = mock_transaction
|
||||
|
||||
return mock_doc_ref, mock_transaction
|
||||
|
||||
|
||||
class TestBrandCodeServiceAllocate:
|
||||
"""Test allocate_brand_code method."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
return MagicMock()
|
||||
|
||||
def test_allocate_sequential_number(self, mock_db):
|
||||
"""Test allocation returns next sequential number when no recycled numbers."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [],
|
||||
})
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc.allocate_brand_code("NOMAD", "/Karaoke/Tracks-Organized")
|
||||
|
||||
assert result == "NOMAD-1264"
|
||||
# Transaction.update should have been called to increment next_number
|
||||
mock_transaction.update.assert_called_once()
|
||||
update_args = mock_transaction.update.call_args[0]
|
||||
assert update_args[0] is mock_doc_ref # first arg is doc_ref
|
||||
assert update_args[1]["next_number"] == 1265
|
||||
|
||||
def test_allocate_uses_recycled_number(self, mock_db):
|
||||
"""Test allocation pops smallest recycled number first."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [1250, 1230, 1245],
|
||||
})
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc.allocate_brand_code("NOMAD", "/path")
|
||||
|
||||
assert result == "NOMAD-1230"
|
||||
# Verify recycled list was updated (1230 removed, sorted remainder)
|
||||
update_args = mock_transaction.update.call_args[0][1]
|
||||
assert update_args["recycled"] == [1245, 1250]
|
||||
|
||||
def test_allocate_initializes_from_dropbox_when_no_counter(self, mock_db):
|
||||
"""Test first allocation scans Dropbox and creates counter doc."""
|
||||
doc_snapshot = _make_doc_snapshot(False)
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
|
||||
with patch.object(svc, '_get_initial_next_number', return_value=1264):
|
||||
result = svc.allocate_brand_code("NOMAD", "/Karaoke/Tracks-Organized")
|
||||
|
||||
assert result == "NOMAD-1264"
|
||||
# Verify counter doc was created via transaction.set
|
||||
mock_transaction.set.assert_called_once()
|
||||
set_args = mock_transaction.set.call_args[0]
|
||||
assert set_args[0] is mock_doc_ref
|
||||
assert set_args[1]["prefix"] == "NOMAD"
|
||||
assert set_args[1]["next_number"] == 1265
|
||||
assert set_args[1]["recycled"] == []
|
||||
|
||||
def test_allocate_nomadnp_prefix(self, mock_db):
|
||||
"""Test NOMADNP prefix works independently."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMADNP",
|
||||
"next_number": 13,
|
||||
"recycled": [],
|
||||
})
|
||||
_setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc.allocate_brand_code("NOMADNP", "/Karaoke/NP")
|
||||
|
||||
assert result == "NOMADNP-0013"
|
||||
mock_db.collection.assert_called_with("brand_code_counters")
|
||||
mock_db.collection.return_value.document.assert_called_with("NOMADNP")
|
||||
|
||||
def test_allocate_formats_with_leading_zeros(self, mock_db):
|
||||
"""Test brand codes are zero-padded to 4 digits."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMADNP",
|
||||
"next_number": 5,
|
||||
"recycled": [],
|
||||
})
|
||||
_setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc.allocate_brand_code("NOMADNP", "/path")
|
||||
|
||||
assert result == "NOMADNP-0005"
|
||||
|
||||
|
||||
class TestBrandCodeServiceRecycle:
|
||||
"""Test recycle_brand_code method."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
return MagicMock()
|
||||
|
||||
def test_recycle_adds_number_to_pool(self, mock_db):
|
||||
"""Test recycling adds number to the recycled list."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [1250],
|
||||
})
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
svc.recycle_brand_code("NOMAD", 1230)
|
||||
|
||||
update_args = mock_transaction.update.call_args[0][1]
|
||||
assert 1230 in update_args["recycled"]
|
||||
assert 1250 in update_args["recycled"]
|
||||
|
||||
def test_recycle_rejects_number_at_or_above_next(self, mock_db):
|
||||
"""Test recycling a number >= next_number is rejected."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [],
|
||||
})
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
# Number equal to next_number — hasn't been allocated yet
|
||||
svc.recycle_brand_code("NOMAD", 1264)
|
||||
|
||||
mock_transaction.update.assert_not_called()
|
||||
|
||||
def test_recycle_rejects_zero_or_negative(self, mock_db):
|
||||
"""Test recycling zero or negative numbers is rejected."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [],
|
||||
})
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
svc.recycle_brand_code("NOMAD", 0)
|
||||
|
||||
mock_transaction.update.assert_not_called()
|
||||
|
||||
def test_recycle_skips_duplicate(self, mock_db):
|
||||
"""Test recycling a number already in the pool doesn't duplicate it."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [1250],
|
||||
})
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
svc.recycle_brand_code("NOMAD", 1250)
|
||||
|
||||
mock_transaction.update.assert_not_called()
|
||||
|
||||
def test_recycle_no_counter_doc_logs_warning(self, mock_db):
|
||||
"""Test recycling when counter doc doesn't exist logs warning and returns."""
|
||||
doc_snapshot = _make_doc_snapshot(False)
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
svc.recycle_brand_code("NOMAD", 1230)
|
||||
|
||||
mock_transaction.update.assert_not_called()
|
||||
mock_transaction.set.assert_not_called()
|
||||
|
||||
|
||||
class TestBrandCodeServiceRecycleRoundTrip:
|
||||
"""Test recycle-then-allocate round trip."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
return MagicMock()
|
||||
|
||||
def test_recycle_then_allocate_reuses_number(self, mock_db):
|
||||
"""Test that a recycled number is returned on next allocation."""
|
||||
mock_doc_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_doc_ref
|
||||
mock_transaction = Mock()
|
||||
mock_db.transaction.return_value = mock_transaction
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
|
||||
# Step 1: Recycle number 1230
|
||||
mock_doc_ref.get.return_value = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [],
|
||||
})
|
||||
svc.recycle_brand_code("NOMAD", 1230)
|
||||
|
||||
# Step 2: Allocate — should get recycled 1230
|
||||
mock_doc_ref.get.return_value = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [1230],
|
||||
})
|
||||
result = svc.allocate_brand_code("NOMAD", "/path")
|
||||
|
||||
assert result == "NOMAD-1230"
|
||||
|
||||
|
||||
class TestInitializeFromDropbox:
|
||||
"""Test _get_initial_next_number."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
return MagicMock()
|
||||
|
||||
def test_init_from_dropbox_finds_max(self, mock_db):
|
||||
"""Test initialization finds the max existing number and adds 1."""
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.list_folders.return_value = [
|
||||
"NOMAD-1260 - Artist A - Song A",
|
||||
"NOMAD-1261 - Artist B - Song B",
|
||||
"NOMAD-1263 - Artist C - Song C",
|
||||
"Some Other Folder",
|
||||
]
|
||||
|
||||
with patch('backend.services.brand_code_service.settings') as mock_settings, \
|
||||
patch('backend.services.dropbox_service.get_dropbox_service', return_value=mock_dropbox):
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc._get_initial_next_number("NOMAD", "/Karaoke/Tracks-Organized")
|
||||
|
||||
assert result == 1264 # max(1260, 1261, 1263) + 1
|
||||
|
||||
def test_init_from_dropbox_no_existing(self, mock_db):
|
||||
"""Test initialization returns 1 when no existing codes found."""
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.list_folders.return_value = ["Some Random Folder"]
|
||||
|
||||
with patch('backend.services.brand_code_service.settings') as mock_settings, \
|
||||
patch('backend.services.dropbox_service.get_dropbox_service', return_value=mock_dropbox):
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc._get_initial_next_number("NOMAD", "/path")
|
||||
|
||||
assert result == 1
|
||||
|
||||
def test_init_from_dropbox_not_configured(self, mock_db):
|
||||
"""Test initialization returns 1 when Dropbox not configured."""
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = False
|
||||
|
||||
with patch('backend.services.brand_code_service.settings') as mock_settings, \
|
||||
patch('backend.services.dropbox_service.get_dropbox_service', return_value=mock_dropbox):
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc._get_initial_next_number("NOMAD", "/path")
|
||||
|
||||
assert result == 1
|
||||
|
||||
def test_init_nomadnp_prefix_independent(self, mock_db):
|
||||
"""Test NOMADNP initialization only finds NOMADNP codes, not NOMAD."""
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.list_folders.return_value = [
|
||||
"NOMADNP-0010 - Artist A",
|
||||
"NOMADNP-0012 - Artist B",
|
||||
"NOMAD-1263 - Artist C", # Should NOT match NOMADNP prefix
|
||||
]
|
||||
|
||||
with patch('backend.services.brand_code_service.settings') as mock_settings, \
|
||||
patch('backend.services.dropbox_service.get_dropbox_service', return_value=mock_dropbox):
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc._get_initial_next_number("NOMADNP", "/Karaoke/NP")
|
||||
|
||||
assert result == 13 # max(10, 12) + 1
|
||||
|
||||
|
||||
class TestParseBrandCode:
|
||||
"""Test parse_brand_code static method."""
|
||||
|
||||
def test_parse_nomad_code(self):
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
prefix, number = BrandCodeService.parse_brand_code("NOMAD-1234")
|
||||
assert prefix == "NOMAD"
|
||||
assert number == 1234
|
||||
|
||||
def test_parse_nomadnp_code(self):
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
prefix, number = BrandCodeService.parse_brand_code("NOMADNP-0012")
|
||||
assert prefix == "NOMADNP"
|
||||
assert number == 12
|
||||
|
||||
def test_parse_leading_zeros(self):
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
prefix, number = BrandCodeService.parse_brand_code("NOMAD-0001")
|
||||
assert prefix == "NOMAD"
|
||||
assert number == 1
|
||||
|
||||
def test_parse_invalid_format_raises(self):
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
with pytest.raises(ValueError, match="Invalid brand code format"):
|
||||
BrandCodeService.parse_brand_code("invalid")
|
||||
|
||||
def test_parse_no_dash_raises(self):
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
with pytest.raises(ValueError, match="Invalid brand code format"):
|
||||
BrandCodeService.parse_brand_code("NOMAD1234")
|
||||
|
||||
def test_parse_lowercase_raises(self):
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
with pytest.raises(ValueError, match="Invalid brand code format"):
|
||||
BrandCodeService.parse_brand_code("nomad-1234")
|
||||
|
||||
|
||||
class TestCleanupDistributionRecycling:
|
||||
"""Test that cleanup_distribution endpoint recycles brand codes correctly."""
|
||||
|
||||
def test_parse_and_recycle_nomad_brand_code(self):
|
||||
"""Test that a NOMAD brand code is correctly parsed and recycled."""
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
|
||||
prefix, number = BrandCodeService.parse_brand_code("NOMAD-1234")
|
||||
assert prefix == "NOMAD"
|
||||
assert number == 1234
|
||||
|
||||
def test_parse_and_recycle_nomadnp_brand_code(self):
|
||||
"""Test that a NOMADNP brand code is correctly parsed and recycled."""
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
|
||||
prefix, number = BrandCodeService.parse_brand_code("NOMADNP-0012")
|
||||
assert prefix == "NOMADNP"
|
||||
assert number == 12
|
||||
|
||||
def test_recycle_called_after_successful_dropbox_delete(self):
|
||||
"""Test the integration pattern: parse brand code, then recycle the number."""
|
||||
mock_db = MagicMock()
|
||||
mock_doc_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_doc_ref
|
||||
mock_transaction = Mock()
|
||||
mock_db.transaction.return_value = mock_transaction
|
||||
|
||||
mock_doc_ref.get.return_value = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [],
|
||||
})
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
|
||||
# Simulate what cleanup_distribution does:
|
||||
# 1. Parse the brand code
|
||||
brand_code = "NOMAD-1234"
|
||||
prefix, number = BrandCodeService.parse_brand_code(brand_code)
|
||||
# 2. Recycle it
|
||||
svc.recycle_brand_code(prefix, number)
|
||||
|
||||
# Verify transaction.update was called to add 1234 to recycled pool
|
||||
mock_transaction.update.assert_called_once()
|
||||
update_args = mock_transaction.update.call_args[0][1]
|
||||
assert 1234 in update_args["recycled"]
|
||||
|
||||
def test_recycle_failure_does_not_raise(self):
|
||||
"""Test that recycling a brand code with no counter doc doesn't raise."""
|
||||
mock_db = MagicMock()
|
||||
mock_doc_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_doc_ref
|
||||
mock_transaction = Mock()
|
||||
mock_db.transaction.return_value = mock_transaction
|
||||
|
||||
mock_doc_ref.get.return_value = _make_doc_snapshot(False)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
|
||||
# Should not raise — cleanup should be resilient
|
||||
svc.recycle_brand_code("NOMAD", 1234)
|
||||
|
||||
mock_transaction.update.assert_not_called()
|
||||
|
||||
|
||||
class TestGetBrandCodeService:
|
||||
"""Test singleton getter."""
|
||||
|
||||
def test_returns_same_instance(self):
|
||||
"""Test get_brand_code_service returns singleton."""
|
||||
with patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
import backend.services.brand_code_service as module
|
||||
# Reset singleton
|
||||
module._brand_code_service = None
|
||||
|
||||
svc1 = module.get_brand_code_service()
|
||||
svc2 = module.get_brand_code_service()
|
||||
assert svc1 is svc2
|
||||
|
||||
# Clean up
|
||||
module._brand_code_service = None
|
||||
@@ -0,0 +1,381 @@
|
||||
"""
|
||||
Tests for the cleanup-distribution endpoint in jobs.py.
|
||||
|
||||
Verifies:
|
||||
- GDrive cleanup uses tracked file IDs from state_data when available (fast path)
|
||||
- GDrive cleanup falls back to brand_code search when gdrive_files is empty (fallback path)
|
||||
- Brand code is recycled ONLY after both Dropbox AND GDrive are confirmed clean
|
||||
- Brand code is NOT recycled when GDrive cleanup fails or is skipped
|
||||
- Endpoint returns correct status for each distribution service
|
||||
|
||||
The cleanup-distribution endpoint is used by the E2E happy-path test (Step 12)
|
||||
to remove test job files from YouTube, Dropbox, and Google Drive after the test.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch, MagicMock
|
||||
from fastapi.testclient import TestClient
|
||||
from fastapi import FastAPI
|
||||
from datetime import datetime, UTC
|
||||
|
||||
from backend.api.routes.jobs import router
|
||||
from backend.api.dependencies import require_admin, require_auth, AuthResult, UserType
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
# ─── Test App ────────────────────────────────────────────────────────────────
|
||||
|
||||
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
|
||||
app.dependency_overrides[require_auth] = get_mock_admin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
# ─── Fixtures ────────────────────────────────────────────────────────────────
|
||||
|
||||
def _make_job(
|
||||
*,
|
||||
brand_code="NOMAD-1271",
|
||||
gdrive_files=None,
|
||||
gdrive_folder_id="root-folder-id",
|
||||
dropbox_path="/Tracks-PublicShare",
|
||||
artist="piri",
|
||||
title="dog",
|
||||
):
|
||||
"""Make a mock Job in COMPLETE state with the given distribution data."""
|
||||
job = Mock(spec=Job)
|
||||
job.job_id = "test-job-id"
|
||||
job.status = JobStatus.COMPLETE
|
||||
job.artist = artist
|
||||
job.title = title
|
||||
job.dropbox_path = dropbox_path
|
||||
job.gdrive_folder_id = gdrive_folder_id
|
||||
job.state_data = {
|
||||
"brand_code": brand_code,
|
||||
"gdrive_files": gdrive_files if gdrive_files is not None else {},
|
||||
}
|
||||
return job
|
||||
|
||||
|
||||
# ─── GDrive Cleanup — Fast Path (tracked file IDs) ───────────────────────────
|
||||
|
||||
class TestCleanupDistributionGDriveTrackedFileIDs:
|
||||
"""GDrive cleanup uses tracked file IDs from state_data when available."""
|
||||
|
||||
def test_gdrive_cleanup_uses_tracked_file_ids(self, client):
|
||||
"""When gdrive_files has file IDs, delete_files is called with those IDs."""
|
||||
job = _make_job(gdrive_files={"mp4": "file-id-mp4", "cdg": "file-id-cdg"})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.delete_files.return_value = {"file-id-mp4": True, "file-id-cdg": True}
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
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.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# Should have used the tracked file IDs (fast path)
|
||||
mock_gdrive.delete_files.assert_called_once_with(["file-id-mp4", "file-id-cdg"])
|
||||
# Should NOT have searched by brand code
|
||||
mock_gdrive.find_files_by_brand_code.assert_not_called()
|
||||
|
||||
assert data["gdrive"]["status"] == "success"
|
||||
|
||||
def test_gdrive_cleanup_reports_partial_when_some_deletes_fail(self, client):
|
||||
"""When some file deletes fail, status is 'partial'."""
|
||||
job = _make_job(gdrive_files={"mp4": "file-id-mp4", "cdg": "file-id-cdg"})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.delete_files.return_value = {
|
||||
"file-id-mp4": True,
|
||||
"file-id-cdg": False, # This one failed
|
||||
}
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
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.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["gdrive"]["status"] == "partial"
|
||||
|
||||
|
||||
# ─── GDrive Cleanup — Fallback Path (brand_code search) ──────────────────────
|
||||
|
||||
class TestCleanupDistributionGDriveFallback:
|
||||
"""GDrive cleanup searches by brand_code when gdrive_files is empty."""
|
||||
|
||||
def test_falls_back_to_brand_code_search_when_gdrive_files_empty(self, client):
|
||||
"""When gdrive_files={}, search GDrive by brand_code and delete found files."""
|
||||
job = _make_job(gdrive_files={}) # Empty — simulates old jobs / silently-failed uploads
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
# find_files_by_brand_code returns file IDs found by searching GDrive
|
||||
mock_gdrive.find_files_by_brand_code.return_value = ["old-file-id-cdg", "old-file-id-mp4"]
|
||||
mock_gdrive.delete_files.return_value = {
|
||||
"old-file-id-cdg": True,
|
||||
"old-file-id-mp4": True,
|
||||
}
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
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.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# Should have searched by brand code (fallback path)
|
||||
mock_gdrive.find_files_by_brand_code.assert_called_once_with(
|
||||
"root-folder-id", "NOMAD-1271"
|
||||
)
|
||||
# Should have deleted the found files
|
||||
mock_gdrive.delete_files.assert_called_once()
|
||||
assert data["gdrive"]["status"] == "success"
|
||||
|
||||
def test_falls_back_to_brand_code_search_when_gdrive_files_none(self, client):
|
||||
"""When gdrive_files not in state_data (old job), search by brand_code."""
|
||||
job = _make_job(gdrive_files=None)
|
||||
job.state_data = {"brand_code": "NOMAD-1271"} # No gdrive_files key at all
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.find_files_by_brand_code.return_value = ["legacy-file-id"]
|
||||
mock_gdrive.delete_files.return_value = {"legacy-file-id": True}
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
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.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_gdrive.find_files_by_brand_code.assert_called_once()
|
||||
|
||||
def test_reports_skipped_when_no_files_found_by_brand_code(self, client):
|
||||
"""When brand_code search finds nothing, GDrive status is 'skipped'."""
|
||||
job = _make_job(gdrive_files={})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.find_files_by_brand_code.return_value = [] # Nothing found
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
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.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["gdrive"]["status"] == "skipped"
|
||||
assert "no files found" in data["gdrive"]["reason"]
|
||||
|
||||
|
||||
# ─── Brand Code Recycling — Gated on GDrive Success ──────────────────────────
|
||||
|
||||
class TestCleanupDistributionBrandCodeRecycling:
|
||||
"""Brand code is recycled only after BOTH Dropbox AND GDrive are confirmed clean."""
|
||||
|
||||
def test_brand_code_recycled_when_both_dropbox_and_gdrive_cleaned(self, client):
|
||||
"""Brand code is recycled when Dropbox delete succeeds and GDrive cleanup succeeds."""
|
||||
job = _make_job(gdrive_files={"cdg": "file-id"})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True # Dropbox success
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.delete_files.return_value = {"file-id": True} # GDrive success
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
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.brand_code_service.BrandCodeService") as mock_bcs_class, \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
mock_bcs_class.parse_brand_code.return_value = ("NOMAD", 1271)
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# Brand code should be recycled
|
||||
mock_brand_service.recycle_brand_code.assert_called_once()
|
||||
assert data["dropbox"].get("recycled_brand_code") is True
|
||||
|
||||
def test_brand_code_not_recycled_when_gdrive_cleanup_partial(self, client):
|
||||
"""Brand code is NOT recycled when GDrive delete only partially succeeded.
|
||||
|
||||
If GDrive still has files with this brand code, recycling would allow a new
|
||||
job to get the same brand code, creating a duplicate in the public share.
|
||||
"""
|
||||
job = _make_job(gdrive_files={"mp4": "file-id-mp4", "cdg": "file-id-cdg"})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True # Dropbox success
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.delete_files.return_value = {
|
||||
"file-id-mp4": True,
|
||||
"file-id-cdg": False, # CDG file still on GDrive
|
||||
}
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
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.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# Brand code should NOT be recycled because GDrive still has a file
|
||||
mock_brand_service.recycle_brand_code.assert_not_called()
|
||||
# recycled_brand_code key should be absent (recycling never attempted)
|
||||
assert "recycled_brand_code" not in data.get("dropbox", {})
|
||||
|
||||
def test_brand_code_not_recycled_when_gdrive_not_configured(self, client):
|
||||
"""Brand code is NOT recycled when GDrive is not configured.
|
||||
|
||||
Without GDrive credentials, we cannot confirm that GDrive was cleaned.
|
||||
A previous upload may have succeeded (e.g., different credentials rotation).
|
||||
"""
|
||||
job = _make_job(gdrive_files={"cdg": "file-id"})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = False # GDrive not configured
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
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.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
|
||||
# Brand code NOT recycled — GDrive might still have files
|
||||
mock_brand_service.recycle_brand_code.assert_not_called()
|
||||
|
||||
def test_brand_code_recycled_when_gdrive_finds_nothing_to_delete(self, client):
|
||||
"""Brand code IS recycled when GDrive search finds nothing (already clean)."""
|
||||
job = _make_job(gdrive_files={}) # Empty — no tracked IDs
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.find_files_by_brand_code.return_value = [] # GDrive already clean
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
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.brand_code_service.BrandCodeService") as mock_bcs_class, \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
mock_bcs_class.parse_brand_code.return_value = ("NOMAD", 1271)
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# GDrive was confirmed clean (nothing found), so brand code IS recycled
|
||||
mock_brand_service.recycle_brand_code.assert_called_once()
|
||||
assert data["dropbox"].get("recycled_brand_code") is True
|
||||
@@ -0,0 +1,151 @@
|
||||
"""
|
||||
Tests for the GCE encoding service (encoding_service.py).
|
||||
|
||||
Tests resilience features: idempotent submission handling, cached/in_progress
|
||||
responses, and 409 fallback behavior.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, patch, MagicMock
|
||||
|
||||
from backend.services.encoding_service import EncodingService
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def encoding_service():
|
||||
"""Create an EncodingService with mocked credentials."""
|
||||
service = EncodingService()
|
||||
service._url = "http://fake-worker:8080"
|
||||
service._api_key = "test-key"
|
||||
service._initialized = True
|
||||
return service
|
||||
|
||||
|
||||
class TestSubmitEncodingJob:
|
||||
"""Tests for submit_encoding_job() resilience."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_submit_returns_accepted(self, encoding_service):
|
||||
"""Normal submission returns accepted response."""
|
||||
mock_resp = {"status": 200, "json": {"status": "accepted", "job_id": "j1"}, "text": None}
|
||||
with patch.object(encoding_service, "_request_with_retry", new_callable=AsyncMock, return_value=mock_resp):
|
||||
result = await encoding_service.submit_encoding_job("j1", "gs://in", "gs://out", {})
|
||||
assert result["status"] == "accepted"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_submit_returns_cached(self, encoding_service):
|
||||
"""When worker returns cached (job already complete), pass through."""
|
||||
mock_resp = {"status": 200, "json": {"status": "cached", "job_id": "j1", "output_files": ["a.mp4"]}, "text": None}
|
||||
with patch.object(encoding_service, "_request_with_retry", new_callable=AsyncMock, return_value=mock_resp):
|
||||
result = await encoding_service.submit_encoding_job("j1", "gs://in", "gs://out", {})
|
||||
assert result["status"] == "cached"
|
||||
assert result["output_files"] == ["a.mp4"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_submit_returns_in_progress(self, encoding_service):
|
||||
"""When worker returns in_progress, pass through."""
|
||||
mock_resp = {"status": 200, "json": {"status": "in_progress", "job_id": "j1"}, "text": None}
|
||||
with patch.object(encoding_service, "_request_with_retry", new_callable=AsyncMock, return_value=mock_resp):
|
||||
result = await encoding_service.submit_encoding_job("j1", "gs://in", "gs://out", {})
|
||||
assert result["status"] == "in_progress"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_409_fallback_returns_cached_if_complete(self, encoding_service):
|
||||
"""On 409, fall back to get_job_status(); return cached if complete."""
|
||||
mock_resp = {"status": 409, "json": None, "text": "Job j1 already exists"}
|
||||
mock_status = {"status": "complete", "output_files": ["a.mp4", "b.mp4"]}
|
||||
|
||||
with patch.object(encoding_service, "_request_with_retry", new_callable=AsyncMock, return_value=mock_resp), \
|
||||
patch.object(encoding_service, "get_job_status", new_callable=AsyncMock, return_value=mock_status):
|
||||
result = await encoding_service.submit_encoding_job("j1", "gs://in", "gs://out", {})
|
||||
|
||||
assert result["status"] == "cached"
|
||||
assert result["output_files"] == ["a.mp4", "b.mp4"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_409_fallback_returns_in_progress_if_running(self, encoding_service):
|
||||
"""On 409, fall back to get_job_status(); return in_progress if running."""
|
||||
mock_resp = {"status": 409, "json": None, "text": "Job j1 already exists"}
|
||||
mock_status = {"status": "running", "progress": 42}
|
||||
|
||||
with patch.object(encoding_service, "_request_with_retry", new_callable=AsyncMock, return_value=mock_resp), \
|
||||
patch.object(encoding_service, "get_job_status", new_callable=AsyncMock, return_value=mock_status):
|
||||
result = await encoding_service.submit_encoding_job("j1", "gs://in", "gs://out", {})
|
||||
|
||||
assert result["status"] == "in_progress"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_409_fallback_returns_in_progress_if_pending(self, encoding_service):
|
||||
"""On 409, fall back to get_job_status(); return in_progress if pending."""
|
||||
mock_resp = {"status": 409, "json": None, "text": "Job j1 already exists"}
|
||||
mock_status = {"status": "pending", "progress": 0}
|
||||
|
||||
with patch.object(encoding_service, "_request_with_retry", new_callable=AsyncMock, return_value=mock_resp), \
|
||||
patch.object(encoding_service, "get_job_status", new_callable=AsyncMock, return_value=mock_status):
|
||||
result = await encoding_service.submit_encoding_job("j1", "gs://in", "gs://out", {})
|
||||
|
||||
assert result["status"] == "in_progress"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_409_fallback_raises_if_failed(self, encoding_service):
|
||||
"""On 409, fall back to get_job_status(); raise if status is failed."""
|
||||
mock_resp = {"status": 409, "json": None, "text": "Job j1 already exists"}
|
||||
mock_status = {"status": "failed", "error": "ffmpeg crash"}
|
||||
|
||||
with patch.object(encoding_service, "_request_with_retry", new_callable=AsyncMock, return_value=mock_resp), \
|
||||
patch.object(encoding_service, "get_job_status", new_callable=AsyncMock, return_value=mock_status):
|
||||
with pytest.raises(RuntimeError, match="already exists with status: failed"):
|
||||
await encoding_service.submit_encoding_job("j1", "gs://in", "gs://out", {})
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_409_fallback_raises_if_status_check_404(self, encoding_service):
|
||||
"""On 409, if status check returns 404 (worker restarted), raise conflict error."""
|
||||
mock_resp = {"status": 409, "json": None, "text": "Job j1 already exists"}
|
||||
|
||||
with patch.object(encoding_service, "_request_with_retry", new_callable=AsyncMock, return_value=mock_resp), \
|
||||
patch.object(encoding_service, "get_job_status", new_callable=AsyncMock, side_effect=RuntimeError("Encoding job j1 not found")):
|
||||
with pytest.raises(RuntimeError, match="conflict: 409 but job not found"):
|
||||
await encoding_service.submit_encoding_job("j1", "gs://in", "gs://out", {})
|
||||
|
||||
|
||||
class TestEncodeVideos:
|
||||
"""Tests for encode_videos() handling of submit result status."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cached_submit_returns_immediately(self, encoding_service):
|
||||
"""When submit returns cached, return immediately without polling."""
|
||||
cached_result = {"status": "cached", "job_id": "j1", "output_files": ["a.mp4"]}
|
||||
|
||||
with patch.object(encoding_service, "submit_encoding_job", new_callable=AsyncMock, return_value=cached_result) as mock_submit, \
|
||||
patch.object(encoding_service, "wait_for_completion", new_callable=AsyncMock) as mock_wait:
|
||||
result = await encoding_service.encode_videos("j1", "gs://in", "gs://out")
|
||||
|
||||
assert result["status"] == "complete"
|
||||
assert result["output_files"] == ["a.mp4"]
|
||||
mock_submit.assert_called_once()
|
||||
mock_wait.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_in_progress_submit_falls_through_to_wait(self, encoding_service):
|
||||
"""When submit returns in_progress, fall through to wait_for_completion."""
|
||||
in_progress_result = {"status": "in_progress", "job_id": "j1"}
|
||||
completed_result = {"status": "complete", "output_files": ["a.mp4"]}
|
||||
|
||||
with patch.object(encoding_service, "submit_encoding_job", new_callable=AsyncMock, return_value=in_progress_result), \
|
||||
patch.object(encoding_service, "wait_for_completion", new_callable=AsyncMock, return_value=completed_result) as mock_wait:
|
||||
result = await encoding_service.encode_videos("j1", "gs://in", "gs://out")
|
||||
|
||||
assert result["status"] == "complete"
|
||||
mock_wait.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_accepted_submit_falls_through_to_wait(self, encoding_service):
|
||||
"""Normal accepted submission falls through to wait_for_completion."""
|
||||
accepted_result = {"status": "accepted", "job_id": "j1"}
|
||||
completed_result = {"status": "complete", "output_files": ["a.mp4"]}
|
||||
|
||||
with patch.object(encoding_service, "submit_encoding_job", new_callable=AsyncMock, return_value=accepted_result), \
|
||||
patch.object(encoding_service, "wait_for_completion", new_callable=AsyncMock, return_value=completed_result) as mock_wait:
|
||||
result = await encoding_service.encode_videos("j1", "gs://in", "gs://out")
|
||||
|
||||
assert result["status"] == "complete"
|
||||
mock_wait.assert_called_once()
|
||||
@@ -9,6 +9,7 @@ These tests mock the Google API client and Secret Manager to verify:
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import pytest
|
||||
from unittest.mock import Mock, MagicMock, patch
|
||||
|
||||
@@ -501,24 +502,451 @@ class TestUploadToPublicShare:
|
||||
assert len(result) == 1
|
||||
|
||||
|
||||
class TestRetryBehavior:
|
||||
"""Test retry behavior for transient connection errors."""
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_retries_on_broken_pipe(self, mock_get_settings):
|
||||
"""Test that BrokenPipeError triggers retry and succeeds on second attempt."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = json.dumps({
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
})
|
||||
mock_get_settings.return_value = mock_settings
|
||||
|
||||
service = GoogleDriveService()
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
# First call raises BrokenPipeError, second succeeds
|
||||
mock_list_result.execute.side_effect = [
|
||||
BrokenPipeError("[Errno 32] Broken pipe"),
|
||||
{"files": [{"id": "folder-123", "name": "MP4"}]},
|
||||
]
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
service._loaded = True
|
||||
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
|
||||
|
||||
# Patch _reset_service to clear but re-set the mock (avoid real OAuth)
|
||||
def mock_reset():
|
||||
service._service = mock_drive
|
||||
|
||||
service._reset_service = mock_reset
|
||||
|
||||
folder_id = service.get_or_create_folder("parent-123", "MP4")
|
||||
assert folder_id == "folder-123"
|
||||
assert mock_list_result.execute.call_count == 2
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_gives_up_after_3_attempts(self, mock_get_settings):
|
||||
"""Test that 3 consecutive failures raises the exception."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = json.dumps({
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
})
|
||||
mock_get_settings.return_value = mock_settings
|
||||
|
||||
service = GoogleDriveService()
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = BrokenPipeError("[Errno 32] Broken pipe")
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
service._loaded = True
|
||||
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
|
||||
|
||||
# Patch _reset_service to re-set the mock (avoid real OAuth)
|
||||
service._reset_service = lambda: setattr(service, '_service', mock_drive)
|
||||
|
||||
with pytest.raises(BrokenPipeError):
|
||||
service.get_or_create_folder("parent-123", "MP4")
|
||||
|
||||
assert mock_list_result.execute.call_count == 3
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_service_reset_on_retry(self, mock_get_settings):
|
||||
"""Test that _service is reset to None between retry attempts."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = json.dumps({
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
})
|
||||
mock_get_settings.return_value = mock_settings
|
||||
|
||||
service = GoogleDriveService()
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = [
|
||||
BrokenPipeError("[Errno 32] Broken pipe"),
|
||||
{"files": [{"id": "folder-123", "name": "MP4"}]},
|
||||
]
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
service._loaded = True
|
||||
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
|
||||
|
||||
# Patch _reset_service to track calls but still do the reset
|
||||
original_reset = service._reset_service
|
||||
reset_calls = []
|
||||
|
||||
def tracked_reset():
|
||||
reset_calls.append(True)
|
||||
original_reset()
|
||||
# Re-set mock service so the retry works
|
||||
service._service = mock_drive
|
||||
|
||||
service._reset_service = tracked_reset
|
||||
|
||||
folder_id = service.get_or_create_folder("parent-123", "MP4")
|
||||
assert folder_id == "folder-123"
|
||||
assert len(reset_calls) == 1 # Reset called once between attempt 1 and 2
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_retries_on_ssl_error(self, mock_get_settings):
|
||||
"""Test that SSLError triggers retry."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = json.dumps({
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
})
|
||||
mock_get_settings.return_value = mock_settings
|
||||
|
||||
service = GoogleDriveService()
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = [
|
||||
ssl.SSLError("SSL: UNEXPECTED_EOF_WHILE_READING"),
|
||||
{"files": [{"id": "folder-123", "name": "MP4"}]},
|
||||
]
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
service._loaded = True
|
||||
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
|
||||
|
||||
# Patch _reset_service to re-set the mock (avoid real OAuth)
|
||||
service._reset_service = lambda: setattr(service, '_service', mock_drive)
|
||||
|
||||
folder_id = service.get_or_create_folder("parent-123", "MP4")
|
||||
assert folder_id == "folder-123"
|
||||
assert mock_list_result.execute.call_count == 2
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_no_retry_on_non_transient_error(self, mock_get_settings):
|
||||
"""Test that non-transient errors are not retried."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = json.dumps({
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
})
|
||||
mock_get_settings.return_value = mock_settings
|
||||
|
||||
service = GoogleDriveService()
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = ValueError("bad value")
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
service._loaded = True
|
||||
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
service.get_or_create_folder("parent-123", "MP4")
|
||||
|
||||
assert mock_list_result.execute.call_count == 1
|
||||
|
||||
|
||||
class TestDeleteFile:
|
||||
"""Test delete_file and delete_files methods."""
|
||||
|
||||
def _make_service(self, mock_get_settings):
|
||||
"""Helper: make a GoogleDriveService with fake credentials pre-loaded."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
mock_settings = Mock()
|
||||
mock_get_settings.return_value = mock_settings
|
||||
service = GoogleDriveService()
|
||||
service._loaded = True
|
||||
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
|
||||
return service
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_delete_file_success(self, mock_get_settings):
|
||||
"""Successful delete returns True."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_delete = Mock()
|
||||
mock_delete.execute.return_value = None
|
||||
mock_files_api.delete.return_value = mock_delete
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
result = service.delete_file("file-id-123")
|
||||
|
||||
assert result is True
|
||||
mock_files_api.delete.assert_called_once_with(fileId="file-id-123")
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_delete_file_returns_true_on_404(self, mock_get_settings):
|
||||
"""404 (already deleted) returns True — idempotent cleanup."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_delete = Mock()
|
||||
not_found = Exception("File not found")
|
||||
not_found.resp = Mock()
|
||||
not_found.resp.status = 404
|
||||
mock_delete.execute.side_effect = not_found
|
||||
mock_files_api.delete.return_value = mock_delete
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
result = service.delete_file("already-gone-id")
|
||||
|
||||
assert result is True
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_delete_file_returns_false_on_error(self, mock_get_settings):
|
||||
"""Non-404 errors return False."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_delete = Mock()
|
||||
mock_delete.execute.side_effect = Exception("Permission denied")
|
||||
mock_files_api.delete.return_value = mock_delete
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
result = service.delete_file("restricted-file")
|
||||
|
||||
assert result is False
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_delete_files_calls_delete_file_for_each_id(self, mock_get_settings):
|
||||
"""delete_files returns a per-ID success dict."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
# Stub delete_file: first ID succeeds, second fails
|
||||
results_by_id = {"id-1": True, "id-2": False}
|
||||
service.delete_file = lambda fid: results_by_id[fid]
|
||||
|
||||
result = service.delete_files(["id-1", "id-2"])
|
||||
|
||||
assert result == {"id-1": True, "id-2": False}
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_delete_files_empty_list(self, mock_get_settings):
|
||||
"""delete_files with empty list returns empty dict."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
result = service.delete_files([])
|
||||
assert result == {}
|
||||
|
||||
|
||||
class TestFindFilesByBrandCode:
|
||||
"""Test find_files_by_brand_code method — used as fallback in cleanup-distribution."""
|
||||
|
||||
def _make_service(self, mock_get_settings):
|
||||
"""Helper: make a GoogleDriveService with fake credentials pre-loaded."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = json.dumps({
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
})
|
||||
mock_get_settings.return_value = mock_settings
|
||||
service = GoogleDriveService()
|
||||
service._loaded = True
|
||||
service._credentials_data = {
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
}
|
||||
return service
|
||||
|
||||
def _attach_mock_drive(self, service, list_side_effects):
|
||||
"""Attach a mock Drive client whose files().list().execute() returns given values."""
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = list_side_effects
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
return mock_files_api
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_finds_files_in_all_subfolders(self, mock_get_settings):
|
||||
"""Test finds matching files across CDG/, MP4/, MP4-720p/ subfolders."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
# Responses: for each subfolder: (1) find subfolder, (2) search for files
|
||||
mock_list_result.execute.side_effect = [
|
||||
{"files": [{"id": "cdg-folder"}]}, # CDG subfolder found
|
||||
{"files": [{"id": "cdg-file-1", "name": "NOMAD-1271 - piri - dog.zip"}]},
|
||||
{"files": [{"id": "mp4-folder"}]}, # MP4 subfolder found
|
||||
{"files": [{"id": "mp4-file-1", "name": "NOMAD-1271 - piri - dog.mp4"}]},
|
||||
{"files": [{"id": "mp4720-folder"}]}, # MP4-720p subfolder found
|
||||
{"files": [{"id": "mp4720-file-1", "name": "NOMAD-1271 - piri - dog.mp4"}]},
|
||||
]
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
|
||||
|
||||
assert len(result) == 3
|
||||
assert "cdg-file-1" in result
|
||||
assert "mp4-file-1" in result
|
||||
assert "mp4720-file-1" in result
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_returns_empty_when_subfolder_not_found(self, mock_get_settings):
|
||||
"""Test returns empty list when public share subfolders don't exist."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
# All subfolder lookups return empty
|
||||
mock_list_result.execute.return_value = {"files": []}
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
|
||||
|
||||
assert result == []
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_filters_by_exact_brand_code_prefix(self, mock_get_settings):
|
||||
"""Test only returns files whose name starts with '{brand_code} - '."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = [
|
||||
{"files": [{"id": "cdg-folder"}]},
|
||||
{
|
||||
"files": [
|
||||
{"id": "match-id", "name": "NOMAD-1271 - piri - dog.zip"},
|
||||
# This one contains NOMAD-1271 but doesn't START with it — should be excluded
|
||||
{"id": "no-match-id", "name": "BONUS-NOMAD-1271 - other.zip"},
|
||||
]
|
||||
},
|
||||
{"files": []}, # MP4 subfolder not found
|
||||
{"files": []}, # MP4-720p subfolder not found
|
||||
]
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
|
||||
|
||||
assert result == ["match-id"]
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_returns_empty_when_no_files_match_brand_code(self, mock_get_settings):
|
||||
"""Test returns empty list when subfolder exists but has no matching files."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = [
|
||||
{"files": [{"id": "cdg-folder"}]},
|
||||
{"files": [{"id": "other-id", "name": "NOMAD-1300 - someone else.zip"}]},
|
||||
{"files": []}, # MP4 not found
|
||||
{"files": []}, # MP4-720p not found
|
||||
]
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
|
||||
|
||||
assert result == []
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_raises_after_all_subfolders_when_any_error(self, mock_get_settings):
|
||||
"""When any subfolder search errors, raises RuntimeError after processing all subfolders.
|
||||
|
||||
This prevents the cleanup endpoint from treating an incomplete search result
|
||||
as "GDrive is clean" and incorrectly recycling the brand code.
|
||||
"""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = [
|
||||
{"files": [{"id": "cdg-folder"}]},
|
||||
Exception("API error"), # CDG file search fails
|
||||
{"files": [{"id": "mp4-folder"}]},
|
||||
{"files": [{"id": "mp4-file-1", "name": "NOMAD-1271 - piri - dog.mp4"}]},
|
||||
{"files": [{"id": "mp4720-folder"}]},
|
||||
{"files": []},
|
||||
]
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
# Should raise after processing all subfolders — an incomplete search must not
|
||||
# be silently treated as "nothing found" by the caller
|
||||
with pytest.raises(RuntimeError, match="search incomplete"):
|
||||
service.find_files_by_brand_code("root-folder", "NOMAD-1271")
|
||||
|
||||
|
||||
class TestGetGdriveService:
|
||||
"""Test get_gdrive_service singleton."""
|
||||
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_get_gdrive_service_singleton(self, mock_get_settings):
|
||||
"""Test get_gdrive_service returns singleton instance."""
|
||||
from backend.services.gdrive_service import get_gdrive_service
|
||||
import backend.services.gdrive_service as gdrive_module
|
||||
|
||||
|
||||
# Reset singleton
|
||||
gdrive_module._gdrive_service = None
|
||||
|
||||
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = None
|
||||
mock_get_settings.return_value = mock_settings
|
||||
|
||||
|
||||
service1 = get_gdrive_service()
|
||||
service2 = get_gdrive_service()
|
||||
|
||||
|
||||
assert service1 is service2
|
||||
|
||||
@@ -196,7 +196,7 @@ class TestUserEmailExtraction:
|
||||
mock_jm.create_job.return_value = mock_job
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_cred.return_value.check_youtube_credentials.return_value = Mock(status=Mock(value="valid"))
|
||||
mock_search.return_value.search.return_value = []
|
||||
mock_search.return_value.search_async = AsyncMock(return_value=[])
|
||||
|
||||
await search_audio(
|
||||
request=mock_request,
|
||||
|
||||
@@ -4,7 +4,7 @@ Tests for the job health service.
|
||||
Tests consistency checks and worker validation functions.
|
||||
"""
|
||||
import pytest
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timedelta, timezone, UTC
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
from backend.services.job_health_service import (
|
||||
@@ -135,6 +135,43 @@ class TestCheckJobConsistency:
|
||||
issues = check_job_consistency(job)
|
||||
assert issues == []
|
||||
|
||||
def test_encoding_recently_started_not_flagged(self):
|
||||
"""Encoding job started 10 minutes ago should not be flagged."""
|
||||
job = create_test_job(status=JobStatus.ENCODING)
|
||||
job.updated_at = datetime.now(timezone.utc) - timedelta(minutes=10)
|
||||
issues = check_job_consistency(job)
|
||||
assert not any("encoding_stuck" in i for i in issues)
|
||||
|
||||
def test_encoding_stuck_55_min_flagged(self):
|
||||
"""Encoding job stuck for 55 minutes should be flagged."""
|
||||
job = create_test_job(status=JobStatus.ENCODING)
|
||||
job.updated_at = datetime.now(timezone.utc) - timedelta(minutes=55)
|
||||
issues = check_job_consistency(job)
|
||||
assert any("encoding_stuck" in i for i in issues)
|
||||
stuck_issue = [i for i in issues if "encoding_stuck" in i][0]
|
||||
assert "55 min" in stuck_issue
|
||||
|
||||
def test_encoding_at_49_min_not_flagged(self):
|
||||
"""Encoding job at 49 minutes should not be flagged (must exceed 50)."""
|
||||
job = create_test_job(status=JobStatus.ENCODING)
|
||||
job.updated_at = datetime.now(timezone.utc) - timedelta(minutes=49)
|
||||
issues = check_job_consistency(job)
|
||||
assert not any("encoding_stuck" in i for i in issues)
|
||||
|
||||
def test_non_encoding_job_not_affected(self):
|
||||
"""Non-encoding job should not trigger encoding_stuck check."""
|
||||
job = create_test_job(status=JobStatus.GENERATING_VIDEO)
|
||||
job.updated_at = datetime.now(timezone.utc) - timedelta(minutes=120)
|
||||
issues = check_job_consistency(job)
|
||||
assert not any("encoding_stuck" in i for i in issues)
|
||||
|
||||
def test_encoding_stuck_with_naive_datetime(self):
|
||||
"""Encoding-stuck check handles naive datetime (no tzinfo)."""
|
||||
job = create_test_job(status=JobStatus.ENCODING)
|
||||
job.updated_at = datetime.utcnow() - timedelta(minutes=60)
|
||||
issues = check_job_consistency(job)
|
||||
assert any("encoding_stuck" in i for i in issues)
|
||||
|
||||
|
||||
class TestCheckJobConsistencyDetailed:
|
||||
"""Tests for check_job_consistency_detailed function."""
|
||||
|
||||
@@ -274,10 +274,129 @@ class TestSelectInstrumental:
|
||||
|
||||
class TestStartReview:
|
||||
"""Tests for POST /api/jobs/{job_id}/start-review."""
|
||||
|
||||
|
||||
def test_start_review_endpoint_exists(self, client, mock_job_manager, mock_job, auth_headers):
|
||||
"""Test start review endpoint exists."""
|
||||
response = client.post("/api/jobs/test123/start-review", headers=auth_headers)
|
||||
# Should not be 404 or 405
|
||||
assert response.status_code not in [404, 405]
|
||||
|
||||
|
||||
class TestSubmitEditLog:
|
||||
"""Tests for POST /api/jobs/{job_id}/edit-log."""
|
||||
|
||||
def test_submit_edit_log_returns_200(self, client, mock_job_manager, mock_job, auth_headers):
|
||||
"""Test submitting a valid edit log returns 200."""
|
||||
edit_log = {
|
||||
"session_id": "sess-abc",
|
||||
"job_id": "test123",
|
||||
"audio_hash": "hash123",
|
||||
"started_at": "2026-03-01T00:00:00.000Z",
|
||||
"entries": [
|
||||
{
|
||||
"id": "e1",
|
||||
"timestamp": "2026-03-01T00:01:00.000Z",
|
||||
"operation": "word_change",
|
||||
"segment_id": "s1",
|
||||
"segment_index": 0,
|
||||
"word_ids_before": ["w1"],
|
||||
"word_ids_after": ["w1"],
|
||||
"text_before": "helo",
|
||||
"text_after": "hello",
|
||||
"feedback": {"reason": "misheard_word", "timestamp": "2026-03-01T00:01:05.000Z"}
|
||||
}
|
||||
]
|
||||
}
|
||||
with patch('backend.api.routes.jobs.StorageService') as mock_storage_cls:
|
||||
mock_storage = MagicMock()
|
||||
mock_storage_cls.return_value = mock_storage
|
||||
response = client.post("/api/jobs/test123/edit-log", json=edit_log, headers=auth_headers)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["entries_count"] == 1
|
||||
assert data["feedback_count"] == 1
|
||||
|
||||
def test_submit_edit_log_stores_to_gcs(self, client, mock_job_manager, mock_job, auth_headers):
|
||||
"""Test edit log is stored to GCS with correct path."""
|
||||
edit_log = {
|
||||
"session_id": "sess-xyz",
|
||||
"job_id": "test123",
|
||||
"audio_hash": "hash123",
|
||||
"started_at": "2026-03-01T00:00:00.000Z",
|
||||
"entries": []
|
||||
}
|
||||
with patch('backend.api.routes.jobs.StorageService') as mock_storage_cls:
|
||||
mock_storage = MagicMock()
|
||||
mock_storage_cls.return_value = mock_storage
|
||||
client.post("/api/jobs/test123/edit-log", json=edit_log, headers=auth_headers)
|
||||
mock_storage.upload_json.assert_called_once_with(
|
||||
"jobs/test123/lyrics/edit_log_sess-xyz.json",
|
||||
edit_log
|
||||
)
|
||||
|
||||
def test_submit_edit_log_updates_firestore(self, client, mock_job_manager, mock_job, auth_headers):
|
||||
"""Test edit log updates Firestore state_data."""
|
||||
edit_log = {
|
||||
"session_id": "sess-123",
|
||||
"job_id": "test123",
|
||||
"audio_hash": "h",
|
||||
"started_at": "2026-03-01T00:00:00.000Z",
|
||||
"entries": []
|
||||
}
|
||||
with patch('backend.api.routes.jobs.StorageService') as mock_storage_cls:
|
||||
mock_storage_cls.return_value = MagicMock()
|
||||
client.post("/api/jobs/test123/edit-log", json=edit_log, headers=auth_headers)
|
||||
mock_job_manager.update_state_data.assert_any_call(
|
||||
"test123", "last_edit_log_path", "jobs/test123/lyrics/edit_log_sess-123.json"
|
||||
)
|
||||
mock_job_manager.update_state_data.assert_any_call(
|
||||
"test123", "last_edit_log_session", "sess-123"
|
||||
)
|
||||
|
||||
def test_submit_edit_log_nonexistent_job_returns_404(self, mock_worker_service, auth_headers):
|
||||
"""Test submitting to nonexistent job returns 404."""
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = None
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_jm
|
||||
|
||||
with patch('backend.api.routes.jobs.job_manager', mock_jm), \
|
||||
patch('backend.api.routes.jobs.worker_service', mock_worker_service), \
|
||||
patch('backend.services.job_manager.JobManager', mock_jm_factory), \
|
||||
patch('backend.services.firestore_service.firestore'), \
|
||||
patch('backend.services.storage_service.storage'), \
|
||||
patch('google.auth.default', return_value=(mock_creds, 'test-project')):
|
||||
from backend.main import app
|
||||
test_client = TestClient(app)
|
||||
response = test_client.post(
|
||||
"/api/jobs/nonexistent/edit-log",
|
||||
json={"session_id": "s", "entries": []},
|
||||
headers=auth_headers
|
||||
)
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_submit_edit_log_counts_feedback_correctly(self, client, mock_job_manager, mock_job, auth_headers):
|
||||
"""Test feedback count excludes no_response entries."""
|
||||
edit_log = {
|
||||
"session_id": "sess-1",
|
||||
"job_id": "test123",
|
||||
"audio_hash": "h",
|
||||
"started_at": "2026-03-01T00:00:00.000Z",
|
||||
"entries": [
|
||||
{"id": "e1", "feedback": {"reason": "misheard_word"}},
|
||||
{"id": "e2", "feedback": {"reason": "no_response"}},
|
||||
{"id": "e3", "feedback": None},
|
||||
{"id": "e4", "feedback": {"reason": "wrong_lyrics"}},
|
||||
]
|
||||
}
|
||||
with patch('backend.api.routes.jobs.StorageService') as mock_storage_cls:
|
||||
mock_storage_cls.return_value = MagicMock()
|
||||
response = client.post("/api/jobs/test123/edit-log", json=edit_log, headers=auth_headers)
|
||||
data = response.json()
|
||||
assert data["entries_count"] == 4
|
||||
assert data["feedback_count"] == 2 # misheard_word + wrong_lyrics
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
"""
|
||||
Unit tests for the annotations endpoint in review.py.
|
||||
|
||||
Tests the actual storage logic (not the stub version).
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_storage():
|
||||
"""Create a mock StorageService that tracks calls."""
|
||||
storage = MagicMock()
|
||||
storage.upload_json = MagicMock()
|
||||
# Default: no existing annotations
|
||||
storage.download_json = MagicMock(side_effect=Exception("Not found"))
|
||||
return storage
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(mock_storage):
|
||||
"""Create TestClient with mocked dependencies for review routes."""
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = MagicMock(
|
||||
job_id="test-job",
|
||||
status="in_review",
|
||||
review_token="test-review-token"
|
||||
)
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_jm
|
||||
|
||||
# Override review auth to bypass complex auth chain
|
||||
async def fake_review_auth():
|
||||
return ("test-job", "full")
|
||||
|
||||
with patch('backend.api.routes.jobs.job_manager', mock_jm), \
|
||||
patch('backend.services.job_manager.JobManager', mock_jm_factory), \
|
||||
patch('backend.services.firestore_service.firestore'), \
|
||||
patch('backend.services.storage_service.storage'), \
|
||||
patch('google.auth.default', return_value=(mock_creds, 'test-project')):
|
||||
|
||||
from backend.main import app
|
||||
from backend.api.dependencies import require_review_auth
|
||||
|
||||
# Override review auth dependency (must use the same function object used by routes)
|
||||
app.dependency_overrides[require_review_auth] = fake_review_auth
|
||||
|
||||
# Patch StorageService inside the review module
|
||||
with patch('backend.api.routes.review.StorageService', return_value=mock_storage):
|
||||
yield TestClient(app)
|
||||
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
class TestSubmitAnnotations:
|
||||
"""Tests for POST /api/review/{job_id}/v1/annotations."""
|
||||
|
||||
def test_submit_single_annotation(self, client, mock_storage):
|
||||
"""Test submitting a single annotation stores to GCS."""
|
||||
annotation = {"annotation_type": "SOUND_ALIKE", "original_text": "helo", "corrected_text": "hello"}
|
||||
response = client.post("/api/review/test-job/v1/annotations", json=annotation)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["saved_count"] == 1
|
||||
|
||||
def test_submit_batch_annotations(self, client, mock_storage):
|
||||
"""Test submitting a batch of annotations."""
|
||||
payload = {
|
||||
"annotations": [
|
||||
{"annotation_type": "SOUND_ALIKE", "original_text": "a"},
|
||||
{"annotation_type": "EXTRA_WORDS", "original_text": "b"},
|
||||
]
|
||||
}
|
||||
response = client.post("/api/review/test-job/v1/annotations", json=payload)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["saved_count"] == 2
|
||||
assert data["total_count"] == 2
|
||||
|
||||
def test_annotations_stored_to_correct_gcs_path(self, client, mock_storage):
|
||||
"""Test annotations are stored at jobs/{job_id}/lyrics/annotations.json."""
|
||||
client.post(
|
||||
"/api/review/test-job/v1/annotations",
|
||||
json={"annotation_type": "MANUAL_EDIT"}
|
||||
)
|
||||
mock_storage.upload_json.assert_called_once()
|
||||
gcs_path = mock_storage.upload_json.call_args[0][0]
|
||||
assert gcs_path == "jobs/test-job/lyrics/annotations.json"
|
||||
|
||||
def test_annotations_merged_with_existing(self, client, mock_storage):
|
||||
"""Test new annotations are merged with existing ones."""
|
||||
# Set up existing annotations
|
||||
mock_storage.download_json.side_effect = None
|
||||
mock_storage.download_json.return_value = {
|
||||
"annotations": [{"annotation_type": "SOUND_ALIKE", "original_text": "existing"}]
|
||||
}
|
||||
|
||||
payload = {"annotations": [{"annotation_type": "EXTRA_WORDS", "original_text": "new"}]}
|
||||
response = client.post("/api/review/test-job/v1/annotations", json=payload)
|
||||
|
||||
data = response.json()
|
||||
assert data["saved_count"] == 1
|
||||
assert data["total_count"] == 2 # 1 existing + 1 new
|
||||
|
||||
# Verify merged data was uploaded
|
||||
uploaded_data = mock_storage.upload_json.call_args[0][1]
|
||||
assert len(uploaded_data["annotations"]) == 2
|
||||
|
||||
def test_annotations_fresh_when_no_existing(self, client, mock_storage):
|
||||
"""Test annotations start fresh when no existing file."""
|
||||
payload = {"annotations": [{"annotation_type": "NO_ERROR"}]}
|
||||
response = client.post("/api/review/test-job/v1/annotations", json=payload)
|
||||
assert response.json()["total_count"] == 1
|
||||
@@ -250,8 +250,28 @@ class TestVideoWorkerOrchestratorPackaging:
|
||||
"""Test packaging stage."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_packaging_no_lrc(self):
|
||||
"""Test packaging stage with no LRC file."""
|
||||
async def test_run_packaging_no_lrc_cdg_disabled(self):
|
||||
"""Test packaging stage with no LRC file and CDG disabled skips silently."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_cdg=False,
|
||||
lrc_file_path=None,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
# Should not raise, just skip
|
||||
await orchestrator._run_packaging()
|
||||
|
||||
assert orchestrator.result.final_karaoke_cdg_zip is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_packaging_no_lrc_cdg_enabled_raises(self):
|
||||
"""Test packaging stage raises when CDG enabled but no LRC file."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
@@ -264,10 +284,8 @@ class TestVideoWorkerOrchestratorPackaging:
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
# Should not raise, just skip
|
||||
await orchestrator._run_packaging()
|
||||
|
||||
assert orchestrator.result.final_karaoke_cdg_zip is None
|
||||
with pytest.raises(RuntimeError, match="LRC file not available"):
|
||||
await orchestrator._run_packaging()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_packaging_cdg(self):
|
||||
@@ -368,6 +386,209 @@ class TestVideoWorkerOrchestratorPackaging:
|
||||
"countdown_padding_seconds must be passed for CDG timestamp adjustment"
|
||||
|
||||
|
||||
class TestPackagingValidation:
|
||||
"""Test CDG/TXT packaging validation checks.
|
||||
|
||||
These tests verify that the orchestrator fails fast when CDG/TXT
|
||||
generation is enabled but fails, rather than silently proceeding
|
||||
to expensive encoding. This prevents jobs from completing without
|
||||
their requested CDG/TXT packages.
|
||||
|
||||
Added after jobs 5b6aba25 and 5161b069 completed with enable_cdg=True
|
||||
but no CDG ZIP was produced due to a FileNotFoundError being silently caught.
|
||||
"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cdg_validation_fails_when_enabled_but_not_produced(self):
|
||||
"""Test that orchestrator raises when CDG enabled but not produced."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_cdg=True,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
# Mock _run_packaging to NOT set result.final_karaoke_cdg_zip (simulates failure)
|
||||
async def mock_packaging():
|
||||
pass # CDG generation "failed" silently
|
||||
|
||||
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
|
||||
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
|
||||
|
||||
result = await orchestrator.run()
|
||||
|
||||
assert result.success is False
|
||||
assert "CDG generation was enabled but failed" in result.error_message
|
||||
mock_encoding.assert_not_called() # Should not reach encoding
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_txt_validation_fails_when_enabled_but_not_produced(self):
|
||||
"""Test that orchestrator raises when TXT enabled but not produced."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_txt=True,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
async def mock_packaging():
|
||||
pass # TXT generation "failed" silently
|
||||
|
||||
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
|
||||
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
|
||||
|
||||
result = await orchestrator.run()
|
||||
|
||||
assert result.success is False
|
||||
assert "TXT generation was enabled but failed" in result.error_message
|
||||
mock_encoding.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pipeline_succeeds_when_cdg_disabled(self):
|
||||
"""Test that pipeline succeeds normally when CDG is not enabled."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_cdg=False,
|
||||
enable_txt=False,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
with patch.object(orchestrator, "_run_packaging", new_callable=AsyncMock) as mock_pkg, \
|
||||
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock), \
|
||||
patch.object(orchestrator, "_run_organization", new_callable=AsyncMock), \
|
||||
patch.object(orchestrator, "_run_distribution", new_callable=AsyncMock), \
|
||||
patch.object(orchestrator, "_run_notifications", new_callable=AsyncMock):
|
||||
|
||||
result = await orchestrator.run()
|
||||
|
||||
assert result.success is True
|
||||
mock_pkg.assert_not_called() # Packaging skipped entirely
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cdg_validation_passes_when_cdg_produced(self):
|
||||
"""Test that validation passes when CDG is successfully produced."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_cdg=True,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
async def mock_packaging_success():
|
||||
orchestrator.result.final_karaoke_cdg_zip = "/output/cdg.zip"
|
||||
|
||||
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging_success), \
|
||||
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock), \
|
||||
patch.object(orchestrator, "_run_organization", new_callable=AsyncMock), \
|
||||
patch.object(orchestrator, "_run_distribution", new_callable=AsyncMock), \
|
||||
patch.object(orchestrator, "_run_notifications", new_callable=AsyncMock):
|
||||
|
||||
result = await orchestrator.run()
|
||||
|
||||
assert result.success is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_both_cdg_and_txt_validation_fail_together(self):
|
||||
"""Test that orchestrator catches CDG failure when both CDG and TXT enabled."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_cdg=True,
|
||||
enable_txt=True,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
async def mock_packaging():
|
||||
pass # Both CDG and TXT "failed" silently
|
||||
|
||||
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
|
||||
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
|
||||
|
||||
result = await orchestrator.run()
|
||||
|
||||
assert result.success is False
|
||||
# CDG validation is checked first
|
||||
assert "CDG generation was enabled but failed" in result.error_message
|
||||
mock_encoding.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lrc_missing_raises_when_cdg_enabled(self):
|
||||
"""Test that missing LRC file raises when CDG is enabled."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_cdg=True,
|
||||
lrc_file_path="/nonexistent/path.lrc",
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
with pytest.raises(RuntimeError, match="LRC file not available"):
|
||||
await orchestrator._run_packaging()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lrc_missing_raises_when_txt_enabled(self):
|
||||
"""Test that missing LRC file raises when TXT is enabled."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_txt=True,
|
||||
lrc_file_path=None,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
with pytest.raises(RuntimeError, match="LRC file not available"):
|
||||
await orchestrator._run_packaging()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lrc_missing_skips_when_cdg_disabled(self):
|
||||
"""Test that missing LRC file just skips packaging when CDG/TXT disabled."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_cdg=False,
|
||||
enable_txt=False,
|
||||
lrc_file_path=None,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
# Should not raise, just skip
|
||||
await orchestrator._run_packaging()
|
||||
assert orchestrator.result.final_karaoke_cdg_zip is None
|
||||
|
||||
|
||||
class TestVideoWorkerOrchestratorEncoding:
|
||||
"""Test encoding stage."""
|
||||
|
||||
@@ -611,7 +832,7 @@ class TestVideoWorkerOrchestratorOrganization:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_organization_generate_brand_code(self):
|
||||
"""Test brand code generation from Dropbox."""
|
||||
"""Test brand code generation via atomic BrandCodeService."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
@@ -624,15 +845,15 @@ class TestVideoWorkerOrchestratorOrganization:
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
with patch("backend.services.dropbox_service.get_dropbox_service") as mock_get:
|
||||
mock_dropbox = MagicMock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.get_next_brand_code.return_value = "TEST-0001"
|
||||
mock_get.return_value = mock_dropbox
|
||||
with patch("backend.services.brand_code_service.get_brand_code_service") as mock_get:
|
||||
mock_service = MagicMock()
|
||||
mock_service.allocate_brand_code.return_value = "TEST-0001"
|
||||
mock_get.return_value = mock_service
|
||||
|
||||
await orchestrator._run_organization()
|
||||
|
||||
assert orchestrator.result.brand_code == "TEST-0001"
|
||||
mock_service.allocate_brand_code.assert_called_once_with("TEST", "/Karaoke/Tracks")
|
||||
|
||||
|
||||
class TestVideoWorkerOrchestratorDistribution:
|
||||
@@ -772,8 +993,12 @@ class TestVideoWorkerOrchestratorFullPipeline:
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
# Mock packaging to set CDG result (validation requires it when enable_cdg=True)
|
||||
async def mock_packaging_with_result():
|
||||
orchestrator.result.final_karaoke_cdg_zip = "/output/cdg.zip"
|
||||
|
||||
# Mock all stages
|
||||
with patch.object(orchestrator, "_run_packaging", new_callable=AsyncMock) as mock_packaging, \
|
||||
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging_with_result) as mock_packaging, \
|
||||
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding, \
|
||||
patch.object(orchestrator, "_run_organization", new_callable=AsyncMock) as mock_org, \
|
||||
patch.object(orchestrator, "_run_distribution", new_callable=AsyncMock) as mock_dist, \
|
||||
@@ -1287,3 +1512,64 @@ class TestOrchestratorCountdownPadding:
|
||||
assert captured_input is not None, "encode() should have been called"
|
||||
assert captured_input.options.get("countdown_padding_seconds") == 3.0, \
|
||||
"Orchestrator must pass countdown_padding_seconds in EncodingInput.options"
|
||||
|
||||
|
||||
class TestDistributionWarnings:
|
||||
"""Test distribution_warnings tracking in OrchestratorResult."""
|
||||
|
||||
def test_result_has_distribution_warnings_field(self):
|
||||
"""Test that OrchestratorResult has distribution_warnings as empty list by default."""
|
||||
result = OrchestratorResult(success=True)
|
||||
assert result.distribution_warnings == []
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_gdrive_failure_populates_warnings(self):
|
||||
"""Test that Google Drive upload failure populates distribution_warnings."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
gdrive_folder_id="folder-123",
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
orchestrator.result.brand_code = "NOMAD-0001"
|
||||
|
||||
with patch("backend.services.gdrive_service.get_gdrive_service") as mock_get:
|
||||
mock_gdrive = MagicMock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.upload_to_public_share.side_effect = Exception("Connection refused")
|
||||
mock_get.return_value = mock_gdrive
|
||||
|
||||
await orchestrator._upload_to_gdrive()
|
||||
|
||||
assert len(orchestrator.result.distribution_warnings) == 1
|
||||
assert "Google Drive upload failed" in orchestrator.result.distribution_warnings[0]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dropbox_failure_populates_warnings(self):
|
||||
"""Test that Dropbox upload failure populates distribution_warnings."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
dropbox_path="/Public Share",
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
orchestrator.result.brand_code = "NOMAD-0001"
|
||||
|
||||
with patch("backend.services.dropbox_service.get_dropbox_service") as mock_get:
|
||||
mock_dropbox = MagicMock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.upload_folder.side_effect = Exception("Auth expired")
|
||||
mock_get.return_value = mock_dropbox
|
||||
|
||||
await orchestrator._upload_to_dropbox()
|
||||
|
||||
assert len(orchestrator.result.distribution_warnings) == 1
|
||||
assert "Dropbox upload failed" in orchestrator.result.distribution_warnings[0]
|
||||
@@ -339,15 +339,26 @@ async def generate_video_orchestrated(job_id: str) -> bool:
|
||||
# Store result metadata in job BEFORE transitioning to COMPLETE
|
||||
# This ensures youtube_url is available when completion email is sent
|
||||
logger.info(f"[job:{job_id}] Video generation complete")
|
||||
job_manager.update_job(job_id, {
|
||||
'state_data': {
|
||||
**job.state_data,
|
||||
'brand_code': result.brand_code,
|
||||
'youtube_url': result.youtube_url,
|
||||
'dropbox_link': result.dropbox_link,
|
||||
'gdrive_files': result.gdrive_files,
|
||||
}
|
||||
})
|
||||
state_update = {
|
||||
**job.state_data,
|
||||
'brand_code': result.brand_code,
|
||||
'youtube_url': result.youtube_url,
|
||||
'dropbox_link': result.dropbox_link,
|
||||
'gdrive_files': result.gdrive_files,
|
||||
}
|
||||
if result.distribution_warnings:
|
||||
state_update['distribution_warnings'] = result.distribution_warnings
|
||||
job_manager.update_job(job_id, {'state_data': state_update})
|
||||
|
||||
# Send Pushbullet alert if any distribution uploads failed
|
||||
if result.distribution_warnings:
|
||||
_send_distribution_warning_notification(
|
||||
job_id=job_id,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
warnings=result.distribution_warnings,
|
||||
settings=settings,
|
||||
)
|
||||
|
||||
# Mark job as complete (triggers completion email with youtube_url now available)
|
||||
job_manager.transition_to_state(
|
||||
@@ -800,9 +811,11 @@ async def _handle_native_distribution(
|
||||
else:
|
||||
job_log.info(f"Starting native Dropbox upload to {dropbox_path}")
|
||||
|
||||
# Calculate brand code from existing folders (if not already generated)
|
||||
# Calculate brand code atomically (if not already generated)
|
||||
if not brand_code:
|
||||
brand_code = dropbox.get_next_brand_code(dropbox_path, brand_prefix)
|
||||
from backend.services.brand_code_service import get_brand_code_service
|
||||
brand_code_service = get_brand_code_service()
|
||||
brand_code = brand_code_service.allocate_brand_code(brand_prefix, dropbox_path)
|
||||
result['brand_code'] = brand_code
|
||||
job_log.info(f"Generated brand code: {brand_code}")
|
||||
|
||||
@@ -839,6 +852,7 @@ async def _handle_native_distribution(
|
||||
job_log.warning(f"Dropbox SDK not installed: {e}")
|
||||
except Exception as e:
|
||||
job_log.error(f"Native Dropbox upload failed: {e}", exc_info=True)
|
||||
result.setdefault('distribution_warnings', []).append(f"Dropbox upload failed: {e}")
|
||||
# Don't fail the job - distribution is optional
|
||||
|
||||
# Upload to Google Drive using native API
|
||||
@@ -882,6 +896,7 @@ async def _handle_native_distribution(
|
||||
job_log.warning(f"Google API packages not installed: {e}")
|
||||
except Exception as e:
|
||||
job_log.error(f"Native Google Drive upload failed: {e}", exc_info=True)
|
||||
result.setdefault('distribution_warnings', []).append(f"Google Drive upload failed: {e}")
|
||||
# Don't fail the job - distribution is optional
|
||||
elif existing_gdrive_files:
|
||||
job_log.info(f"Skipping Google Drive upload - orchestrator already uploaded {len(existing_gdrive_files)} files")
|
||||
@@ -889,17 +904,64 @@ async def _handle_native_distribution(
|
||||
# Update job state_data with brand code and links
|
||||
if brand_code or result.get('dropbox_link') or result.get('gdrive_files'):
|
||||
try:
|
||||
job_manager.update_job(job_id, {
|
||||
'state_data': {
|
||||
**job.state_data,
|
||||
'brand_code': brand_code,
|
||||
'dropbox_link': result.get('dropbox_link'),
|
||||
'gdrive_files': result.get('gdrive_files'),
|
||||
}
|
||||
})
|
||||
state_update = {
|
||||
**job.state_data,
|
||||
'brand_code': brand_code,
|
||||
'dropbox_link': result.get('dropbox_link'),
|
||||
'gdrive_files': result.get('gdrive_files'),
|
||||
}
|
||||
if result.get('distribution_warnings'):
|
||||
state_update['distribution_warnings'] = result['distribution_warnings']
|
||||
job_manager.update_job(job_id, {'state_data': state_update})
|
||||
except Exception as e:
|
||||
job_log.warning(f"Failed to update job state_data: {e}")
|
||||
|
||||
# Send Pushbullet alert if any distribution uploads failed
|
||||
if result.get('distribution_warnings'):
|
||||
_send_distribution_warning_notification(
|
||||
job_id=job_id,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
warnings=result['distribution_warnings'],
|
||||
settings=settings,
|
||||
)
|
||||
|
||||
|
||||
def _send_distribution_warning_notification(
|
||||
job_id: str,
|
||||
artist: str,
|
||||
title: str,
|
||||
warnings: list[str],
|
||||
settings=None,
|
||||
) -> None:
|
||||
"""Send Pushbullet notification when distribution uploads fail."""
|
||||
try:
|
||||
if settings is None:
|
||||
settings = get_settings()
|
||||
api_key = settings.get_secret("pushbullet-api-key")
|
||||
if not api_key:
|
||||
logger.warning("Pushbullet API key not found, skipping distribution warning notification")
|
||||
return
|
||||
|
||||
import requests as req
|
||||
|
||||
push_title = f"Distribution Warning: {artist} - {title}"
|
||||
body = f"Job {job_id} completed but {len(warnings)} upload(s) failed:\n\n"
|
||||
body += "\n".join(f" - {w}" for w in warnings)
|
||||
|
||||
resp = req.post(
|
||||
"https://api.pushbullet.com/v2/pushes",
|
||||
headers={"Access-Token": api_key, "Content-Type": "application/json"},
|
||||
json={"type": "note", "title": push_title, "body": body},
|
||||
timeout=10,
|
||||
)
|
||||
if resp.ok:
|
||||
logger.info(f"[job:{job_id}] Distribution warning notification sent via Pushbullet")
|
||||
else:
|
||||
logger.warning(f"[job:{job_id}] Pushbullet notification failed: {resp.status_code} {resp.text}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Failed to send Pushbullet notification: {e}")
|
||||
|
||||
|
||||
def _validate_prerequisites(job) -> bool:
|
||||
"""Validate that all prerequisites are met for video generation."""
|
||||
|
||||
@@ -109,6 +109,9 @@ class OrchestratorResult:
|
||||
dropbox_link: Optional[str] = None
|
||||
gdrive_files: Optional[Dict[str, str]] = field(default_factory=dict)
|
||||
|
||||
# Distribution warnings (non-fatal upload failures)
|
||||
distribution_warnings: List[str] = field(default_factory=list)
|
||||
|
||||
# Timing
|
||||
encoding_time_seconds: Optional[float] = None
|
||||
total_time_seconds: Optional[float] = None
|
||||
@@ -228,6 +231,18 @@ class VideoWorkerOrchestrator:
|
||||
if self.config.enable_cdg or self.config.enable_txt:
|
||||
await self._run_packaging()
|
||||
|
||||
# Validate required packaging outputs before expensive encoding
|
||||
if self.config.enable_cdg and not self.result.final_karaoke_cdg_zip:
|
||||
raise RuntimeError(
|
||||
"CDG generation was enabled but failed. "
|
||||
"Check worker logs for CDG-related errors."
|
||||
)
|
||||
if self.config.enable_txt and not self.result.final_karaoke_txt_zip:
|
||||
raise RuntimeError(
|
||||
"TXT generation was enabled but failed. "
|
||||
"Check worker logs for TXT-related errors."
|
||||
)
|
||||
|
||||
# Stage 2: Encoding
|
||||
await self._run_encoding()
|
||||
|
||||
@@ -240,6 +255,11 @@ class VideoWorkerOrchestrator:
|
||||
# Stage 5: Notifications (Discord)
|
||||
await self._run_notifications()
|
||||
|
||||
# Stage 6: Post-distribution GDrive validation
|
||||
# Only for jobs that uploaded to the public share (non-private)
|
||||
if self.config.gdrive_folder_id:
|
||||
await self._trigger_gdrive_validation()
|
||||
|
||||
self.result.success = True
|
||||
self.result.total_time_seconds = time.time() - start_time
|
||||
|
||||
@@ -259,6 +279,10 @@ class VideoWorkerOrchestrator:
|
||||
self.job_log.info("Starting packaging stage (CDG/TXT)")
|
||||
|
||||
if not self.config.lrc_file_path or not os.path.isfile(self.config.lrc_file_path):
|
||||
if self.config.enable_cdg or self.config.enable_txt:
|
||||
raise RuntimeError(
|
||||
f"CDG/TXT generation enabled but LRC file not available: {self.config.lrc_file_path}"
|
||||
)
|
||||
self.job_log.warning("No LRC file available, skipping CDG/TXT packaging")
|
||||
return
|
||||
|
||||
@@ -468,18 +492,15 @@ class VideoWorkerOrchestrator:
|
||||
# Generate brand code from Dropbox if configured
|
||||
if self.config.dropbox_path and self.config.brand_prefix:
|
||||
try:
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
from backend.services.brand_code_service import get_brand_code_service
|
||||
|
||||
dropbox = get_dropbox_service()
|
||||
if dropbox.is_configured:
|
||||
brand_code = dropbox.get_next_brand_code(
|
||||
self.config.dropbox_path,
|
||||
self.config.brand_prefix
|
||||
)
|
||||
self.result.brand_code = brand_code
|
||||
self.job_log.info(f"Generated brand code: {brand_code}")
|
||||
else:
|
||||
self.job_log.warning("Dropbox not configured, skipping brand code generation")
|
||||
brand_code_service = get_brand_code_service()
|
||||
brand_code = brand_code_service.allocate_brand_code(
|
||||
self.config.brand_prefix,
|
||||
self.config.dropbox_path
|
||||
)
|
||||
self.result.brand_code = brand_code
|
||||
self.job_log.info(f"Generated brand code: {brand_code}")
|
||||
|
||||
except Exception as e:
|
||||
self.job_log.error(f"Brand code generation failed: {e}")
|
||||
@@ -590,6 +611,7 @@ class VideoWorkerOrchestrator:
|
||||
|
||||
except Exception as e:
|
||||
self.job_log.error(f"YouTube upload failed: {e}")
|
||||
self.result.distribution_warnings.append(f"YouTube upload failed: {e}")
|
||||
# Don't fail the pipeline - YouTube is optional
|
||||
|
||||
async def _upload_to_dropbox(self):
|
||||
@@ -626,6 +648,7 @@ class VideoWorkerOrchestrator:
|
||||
|
||||
except Exception as e:
|
||||
self.job_log.error(f"Dropbox upload failed: {e}")
|
||||
self.result.distribution_warnings.append(f"Dropbox upload failed: {e}")
|
||||
# Don't fail the pipeline - Dropbox is optional
|
||||
|
||||
async def _upload_to_gdrive(self):
|
||||
@@ -662,6 +685,7 @@ class VideoWorkerOrchestrator:
|
||||
|
||||
except Exception as e:
|
||||
self.job_log.error(f"Google Drive upload failed: {e}")
|
||||
self.result.distribution_warnings.append(f"Google Drive upload failed: {e}")
|
||||
# Don't fail the pipeline - GDrive is optional
|
||||
|
||||
async def _run_notifications(self):
|
||||
@@ -684,6 +708,16 @@ class VideoWorkerOrchestrator:
|
||||
self.job_log.error(f"Discord notification failed: {e}")
|
||||
# Don't fail the pipeline - notifications are optional
|
||||
|
||||
async def _trigger_gdrive_validation(self):
|
||||
"""Trigger GDrive validation after uploading to the public share."""
|
||||
try:
|
||||
from backend.services.gdrive_validator_client import trigger_gdrive_validation
|
||||
self.job_log.info("Triggering post-job GDrive validation")
|
||||
trigger_gdrive_validation()
|
||||
except Exception as e:
|
||||
self.job_log.warning(f"GDrive validation trigger failed (non-fatal): {e}")
|
||||
# Never fail the pipeline for validation
|
||||
|
||||
|
||||
def create_orchestrator_config_from_job(
|
||||
job,
|
||||
|
||||
@@ -225,6 +225,51 @@ Error (duration mismatch):
|
||||
}
|
||||
```
|
||||
|
||||
#### Submit Edit Log
|
||||
|
||||
```http
|
||||
POST /api/jobs/{job_id}/edit-log
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"session_id": "abc123",
|
||||
"job_id": "test-job",
|
||||
"audio_hash": "hash",
|
||||
"started_at": "2026-03-01T00:00:00.000Z",
|
||||
"entries": [
|
||||
{
|
||||
"id": "entry-1",
|
||||
"timestamp": "2026-03-01T00:01:00.000Z",
|
||||
"operation": "word_change",
|
||||
"segment_id": "seg-0",
|
||||
"segment_index": 0,
|
||||
"word_ids_before": ["w1"],
|
||||
"word_ids_after": ["w1"],
|
||||
"text_before": "helo",
|
||||
"text_after": "hello",
|
||||
"feedback": { "reason": "misheard_word", "timestamp": "..." }
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Stores a session edit log to GCS at `jobs/{job_id}/lyrics/edit_log_{session_id}.json`. Tracks all user edits and optional feedback reasons for transcription improvement. Called automatically on review submission.
|
||||
|
||||
#### Submit Annotations
|
||||
|
||||
```http
|
||||
POST /api/review/{job_id}/v1/annotations
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"annotations": [
|
||||
{ "annotation_type": "SOUND_ALIKE", "original_text": "helo" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Stores annotations to `jobs/{job_id}/lyrics/annotations.json`. Merges with existing annotations if present.
|
||||
|
||||
### Instrumental Selection (Finalise-Only Jobs)
|
||||
|
||||
For finalise-only jobs (where audio prep was done externally), instrumental selection is handled separately:
|
||||
|
||||
@@ -119,6 +119,8 @@ jobs/{job_id}/
|
||||
├── lyrics/
|
||||
│ ├── corrections.json # Auto-corrected
|
||||
│ ├── corrections_updated.json # After human review
|
||||
│ ├── edit_log_{session}.json # User edit log with feedback
|
||||
│ ├── annotations.json # Correction annotations
|
||||
│ └── karaoke.ass
|
||||
├── screens/
|
||||
│ ├── title.mov
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
# Google Drive Validator
|
||||
|
||||
Automated validation of the Nomad Karaoke public Google Drive share folder. Detects duplicate brand codes, invalid filenames, and sequence gaps.
|
||||
|
||||
## Overview
|
||||
|
||||
The public share folder (`1laRKAyxo0v817SstfM5XkpbWiNKNAMSX`) contains all published karaoke tracks organized into subfolders:
|
||||
|
||||
```
|
||||
Public Share/
|
||||
CDG/ # .zip files (MP3 + CDG for KJ players)
|
||||
MP4/ # .mp4 files (4K lossless)
|
||||
MP4-720p/ # .mp4 files (720p lossy)
|
||||
```
|
||||
|
||||
Each file follows the naming convention: `NOMAD-XXXX - Artist - Title.(mp4|zip)`
|
||||
|
||||
The validator checks:
|
||||
- **Duplicate sequence numbers** - e.g., two files both named `NOMAD-1271`
|
||||
- **Invalid filenames** - files that don't match the expected pattern
|
||||
- **Sequence gaps** - missing numbers in the NOMAD-XXXX sequence (with known exclusions)
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌────────────────────────┐
|
||||
│ Cloud Scheduler │
|
||||
│ (9 PM ET daily) │
|
||||
└──────────┬─────────────┘
|
||||
│ OIDC auth
|
||||
▼
|
||||
┌──────────────────┐ ┌────────────────────────┐ ┌──────────────┐
|
||||
│ Backend (post- │ OIDC │ gdrive-validator │ API │ Google Drive │
|
||||
│ job completion) │─────────→│ Cloud Function (Gen2) │─────────→│ API v3 │
|
||||
└──────────────────┘ └──────────┬─────────────┘ └──────────────┘
|
||||
│
|
||||
┌──────────────────┐ ┌──────┴──────┐
|
||||
│ gcloud functions │ │ │
|
||||
│ call (manual) │─────────→ ▼ ▼
|
||||
└──────────────────┘ ┌───────────┐ ┌────────────┐
|
||||
│ SendGrid │ │ Pushbullet │
|
||||
│ (primary) │ │ (fallback) │
|
||||
└───────────┘ └────────────┘
|
||||
```
|
||||
|
||||
### Trigger Points
|
||||
|
||||
| Trigger | When | How |
|
||||
|---------|------|-----|
|
||||
| **Daily schedule** | 9:00 PM ET every day | Cloud Scheduler → HTTP POST with OIDC token |
|
||||
| **Post-job** | After each job uploads to public share | Backend orchestrator → HTTP POST with OIDC token |
|
||||
| **Manual** | On demand | `python scripts/check_public_share.py` via gcloud CLI |
|
||||
|
||||
### Notifications
|
||||
|
||||
Notifications are sent via **both** channels (belt + suspenders):
|
||||
|
||||
1. **SendGrid email** (primary) - Sent to `gen@nomadkaraoke.com`. Provides a persistent, searchable record.
|
||||
2. **Pushbullet** (fallback) - Push notification for immediate visibility.
|
||||
|
||||
Notifications are sent when:
|
||||
- Issues are found (always)
|
||||
- No issues found and `NOTIFY_ON_SUCCESS=true` (daily summary)
|
||||
- Errors occur during validation
|
||||
|
||||
## Files
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `infrastructure/functions/gdrive_validator/main.py` | Cloud Function source code |
|
||||
| `infrastructure/functions/gdrive_validator/requirements.txt` | Python dependencies |
|
||||
| `infrastructure/functions/gdrive_validator/deploy.sh` | Manual deployment script |
|
||||
| `infrastructure/__main__.py` | Pulumi config (env vars, secrets, IAM) |
|
||||
| `infrastructure/modules/iam/worker_sas.py` | Service account definition |
|
||||
| `backend/services/gdrive_validator_client.py` | Backend HTTP client (OIDC auth) |
|
||||
| `backend/workers/video_worker_orchestrator.py` | Post-job trigger integration |
|
||||
| `scripts/check_public_share.py` | Local CLI for manual checks |
|
||||
|
||||
## Configuration
|
||||
|
||||
### Environment Variables (Cloud Function)
|
||||
|
||||
| Variable | Value | Description |
|
||||
|----------|-------|-------------|
|
||||
| `GDRIVE_FOLDER_ID` | `1laRKAyxo0v817SstfM5XkpbWiNKNAMSX` | Root folder of public share |
|
||||
| `NOTIFY_ON_SUCCESS` | `true` | Send daily "all clear" summary |
|
||||
| `EMAIL_TO` | `gen@nomadkaraoke.com` | Email recipient |
|
||||
| `EMAIL_FROM` | `gen@nomadkaraoke.com` | Email sender |
|
||||
|
||||
### Secrets (Cloud Function)
|
||||
|
||||
| Secret | Source | Description |
|
||||
|--------|--------|-------------|
|
||||
| `SENDGRID_API_KEY` | `sendgrid-api-key:latest` | SendGrid API key for email |
|
||||
| `PUSHBULLET_API_KEY` | `pushbullet-api-key:latest` | Pushbullet API key for push notifications |
|
||||
|
||||
### Secrets (Backend / Cloud Run)
|
||||
|
||||
| Secret | Source | Description |
|
||||
|--------|--------|-------------|
|
||||
| `GDRIVE_VALIDATOR_URL` | `gdrive-validator-url:latest` | Cloud Function URL for post-job trigger |
|
||||
|
||||
### IAM
|
||||
|
||||
| Principal | Role | Resource | Purpose |
|
||||
|-----------|------|----------|---------|
|
||||
| `gdrive-validator@` SA | `roles/cloudfunctions.invoker` | gdrive-validator function | Self-invoke (Cloud Scheduler) |
|
||||
| Cloud Scheduler agent | `roles/cloudfunctions.invoker` | gdrive-validator function | Daily trigger |
|
||||
| `karaoke-backend@` SA | `roles/cloudfunctions.invoker` | gdrive-validator function | Post-job trigger |
|
||||
| `karaoke-backend@` SA | `roles/run.invoker` | gdrive-validator Cloud Run service | Gen2 function HTTP access |
|
||||
|
||||
### Known Gaps
|
||||
|
||||
The validator knows about expected sequence gaps (historical missing numbers). These are configured identically in both:
|
||||
- `infrastructure/functions/gdrive_validator/main.py` (Cloud Function)
|
||||
- `scripts/validate_and_sync.py` (local script)
|
||||
|
||||
When a new gap is discovered intentionally (e.g., a track was removed), update the `KNOWN_GAPS` dict in **both** files.
|
||||
|
||||
## Usage
|
||||
|
||||
### Manual Check
|
||||
|
||||
```bash
|
||||
# Formatted output
|
||||
python scripts/check_public_share.py
|
||||
|
||||
# Raw JSON
|
||||
python scripts/check_public_share.py --json
|
||||
```
|
||||
|
||||
Exit codes: `0` = all clear, `1` = issues found, `2` = error.
|
||||
|
||||
### Checking Cloud Function Logs
|
||||
|
||||
```bash
|
||||
gcloud functions logs read gdrive-validator --region=us-central1 --project=nomadkaraoke --limit=50
|
||||
```
|
||||
|
||||
### Redeploying the Cloud Function
|
||||
|
||||
The Cloud Function source is not deployed via CI — it's deployed either:
|
||||
1. **Via Pulumi** (infrastructure changes like env vars, secrets, IAM)
|
||||
2. **Via `deploy.sh`** (code changes to `main.py`)
|
||||
|
||||
```bash
|
||||
cd infrastructure/functions/gdrive_validator
|
||||
./deploy.sh
|
||||
```
|
||||
|
||||
Note: `deploy.sh` deploys the source code. Pulumi manages the infrastructure (env vars, secrets, IAM, scheduler). After running `deploy.sh`, the Pulumi-managed config is overwritten by the gcloud deploy — run `pulumi up` afterward if you need to restore Pulumi-managed settings.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Email Not Received
|
||||
|
||||
1. Check Cloud Function logs for SendGrid errors:
|
||||
```bash
|
||||
gcloud functions logs read gdrive-validator --region=us-central1 --limit=20
|
||||
```
|
||||
2. Verify the SendGrid API key is set:
|
||||
```bash
|
||||
gcloud secrets versions access latest --secret=sendgrid-api-key --project=nomadkaraoke | head -c 10
|
||||
```
|
||||
3. Check SendGrid dashboard for delivery status
|
||||
4. Pushbullet should still work as fallback
|
||||
|
||||
### Post-Job Trigger Not Firing
|
||||
|
||||
1. Check that `GDRIVE_VALIDATOR_URL` secret is set:
|
||||
```bash
|
||||
gcloud secrets versions access latest --secret=gdrive-validator-url --project=nomadkaraoke
|
||||
```
|
||||
2. Check backend logs for the job — look for "Triggering post-job GDrive validation" or "GDrive validation trigger failed"
|
||||
3. Verify the backend SA has invoker permissions:
|
||||
```bash
|
||||
gcloud functions get-iam-policy gdrive-validator --region=us-central1 --project=nomadkaraoke
|
||||
```
|
||||
4. The trigger only fires for non-private jobs (jobs with `gdrive_folder_id` set)
|
||||
|
||||
### False Positive Gaps
|
||||
|
||||
If the validator reports gaps that are intentional:
|
||||
1. Add the gap number(s) to `KNOWN_GAPS` in both `main.py` and `scripts/validate_and_sync.py`
|
||||
2. Redeploy the cloud function with `./deploy.sh`
|
||||
|
||||
### Duplicate Brand Code Detected
|
||||
|
||||
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
|
||||
4. Re-trigger validation to confirm the fix
|
||||
|
||||
## Cloud Function vs Local Script
|
||||
|
||||
| Check | Cloud Function | Local Script (`validate_and_sync.py`) |
|
||||
|-------|---------------|--------------------------------------|
|
||||
| Duplicate sequence numbers | Yes | Yes |
|
||||
| Invalid filenames | Yes | Yes |
|
||||
| Sequence gaps | Yes | Yes |
|
||||
| ZIP contents (MP3+CDG) | No (expensive) | Yes |
|
||||
| Video resolution | No (expensive) | Yes |
|
||||
| Render quality | No (expensive) | Yes |
|
||||
| Bidirectional sync | No (read-only) | Yes (rclone) |
|
||||
|
||||
The cloud function does metadata-only checks via the GDrive API (fast, cheap, can run frequently). The local script does deep content validation that requires downloading files (slow, run manually).
|
||||
|
||||
## History
|
||||
|
||||
- **2025-12-24**: Initial cloud function deployed with Pushbullet notifications and daily Cloud Scheduler trigger
|
||||
- **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.
|
||||
@@ -6,6 +6,16 @@ Key insights for future AI agents working on this codebase.
|
||||
|
||||
---
|
||||
|
||||
## UX Patterns
|
||||
|
||||
### Fixture-Driven UI Verification
|
||||
For UI that renders differently based on data (e.g., audio search result tiers), fetch real production data as fixtures and build a Playwright review tool. The `npm run fixtures:review-ui` pattern (41 fixtures, console-based `next()` advancement) was far more effective than manual testing or screenshots — caught edge cases with non-Latin filenames, single-character filenames, and underscore-separated names that unit tests alone would have missed.
|
||||
|
||||
### Filename Matching Normalization
|
||||
When comparing filenames to search titles, treat underscores/hyphens/dots as word separators BEFORE stripping non-alphanumeric chars. Also require a minimum substring length (3 chars) to prevent false matches like filename "K" matching title "KoREH". For non-Latin scripts (Hebrew, etc.), return an indeterminate result rather than a false match or false mismatch.
|
||||
|
||||
---
|
||||
|
||||
## Architecture Decisions
|
||||
|
||||
### Separate Collections for Multi-App Projects
|
||||
@@ -30,6 +40,17 @@ When two sequential human review steps can be combined into one, do it. We origi
|
||||
|
||||
## Common Gotchas
|
||||
|
||||
### Gate Resource Recycling on Full Cleanup Confirmation (Feb 2026)
|
||||
**What happened**: Brand code NOMAD-1271 was recycled and reused for a real song while old E2E test job files still existed in Google Drive, creating a duplicate in the public share.
|
||||
|
||||
**Root causes**:
|
||||
1. `if gdrive_files:` skips cleanup when `gdrive_files = {}` (empty dict is falsy) — any falsy check on a collection will silently skip work
|
||||
2. Brand code recycled after Dropbox cleanup success, *before* confirming GDrive was clean — partial cleanup allowed resource reuse with orphaned files
|
||||
|
||||
**Fix**: Use `if gdrive_files is not None` (or check explicitly). Gate resource recycling on **all** cleanup steps succeeding, not just the first one. When a resource has been distributed to N places, it's only safe to recycle when all N locations are confirmed clean.
|
||||
|
||||
**Pattern**: Treat resource IDs (brand codes, sequential IDs) like distributed transactions — either all distribution points are cleaned, or the ID stays reserved.
|
||||
|
||||
### Fail Fast, Don't Fall Back
|
||||
Silent fallbacks hide configuration errors. When critical configuration is missing (themes, credentials, etc.), raise clear errors instead of falling back to defaults. Better to fail loudly during testing than silently produce incorrect output in production. Example: Theme validation (v0.109.0) now raises `ValueError` on incomplete themes instead of merging with defaults. This ensures all cloud jobs use complete, explicit themes with no silent degradation.
|
||||
|
||||
@@ -58,6 +79,15 @@ When multiple code paths create jobs (file upload, audio search, webhooks), use
|
||||
|
||||
**Pattern**: When a function can fail, prefer exceptions over boolean returns. Silent failures accumulate into production bugs. Use centralized helpers for multi-step operations (state change + side effects) to prevent divergent implementations.
|
||||
|
||||
### Validate Pipeline Stage Outputs Before Proceeding (Feb 2026)
|
||||
**What happened**: Jobs 5b6aba25 and 5161b069 completed with `enable_cdg=True` but no CDG ZIP was produced. The orchestrator silently caught a `FileNotFoundError` during CDG generation and proceeded to 11+ minutes of GPU encoding, distribution, and notifications — all for an incomplete output.
|
||||
|
||||
**Root cause**: CDG generation failed because `instrumental_selection: custom` had no case in the filename construction (fell through to "Backing" suffix). The `FileNotFoundError` was caught by a broad `except Exception` that just logged and continued, since "CDG is optional."
|
||||
|
||||
**Fix**: Add validation gates between pipeline stages. After packaging completes but before expensive encoding begins, verify that all enabled outputs were actually produced. If `enable_cdg=True` but no CDG ZIP exists, raise `RuntimeError` immediately. This fails fast, saves encoding costs, and makes the error visible.
|
||||
|
||||
**Pattern**: When a pipeline stage produces optional outputs that were explicitly requested, validate their existence before proceeding to the next stage. "Optional" means "can be disabled," not "can silently fail when enabled."
|
||||
|
||||
### Fix Both Sides of Dual Code Paths
|
||||
When fixing a bug in a system with multiple code paths (e.g., legacy vs orchestrator, local vs cloud), verify ALL paths are fixed. PR #271 fixed the GCE worker to READ `instrumental_selection` but only checked the legacy path which was already SENDING it. The orchestrator path (production default) wasn't sending it. **Pattern**: If a component receives config from multiple callers, check ALL callers when fixing the receiving side. Write integration tests that cover each path.
|
||||
|
||||
@@ -213,6 +243,18 @@ When deferring processing from one worker to another, you MUST update the job st
|
||||
### Google Drive Query Escaping
|
||||
Escape special chars in Google Drive API queries: `'` → `\'`, `\` → `\\\\`.
|
||||
|
||||
### Google Drive Stale Connection on Cloud Run (Feb 2026)
|
||||
**What happened**: Every GDrive upload silently failed for ~1 month (64 errors, 12+ jobs). Errors: `[Errno 32] Broken pipe` or `[SSL: UNEXPECTED_EOF_WHILE_READING]`. Jobs completed with `gdrive_files: {}` and no alert was sent.
|
||||
|
||||
**Root cause**: The singleton `GoogleDriveService` caches its HTTP connection. When Cloud Run containers sit idle between jobs, the underlying TCP connection goes stale. The next API call hits a dead socket. The orchestrator catches all exceptions in distribution and continues silently.
|
||||
|
||||
**Fix** (v0.119.7):
|
||||
1. Added tenacity retry with `_reset_service()` (sets `self._service = None` to force fresh connection) on transient errors (`BrokenPipeError`, `ConnectionResetError`, `ssl.SSLError`)
|
||||
2. Added `distribution_warnings` field to `OrchestratorResult` to track non-fatal upload failures
|
||||
3. Added Pushbullet notification when distribution uploads fail, so operator is alerted immediately
|
||||
|
||||
**Pattern**: Any singleton service that caches HTTP connections should have retry logic with connection reset for stale connection errors. Cloud Run containers can idle for minutes between requests, killing keep-alive connections. Also, never silently swallow distribution failures - always track and alert on them.
|
||||
|
||||
### FFmpeg Path Escaping
|
||||
For subprocess without shell, FFmpeg filter paths need: apostrophes escaped as `'\\''`, special chars as `\\[char]`.
|
||||
|
||||
@@ -637,6 +679,9 @@ Langfuse v3 is built on OpenTelemetry. If `CallbackHandler()` is created without
|
||||
### Cold Start Mitigation
|
||||
Set `min-instances > 0` for Cloud Run services with heavy initialization.
|
||||
|
||||
### Never Call sync-over-async from FastAPI async Routes (Feb 2026)
|
||||
Sync methods that internally create new event loops (`asyncio.new_event_loop()` + `loop.run_until_complete()`) will **block the FastAPI event loop** when called from `async def` routes or background tasks. The response body gets queued but never flushed because the blocked loop can't process I/O — causing 20-36s endpoint latency instead of <1s. **Fix**: Either (a) call the underlying async client directly with `await` (preferred — e.g., `await flacfetch_client.download_by_id()`), or (b) wrap sync calls in `await asyncio.to_thread()` / `loop.run_in_executor()` to run them in a thread pool. The `nest_asyncio` library is NOT a reliable workaround — it patches CPython internals and can cause deadlocks. See `audio_search.py` and `youtube_download_service.py` for the correct async patterns.
|
||||
|
||||
---
|
||||
|
||||
## Data & Storage
|
||||
@@ -675,6 +720,9 @@ When adding alternative implementations (GCE vs local encoding), audit ALL side
|
||||
### External Response Validation
|
||||
Add defensive type checking for all external service responses. Lists vs dicts, missing fields cause cryptic failures.
|
||||
|
||||
### Brand Code Allocation Must Be Atomic (Feb 2026)
|
||||
Two concurrent jobs both got brand code `NOMADNP-0012` because `get_next_brand_code()` scanned Dropbox folders to find the next number — a classic TOCTOU race condition. Jobs processed 0.86s apart both saw the same state. **Fix**: `brand_code_service.py` uses Firestore transactions to atomically allocate codes. Counter doc per prefix (`NOMAD`, `NOMADNP`) with `next_number` and `recycled` pool. E2E cleanup recycles numbers via `recycle_brand_code()`.
|
||||
|
||||
---
|
||||
|
||||
## Frontend Patterns
|
||||
@@ -704,6 +752,17 @@ Use subdomain detection in middleware. Disable query param detection in producti
|
||||
### Middleware Mocking
|
||||
When mocking tenant middleware, patch both the middleware import path AND the service factory function.
|
||||
|
||||
### Resilient Remote Worker Interactions (Feb 2026)
|
||||
|
||||
When a Cloud Run poller calls a stateful GCE worker, deployments can kill the poller mid-encoding. The worker completes but nobody receives the result — the job gets permanently stuck. Worse, re-submitting gets a 409 because the worker's in-memory dict still has the job.
|
||||
|
||||
**Three-part fix pattern:**
|
||||
1. **Make worker endpoints idempotent** — return cached results for completed jobs, allow retry on failure, return status for in-progress jobs (instead of hard 409 reject)
|
||||
2. **Handle all response types on the caller side** — `cached` → return immediately, `in_progress` → join the existing poll, `accepted` → normal flow. On 409 fallback, check job status before giving up.
|
||||
3. **Add stuck-job detection** — flag jobs in `encoding` status >50 min without `updated_at` advancing. This catches the case where the poller dies entirely.
|
||||
|
||||
This generalizes the preview encoding pattern (`/encode-preview` was already idempotent; `/encode` was not).
|
||||
|
||||
---
|
||||
|
||||
## What We'd Do Differently
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
|
||||
## Known Issues
|
||||
|
||||
- CDG format generation requires additional style configuration
|
||||
(No known issues)
|
||||
|
||||
## Pending Work
|
||||
|
||||
@@ -42,6 +42,14 @@
|
||||
|
||||
## Recent Changes
|
||||
|
||||
- **Fix Event Loop Blocking in Audio Search Endpoints** (2026-02-28): Fixed `/api/audio-search/{job_id}/select` taking 20-36s to respond (should be <1s) and `/api/audio-search/search` sometimes taking 25-47s. **Root cause**: Async endpoints called sync methods that create new event loops via `loop.run_until_complete()`, blocking the FastAPI event loop — response body was queued but never flushed. **Fix**: RED/OPS and Spotify download paths now call `FlacfetchClient` async methods directly (matching `YouTubeDownloadService` pattern), generic downloads use `asyncio.to_thread()`, search endpoint uses `search_async()`. Also fixed `InsufficientCreditsError` occasionally returning 500 instead of 402 by using `isinstance()` check. Added 14 new tests. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#never-call-sync-over-async-from-fastapi-async-routes-feb-2026).
|
||||
|
||||
- **GDrive Cleanup Robustness + Brand Code Race Fix** (2026-02-27): Fixed duplicate brand codes appearing in the public Google Drive share after the daily E2E test (NOMAD-1271 appearing for both the test job "piri - dog" and real song "Hot Mulligan - Pop Shuvit"). **Root causes**: (1) `if gdrive_files:` was falsy for empty dict `{}` — when GDrive upload silently failed (pre-PR #417), the entire GDrive cleanup block was skipped, (2) Brand code was recycled immediately after Dropbox cleanup succeeded, without confirming GDrive was also clean — a new job could claim the recycled code while old GDrive files still existed. **Fixes**: Added `find_files_by_brand_code()` fallback to `GoogleDriveService` that searches CDG/MP4/MP4-720p subfolders by brand code prefix when tracked file IDs aren't available. `cleanup-distribution` endpoint now: (a) uses tracked file IDs (fast path) or falls back to brand_code search, (b) only recycles the brand code after **both** Dropbox AND GDrive are confirmed clean. Added `scripts/cleanup_test_job_gdrive.py` remediation script. Added 14 new tests (94% coverage on gdrive_service.py).
|
||||
|
||||
- **CDG Packaging Fail-Fast Validation** (2026-02-27): Fixed silent CDG generation failures where jobs completed with `enable_cdg=True` but no CDG ZIP was produced. **Root cause**: Jobs 5b6aba25 and 5161b069 had `instrumental_selection: custom` but before commit b671b83f, the orchestrator had no `custom` case — it fell through to `"Backing"` suffix. The CDG generator then hit a `FileNotFoundError` looking for the wrong filename, which was silently caught. **Fix**: (1) Orchestrator now validates CDG/TXT outputs after packaging stage and before encoding — if `enable_cdg=True` but no CDG ZIP was produced, the pipeline fails fast instead of silently continuing to expensive encoding, (2) Missing LRC file now raises when CDG/TXT is enabled instead of silently skipping, (3) Added `scripts/regenerate_cdg.py` remediation script for affected jobs. Removed "CDG requires additional style configuration" known issue (the nomad theme has complete CDG styles). Added 7 new tests for validation logic.
|
||||
|
||||
- **GCE Encoding Pipeline Resilience** (2026-02-26): Made encoding pipeline resilient to Cloud Run deployment interruptions. A deployment killed a poller mid-encoding, leaving job a03ad39c permanently stuck at `encoding` status. Three fixes: (1) GCE worker `/encode` endpoint now idempotent — returns cached results for completed jobs, allows retry on failure, returns status for in-progress (previously hard 409 reject), (2) `encoding_service.py` handles cached/in_progress responses and falls back to status check on 409, (3) Health service detects jobs stuck in `encoding` >50 min. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#resilient-remote-worker-interactions-feb-2026).
|
||||
|
||||
- **Private (Non-Published) Tracks** (2026-02-24): Added `is_private` flag on jobs for private/non-published track production. Private jobs upload to Dropbox `Tracks-NonPublished` folder with `NOMADNP` brand prefix, skip YouTube and Google Drive entirely, and send completion emails without the YouTube section. Available as a checkbox on all job creation tabs and as an admin toggle (auto-deletes outputs when toggling a completed job to private). See [archive/2026-02-24-private-tracks-plan.md](archive/2026-02-24-private-tracks-plan.md).
|
||||
|
||||
- **GCE Encoding Worker Version Sorting Fix** (2026-02-11): Fixed critical regression from PR #384 where alphabetical sorting caused encoder to use v0.99.9 instead of v0.116.1. **Root cause**: `sorted(wheels)[-1]` uses string comparison, not semantic versioning. String comparison puts "0.99.9" > "0.116.1" (because '9' > '1' in second position). **Impact**: Production encoder was running an extremely old version (v0.99.9 from months ago) instead of the latest (v0.116.1). **Fix**: Extract version from wheel filename using regex, sort by `packaging.version.Version` objects instead of strings. Added 10 comprehensive unit tests covering the exact regression case (0.99.9 vs 0.116.1), edge cases (empty list, invalid filenames), and complex version comparisons (major/minor/patch). Production now correctly selects the latest semantic version. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#semantic-version-sorting-feb-2026).
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
# Troubleshooting
|
||||
|
||||
Operational runbooks for known production issues.
|
||||
|
||||
---
|
||||
|
||||
## Job stuck at `encoding` status
|
||||
|
||||
**Cause:** A Cloud Run deployment killed the poller mid-encoding. The GCE worker finished but nobody received the result. The health service will flag this as `encoding_stuck` after 50 minutes.
|
||||
|
||||
**Recovery:**
|
||||
|
||||
```bash
|
||||
# 1. Confirm the job is flagged
|
||||
curl -s "https://api.nomadkaraoke.com/api/health/job-consistency" \
|
||||
-H "X-Admin-Token: $(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke)" \
|
||||
| python3 -m json.tool | grep -A3 "encoding_stuck"
|
||||
|
||||
# 2. Check what the GCE worker knows about the job
|
||||
WORKER_URL=$(gcloud secrets versions access latest --secret=encoding-worker-url --project=nomadkaraoke)
|
||||
WORKER_KEY=$(gcloud secrets versions access latest --secret=encoding-worker-api-key --project=nomadkaraoke)
|
||||
curl -s "$WORKER_URL/status/YOUR_JOB_ID" -H "X-API-Key: $WORKER_KEY" | python3 -m json.tool
|
||||
|
||||
# 3. Re-trigger the video worker — it will pick up the cached GCE result if encoding
|
||||
# already finished, or rejoin the poll if it's still running
|
||||
curl -X POST "https://api.nomadkaraoke.com/api/internal/workers/video" \
|
||||
-H "X-Admin-Token: $(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke)" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"job_id": "YOUR_JOB_ID"}'
|
||||
```
|
||||
|
||||
**Note:** SSH-restarting the encoding worker is **not needed** since v0.119.6 (PR #413). The `/encode` endpoint is now idempotent — re-triggering the video worker is sufficient.
|
||||
|
||||
---
|
||||
|
||||
## CDG/TXT packages missing from completed job
|
||||
|
||||
**Cause:** Before v0.119.7, CDG/TXT generation failures were silently caught. Jobs would complete with `enable_cdg=True` but no CDG ZIP in outputs. Fixed in v0.119.7 with fail-fast validation — new jobs will now fail loudly if CDG/TXT generation fails.
|
||||
|
||||
**Recovery** (for jobs that already completed without CDG/TXT):
|
||||
|
||||
```bash
|
||||
# Regenerate and distribute CDG/TXT packages for specific jobs
|
||||
GCS_BUCKET_NAME=karaoke-gen-storage-nomadkaraoke \
|
||||
GOOGLE_CLOUD_PROJECT=nomadkaraoke \
|
||||
python -m scripts.regenerate_cdg JOB_ID [JOB_ID ...]
|
||||
|
||||
# Example:
|
||||
GCS_BUCKET_NAME=karaoke-gen-storage-nomadkaraoke \
|
||||
GOOGLE_CLOUD_PROJECT=nomadkaraoke \
|
||||
python -m scripts.regenerate_cdg 5b6aba25 5161b069
|
||||
```
|
||||
|
||||
The script is idempotent — re-running it skips regeneration if the CDG ZIP already exists in GCS and proceeds to any missing distribution steps (GDrive, Dropbox).
|
||||
|
||||
---
|
||||
|
||||
## GCE encoding worker on wrong wheel version
|
||||
|
||||
**Cause:** Worker picks up a new deploy but doesn't restart automatically.
|
||||
|
||||
```bash
|
||||
# Check current wheel version
|
||||
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
|
||||
--command="curl -s http://localhost:8080/health | python3 -m json.tool"
|
||||
|
||||
# Restart to pick up latest wheel
|
||||
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
|
||||
--command="sudo systemctl restart encoding-worker"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Google Drive uploads missing (gdrive_files empty)
|
||||
|
||||
**Symptoms:** Jobs complete successfully but `state_data.gdrive_files` is empty `{}`. Cloud Run logs show `BrokenPipeError` or `SSL: UNEXPECTED_EOF_WHILE_READING`.
|
||||
|
||||
**Cause:** Stale HTTP connections in the singleton `GoogleDriveService`. Since v0.119.7, this is handled automatically with retry + connection reset.
|
||||
|
||||
**Backfill affected jobs:**
|
||||
```bash
|
||||
# Dry run - list affected jobs
|
||||
GCS_BUCKET_NAME=karaoke-gen-storage-nomadkaraoke \
|
||||
GOOGLE_CLOUD_PROJECT=nomadkaraoke \
|
||||
python scripts/backfill_gdrive_uploads.py --all-missing --dry-run
|
||||
|
||||
# Run for real
|
||||
GCS_BUCKET_NAME=karaoke-gen-storage-nomadkaraoke \
|
||||
GOOGLE_CLOUD_PROJECT=nomadkaraoke \
|
||||
python scripts/backfill_gdrive_uploads.py --all-missing
|
||||
|
||||
# Specific jobs
|
||||
python scripts/backfill_gdrive_uploads.py --job-ids JOB1,JOB2
|
||||
```
|
||||
@@ -0,0 +1,109 @@
|
||||
# GDrive Validator: Email Alerts, Manual Trigger, Post-Job Check
|
||||
|
||||
## Context
|
||||
|
||||
The GDrive validator cloud function checks the public Google Drive share for duplicate brand codes, invalid filenames, and sequence gaps. Currently it:
|
||||
- Runs once daily at 9 PM Eastern via Cloud Scheduler
|
||||
- Sends results via Pushbullet (easy to miss, no persistent record)
|
||||
- Cannot be easily triggered manually
|
||||
- Doesn't run after each job, so issues can persist for up to 24 hours before detection
|
||||
|
||||
The recent NOMAD-1271 duplicate brand code incident showed that daily checks aren't frequent enough — the duplicate existed for at least a day before manual discovery.
|
||||
|
||||
## Changes
|
||||
|
||||
### 1. Cloud Function: Replace Pushbullet with Email (SendGrid)
|
||||
|
||||
**File:** `infrastructure/functions/gdrive_validator/main.py`
|
||||
|
||||
- Replace `send_pushbullet_notification()` with `send_email_notification()` using SendGrid API
|
||||
- SendGrid API key already in Secret Manager as `sendgrid-api-key`
|
||||
- Send from `gen@nomadkaraoke.com` to `gen@nomadkaraoke.com`
|
||||
- Keep Pushbullet as a secondary fallback (both are cheap; belt + suspenders)
|
||||
- Add `SENDGRID_API_KEY` env var to the function
|
||||
|
||||
**File:** `infrastructure/functions/gdrive_validator/requirements.txt`
|
||||
|
||||
- Add `sendgrid>=6.0.0`
|
||||
|
||||
**File:** `infrastructure/__main__.py`
|
||||
|
||||
- Add `sendgrid-api-key` secret to the function's `secret_environment_variables`
|
||||
- Add `EMAIL_TO` env var = `gen@nomadkaraoke.com`
|
||||
|
||||
**File:** `infrastructure/functions/gdrive_validator/deploy.sh`
|
||||
|
||||
- Add `--set-secrets` entry for `SENDGRID_API_KEY=sendgrid-api-key:latest`
|
||||
- Add `--set-env-vars` entry for `EMAIL_TO=gen@nomadkaraoke.com`
|
||||
|
||||
### 2. Local Command: `check_public_share`
|
||||
|
||||
**File:** `scripts/check_public_share.py`
|
||||
|
||||
- Calls the Cloud Function via `gcloud functions call gdrive-validator --region=us-central1`
|
||||
- Parses the JSON response and prints formatted results to terminal
|
||||
- Exit code 0 = all clear, 1 = issues found, 2 = error
|
||||
- Supports `--json` flag for raw JSON output
|
||||
|
||||
### 3. Post-Job Trigger from Backend
|
||||
|
||||
**File:** `backend/services/gdrive_validator_client.py` (new)
|
||||
|
||||
- Lightweight client that calls the Cloud Function via HTTP with OIDC token
|
||||
- Uses `google.oauth2.id_token.fetch_id_token()` for authentication
|
||||
- Fire-and-forget pattern (never blocks or fails the job)
|
||||
- Logs the response but does not raise on validation issues (just notifies)
|
||||
|
||||
**File:** `backend/workers/video_worker_orchestrator.py`
|
||||
|
||||
- After `_run_notifications()` (line ~253), add a new call: `await self._trigger_gdrive_validation()`
|
||||
- Only triggers for non-private, non-test jobs (private jobs don't upload to public share)
|
||||
- Wrapped in try/except so validation failure never blocks job completion
|
||||
|
||||
**File:** `infrastructure/__main__.py`
|
||||
|
||||
- Add IAM binding: grant `karaoke-backend` service account `roles/cloudfunctions.invoker` on the gdrive-validator function
|
||||
- For Gen2 functions also need `roles/run.invoker` on the underlying Cloud Run service
|
||||
|
||||
**File:** `infrastructure/modules/iam/backend_sa.py`
|
||||
|
||||
- Add the Cloud Functions invoker permission
|
||||
|
||||
### 4. Pulumi Infrastructure Updates
|
||||
|
||||
All IAM and secret changes go through `infrastructure/__main__.py` — deployed automatically on merge to main.
|
||||
|
||||
## Comparison: Local Script vs Cloud Function
|
||||
|
||||
| Check | Local Script | Cloud Function |
|
||||
|-------|-------------|----------------|
|
||||
| Duplicate sequence numbers | ✅ | ✅ |
|
||||
| Invalid filenames | ✅ | ✅ |
|
||||
| Sequence gaps (with known gaps) | ✅ | ✅ |
|
||||
| Known gaps config | ✅ (identical) | ✅ (identical) |
|
||||
| ZIP contents (MP3+CDG) | ✅ | ❌ (expensive, needs file download) |
|
||||
| Video resolution (4K/720p) | ✅ | ❌ (expensive, needs file download) |
|
||||
| Render quality (pixel check) | ✅ | ❌ (expensive, needs ffmpeg) |
|
||||
| Bidirectional sync | ✅ (rclone) | ❌ (read-only) |
|
||||
|
||||
The cloud function correctly implements the "quick/cheap" checks (metadata-only via GDrive API). The expensive content checks (ZIP, resolution, pixel) belong in the local script since they require downloading files. No changes needed to align them.
|
||||
|
||||
## Files Modified
|
||||
|
||||
| File | Change |
|
||||
|------|--------|
|
||||
| `infrastructure/functions/gdrive_validator/main.py` | Add SendGrid email, keep Pushbullet as fallback |
|
||||
| `infrastructure/functions/gdrive_validator/requirements.txt` | Add `sendgrid` |
|
||||
| `infrastructure/functions/gdrive_validator/deploy.sh` | Add SendGrid secret + EMAIL_TO env var |
|
||||
| `infrastructure/__main__.py` | Add SendGrid secret to function, add backend invoker IAM |
|
||||
| `backend/services/gdrive_validator_client.py` | New: HTTP client to invoke cloud function |
|
||||
| `backend/workers/video_worker_orchestrator.py` | Add post-distribution GDrive validation trigger |
|
||||
| `scripts/check_public_share.py` | New: local command to trigger cloud function |
|
||||
|
||||
## Verification
|
||||
|
||||
1. Deploy cloud function with `./deploy.sh`
|
||||
2. Run `python scripts/check_public_share.py` — should print formatted results and receive email at gen@nomadkaraoke.com
|
||||
3. Trigger a test job or wait for the daily E2E test — after job completes, check Cloud Function logs to confirm it was invoked
|
||||
4. Check gen@nomadkaraoke.com inbox for the validation email
|
||||
5. Run `make test` to verify no regressions
|
||||
@@ -0,0 +1,75 @@
|
||||
# UX Overhaul - Master Plan
|
||||
|
||||
> **Status**: Phases 1-3 complete, Phase 4 remaining
|
||||
> **Created**: 2026-02-28
|
||||
> **Branch**: feat/sess-20260227-1637-ux-overhaul
|
||||
> **Worktree**: /Users/andrew/Projects/nomadkaraoke/karaoke-gen-ux-overhaul
|
||||
|
||||
## Overview
|
||||
|
||||
The karaoke generation platform was built for personal/power-user use. New users lack guidance at each stage of the multi-step process. This UX overhaul will improve guidance, simplify choices, and steer users toward the best outcomes.
|
||||
|
||||
## Phased Approach
|
||||
|
||||
The system has several distinct stages of human interaction, each requiring dedicated UX thought. We're breaking this into phases, with a detailed plan for each phase created through live UI walkthrough with screenshots and user feedback.
|
||||
|
||||
### Phase 1: Job Creation & Audio Input ✅
|
||||
**Plan**: [2026-02-28-ux-phase1-job-creation.md](2026-02-28-ux-phase1-job-creation.md)
|
||||
**Implementation**: [2026-02-28-ux-phase1-implementation.md](2026-02-28-ux-phase1-implementation.md)
|
||||
**Scope**: Restructure the job creation form as a guided flow. Steer users toward Search as the default path, with Upload/URL as fallbacks.
|
||||
**Done**: Removed "Skip lyrics review" checkbox, renamed Private label, built 3-step GuidedJobFlow wizard, title card preview, production E2E tests. Renamed "Find Audio" → "Choose Audio".
|
||||
|
||||
### Phase 2: Audio Source Selection ✅
|
||||
**Plan**: [2026-02-28-ux-phase2-audio-selection.md](2026-02-28-ux-phase2-audio-selection.md)
|
||||
**Scope**: Auto-select audio for simple cases, improve guidance for complex cases, build heuristics from real usage data.
|
||||
**Done**: 3-tier confidence system (perfect match / recommended / limited sources), guidance-first layout for Tier 3, validated against 41 production fixtures with unit tests.
|
||||
|
||||
### Phase 3: Lyrics Review ✅
|
||||
**Plan**: [2026-02-28-ux-phase3-lyrics-review.md](2026-02-28-ux-phase3-lyrics-review.md)
|
||||
**Scope**: Add onboarding, explain color coding, guide users through the correction workflow. This is the most complex screen.
|
||||
**Done**: Guidance panel replacing stats bar (collapsible, color coding legend, workflow tips), gap navigator with keyboard shortcuts (J/K), simplified toolbar with Advanced Mode toggle, hidden line numbers/delete icons by default, edit tracking system with low-friction feedback bar for transcription improvement data collection. 40 tests.
|
||||
|
||||
### Phase 4: Instrumental Review ← REMAINING
|
||||
**Plan**: [2026-02-28-ux-phase4-instrumental-review.md](2026-02-28-ux-phase4-instrumental-review.md)
|
||||
**Scope**: Explain what backing vocals are, guide the listen/decide flow, simplify the default case.
|
||||
|
||||
## Cross-Cutting Concerns
|
||||
|
||||
- **Remove "Skip lyrics review" checkbox** from UI (keep backend field for API/admin use)
|
||||
- **Rename "Private (non-published)"** to something clearer like "Private (no YouTube upload)"
|
||||
- **Auto-select heuristics training** - Pull last ~50 jobs, capture what audio the user would choose and why, codify into algorithm (may be a separate workstream touching flacfetch)
|
||||
|
||||
## Screenshots Captured
|
||||
|
||||
All screenshots saved in the worktree root during the walkthrough session:
|
||||
|
||||
### Phase 1: Job Creation
|
||||
- `phase1-job-creation-current.png` - Current job creation form
|
||||
- `phase1-filled-form.png` - Form filled with Coldplay - Parachutes
|
||||
- `phase1-job-created-awaiting-audio.png` - Job created, awaiting audio selection
|
||||
|
||||
### Phase 2: Audio Source Selection
|
||||
- `phase2-audio-search-results.png` - Audio search results dialog (Coldplay, top)
|
||||
- `phase2-audio-search-bottom.png` - Audio search results dialog (Coldplay, bottom)
|
||||
- `phase2-pony-bradshaw-results.png` - Audio search results for obscure track (Pony Bradshaw)
|
||||
|
||||
### Phase 3: Lyrics Review (Difficulty Spectrum)
|
||||
- `phase3-lyrics-review.png` / `phase3-lyrics-review-top.png` - Bon Jovi lyrics review (easy-medium, 94% anchored)
|
||||
- `phase3-lyrics-review-bottom.png` - Bon Jovi lyrics review (bottom/end of lyrics)
|
||||
- `phase3-bon-jovi-review.png` - Bon Jovi "It's My Life" (easy-medium: 94% anchored, 9 gaps, 18 words)
|
||||
- `phase3-silversun-pickups-review.png` - Silversun Pickups (medium: 84% anchored, 8 gaps, 32 words)
|
||||
- `phase3-steve-taylor-review.png` - Steve Taylor live (hard: 42% anchored, 20 gaps, 194 words, wrong reference lyrics)
|
||||
- `phase3-preview-dialog.png` - Preview Video dialog (transition from lyrics to instrumental review)
|
||||
|
||||
### Phase 4: Instrumental Review
|
||||
- `phase4-instrumental-review.png` - Instrumental review page (Coldplay - Parachutes, 4% backing vocals, Clean recommended)
|
||||
|
||||
## Test Jobs Used
|
||||
|
||||
| Track | ID | Difficulty | Stage |
|
||||
|-------|-----|-----------|-------|
|
||||
| Coldplay - Parachutes | a95023e8 | Easy | Progressed to instrumental review |
|
||||
| Bon Jovi - It's My Life | c235f6bd | Easy-Medium | At lyrics review |
|
||||
| Silversun Pickups - Well Thought Out Twinkles | 41026cfe | Medium | At lyrics review |
|
||||
| Pony Bradshaw - Jehovah | 3552d63d | Medium | At lyrics review |
|
||||
| Steve Taylor - Jim Morrisons Grave - Live | ce8f2901 | Hard | At lyrics review |
|
||||
@@ -0,0 +1,58 @@
|
||||
# Phase 1: Job Creation UX Overhaul - Implementation Record
|
||||
|
||||
Date: 2026-02-28
|
||||
|
||||
## What Was Done
|
||||
|
||||
### Increment 1: Quick Wins
|
||||
- Removed "Skip lyrics review (non-interactive)" checkbox from all 3 tabs in `JobSubmission.tsx`
|
||||
- Renamed "Private (non-published)" to "Private (no YouTube upload)" across all 3 tabs
|
||||
- Removed `nonInteractive` state variable and `non_interactive` from all submit handler payloads
|
||||
- Backend `non_interactive` field preserved for CLI/admin API use
|
||||
|
||||
### Increment 2: Guided Step Flow
|
||||
Replaced the tab-based `JobSubmission` with a new `GuidedJobFlow` wizard component.
|
||||
|
||||
#### New Files Created
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `lib/audio-search-utils.ts` | Extracted categorization logic shared between AudioSearchDialog and new flow |
|
||||
| `components/job/GuidedJobFlow.tsx` | Main orchestrator with step state management |
|
||||
| `components/job/steps/SongInfoStep.tsx` | Step 1: Artist & Title input |
|
||||
| `components/job/steps/AudioSourceStep.tsx` | Step 2: Auto-search + fallback upload/URL |
|
||||
| `components/job/steps/CustomizeStep.tsx` | Step 3: Title card preview + options |
|
||||
| `components/job/steps/ConfirmStep.tsx` | Step 4: Review & confirm |
|
||||
| `components/job/TitleCardPreview.tsx` | CSS mockup of title/end screens |
|
||||
|
||||
#### Modified Files
|
||||
| File | Change |
|
||||
|------|--------|
|
||||
| `components/job/JobSubmission.tsx` | Quick wins only (kept as reference) |
|
||||
| `components/audio-search/AudioSearchDialog.tsx` | Refactored to import from shared utils |
|
||||
| `app/app/page.tsx` | Swapped JobSubmission for GuidedJobFlow |
|
||||
|
||||
### Architecture Decisions
|
||||
|
||||
1. **Display overrides in Step 1**: The `searchAudio` API sets display_artist/display_title at creation time (not updateable after). So the display override toggle stays in Step 1 as a collapsible section, before the search is triggered.
|
||||
|
||||
2. **Privacy setting timing**: For search path, `is_private` is set during the `searchAudio` call in Step 2. Step 3 (Customize) shows the current value but changes there would need a backend `updateJob` call (which supports `is_private`). For upload/URL fallback paths, `is_private` is set at creation time.
|
||||
|
||||
3. **Upload/URL skip customize**: When users choose upload or URL fallback in Step 2, they skip directly to Step 4 (Confirm) since the title card preview is less relevant for these paths.
|
||||
|
||||
4. **Search polling**: AudioSourceStep polls `getAudioSearchResults` every 2 seconds (max 30 attempts = 60s) while waiting for the backend search to complete.
|
||||
|
||||
5. **Error handling**: Backend errors during search show the error message and immediately offer fallback options (Upload file / YouTube URL).
|
||||
|
||||
## Visual Testing Results
|
||||
|
||||
Screenshots saved in `docs/images/`:
|
||||
- `phase1-step1-initial.png` - Empty step 1 form
|
||||
- `phase1-step1-filled.png` - Form with "Queen - Bohemian Rhapsody"
|
||||
- `phase1-step1-display-override.png` - Display override section expanded
|
||||
- `phase1-step2-searching.png` - Search loading state with spinner
|
||||
- `phase1-step2-error-with-fallbacks.png` - Error handling with fallback options
|
||||
|
||||
## Test Results
|
||||
- All 323 Jest tests pass
|
||||
- Next.js build succeeds with no errors
|
||||
- Visual testing confirms all Step 1 and Step 2 UI renders correctly
|
||||
@@ -0,0 +1,93 @@
|
||||
# Phase 1: Job Creation & Audio Input - UX Plan
|
||||
|
||||
> **Status**: Feedback captured, ready for detailed design
|
||||
> **Screenshots**: `phase1-job-creation-current.png`, `phase1-filled-form.png`
|
||||
|
||||
## Current State
|
||||
|
||||
The job creation form at `/app` has:
|
||||
- **Three equal tabs**: Search / Upload / URL - no indication which is preferred or when to use each
|
||||
- **"Search For Audio Online"** heading with Artist/Title fields
|
||||
- **Note**: "Format these exactly as you want them on the title card and video filename" - confusing for users who don't know what "title card" means
|
||||
- **"Use different artist/title for title screen"** - collapsible, but unclear what it does
|
||||
- **"Skip lyrics review (non-interactive)"** - admin-only but visible, confusing
|
||||
- **"Private (non-published)"** - useful but wording is unclear
|
||||
- **"Search & Create Job"** button - creates job AND searches, then user must find the job in Recent Jobs and click "Select Audio" separately (split interaction)
|
||||
|
||||
## User Feedback
|
||||
|
||||
### Search should be strongly preferred
|
||||
> "We need to strongly steer users towards trying Search first as it provides high quality lossless audio which makes for a better karaoke track. Ideally they should only use Upload for tracks which aren't commercially/generally available online, and they should only use YouTube if the specific version they want a karaoke track for doesn't come up in the Search results (e.g. if it's a bootleg or specific live version or something indie which is only on YouTube)"
|
||||
|
||||
### Title card note is confusing
|
||||
> "Honestly I'd imagine this is kinda confusing to new users who may not even know what 'title screen' means."
|
||||
|
||||
### Restructure as guided flow
|
||||
> "I'm now wondering if it would be better to restructure it as a series of questions which leads the user to the job creation. That way we could give the user clearer guidance for each step and make the order make sense (e.g. do the audio search first, only fall back to youtube/upload if they couldn't find the exact version in the search results). If we did that the question about whether there should be a different artist/title for the title card could be answered as a separate question in this flow, with a dynamically generated preview image showing roughly what the title card would look like to help the user understand what it is."
|
||||
|
||||
### Remove "Skip lyrics review"
|
||||
> "Honestly I can't even remember why I added 'Skip lyrics review' as an option, we should probably remove that as I don't really think there's ever a legit reason for anyone to use that."
|
||||
|
||||
**Investigation result**: Added Dec 25, 2025 as CLI `-y` equivalent, refined to admin-only per-job option Jan 3, 2026 (PR #162). It's an admin/testing power tool that auto-completes review stages. The backend `non_interactive` field should stay for API/admin use, but the checkbox should be removed from the job creation form.
|
||||
|
||||
### Rename "Private" option
|
||||
> "The 'Private' option is definitely useful and important, we can probably make it even easier to understand by changing '(non-published)' to '(no public upload on YouTube)' or something"
|
||||
|
||||
## Proposed Design: Guided Step Flow
|
||||
|
||||
Replace the current tab-based form with a step-by-step guided flow:
|
||||
|
||||
### Step 1: "What song do you want to make a karaoke track for?"
|
||||
- Artist & Title fields (simple, friendly)
|
||||
- This is the same regardless of input method
|
||||
|
||||
### Step 2: "Find the audio"
|
||||
- Auto-search runs immediately with the artist/title from Step 1
|
||||
- Results appear inline (not in a separate modal after job creation)
|
||||
- "Best Choice" is prominently recommended (or auto-selected - see Phase 2)
|
||||
- If nothing found or wrong version: "Can't find it? Try a YouTube URL or upload your own audio file"
|
||||
- Upload and URL become **fallback options**, not equal peers
|
||||
|
||||
### Step 3: "How should it look?"
|
||||
- Title card preview (dynamically rendered) showing roughly what the title/end screens will look like
|
||||
- Option to override artist/title for display
|
||||
- Private toggle with clearer label: "Private (no YouTube upload)"
|
||||
- This step gives context for what "title card" actually means
|
||||
|
||||
### Step 4: Confirm & Create
|
||||
|
||||
## Key Technical Considerations
|
||||
|
||||
### Current flow (split interaction):
|
||||
```
|
||||
Form → "Search & Create Job" → Job created in backend → Job appears in Recent Jobs list
|
||||
→ User clicks "Select Audio" on job card → Modal dialog opens → User picks result → Job progresses
|
||||
```
|
||||
|
||||
### Proposed flow (unified):
|
||||
```
|
||||
Step 1 (artist/title) → Step 2 (search results inline, or fallback to upload/URL)
|
||||
→ Step 3 (title card preview, private toggle) → Step 4 (confirm) → Job created & processing
|
||||
```
|
||||
|
||||
The key complexity: currently the backend creates the job when the search is initiated. The guided flow might need to either:
|
||||
1. Still create the job early but hide that from the user (keep current backend flow, change frontend presentation)
|
||||
2. Defer job creation until the user confirms everything (would require backend changes)
|
||||
|
||||
Option 1 is probably simpler and lower-risk.
|
||||
|
||||
### Components affected:
|
||||
- `frontend/components/job/JobSubmission.tsx` - Main form (3 tab state objects, submit handlers)
|
||||
- `frontend/components/audio-search/AudioSearchDialog.tsx` - Currently a modal, would become inline
|
||||
- `frontend/components/job/JobCard.tsx` - Currently shows "Select Audio" button for awaiting jobs
|
||||
- `frontend/app/app/page.tsx` - Main dashboard layout (2-column: form + recent jobs)
|
||||
- `frontend/lib/api.ts` - `searchAudio()`, `getAudioSearchResults()`, `selectAudioResult()`
|
||||
|
||||
## Changes to Ship
|
||||
|
||||
1. **Remove "Skip lyrics review" checkbox** from all 3 tabs in JobSubmission.tsx (lines 325-348, 447-470, 607-630). Keep backend `non_interactive` field.
|
||||
2. **Rename "Private (non-published)"** to "Private (no YouTube upload)" or similar
|
||||
3. **Restructure form** as guided step flow (major change - needs detailed component design)
|
||||
4. **Title card preview** - dynamically generated preview showing what title screen looks like
|
||||
5. **Inline audio search results** - move from modal dialog to inline step in guided flow
|
||||
6. **Fallback positioning** - Upload/URL presented as fallbacks when Search doesn't find the right track
|
||||
@@ -0,0 +1,136 @@
|
||||
# Phase 2: Audio Source Selection - UX Plan
|
||||
|
||||
> **Status**: Implemented and verified with 41 production fixtures
|
||||
> **Screenshots**: `phase2-audio-search-results.png`, `phase2-audio-search-bottom.png`, `phase2-pony-bradshaw-results.png`
|
||||
|
||||
## Implementation Summary (2026-02-28)
|
||||
|
||||
### 3-Tier Confidence System
|
||||
Built in `frontend/lib/audio-search-utils.ts` and `frontend/components/job/steps/AudioSourceStep.tsx`:
|
||||
|
||||
- **Tier 1 ("Perfect match found")**: Green card, best result is lossless with 50+ seeders and no filename mismatch
|
||||
- **Tier 2 ("Recommended")**: Amber card with reasoning — has lossless options but not clearly ideal
|
||||
- **Tier 3 ("Limited sources found")**: Guidance-first layout — upload/URL fallback shown above search results
|
||||
|
||||
### Key Features
|
||||
- **Filename mismatch detection**: Compares search title against `target_file` (torrent/Spotify) or `title` (YouTube). Handles underscores as word separators, skips non-Latin scripts gracefully. Shows "Title match" / "Wrong track?" badges.
|
||||
- **Spotify separated from YouTube**: Own category with green styling, higher priority than YouTube in best-result selection
|
||||
- **Dynamic guidance tips**: The "Limited sources found" box only shows tips relevant to the actual result types found
|
||||
- **Color-coded view counts**: Green (1M+), amber (100K+), neutral for YouTube/Spotify results
|
||||
- **Availability tooltips**: User-friendly language ("may take a bit more time to prepare")
|
||||
|
||||
### Testing
|
||||
- 75 unit tests for `audio-search-utils.ts` (96%+ coverage)
|
||||
- 47 fixture confidence tests against 41 production search results
|
||||
- Fixture review tooling: `npm run fixtures:review-ui` for visual verification
|
||||
- E2E regression tests (25 tests) and production E2E tests (7 tests)
|
||||
|
||||
## Current State
|
||||
|
||||
The "Select Audio Source" modal dialog shows:
|
||||
- **Title**: "Select Audio Source v0.119.8 (N results across M categories)"
|
||||
- **Categories** (up to 9): BEST CHOICE, HI-RES 24-BIT, STUDIO ALBUMS, SINGLES, LIVE VERSIONS, COMPILATIONS, VINYL RIPS, YOUTUBE/LOSSY, OTHER
|
||||
- Each result shows: index number, quality badges (LOSSLESS, VINYL, YouTube), artist, title, format details, file size, availability badge (High/Medium/Low color-coded), album metadata, target filename
|
||||
- Each category shows 2-3 results by default with "+N more" expand button
|
||||
- Each result has a "Select" button
|
||||
|
||||
## Problems Identified
|
||||
|
||||
### Too much information / too much choice
|
||||
> "It's just too much information and probably too much choice for most users who just know what song they want a karaoke version of."
|
||||
|
||||
### Wrong songs appear in results
|
||||
- Coldplay "Parachutes" search returned "Everything's Not Lost", "High Speed", "Spies" (other songs from the same album or artist)
|
||||
- Pony Bradshaw "Jehovah" search returned "Van Gogh", "Josephine" (other songs by same artist)
|
||||
- The compilation results (#27, #28 for Coldplay) showed filename "Parachutes/03 - Spies.flac" - a different track entirely
|
||||
- Users need domain knowledge to evaluate these
|
||||
|
||||
### Availability badges unexplained
|
||||
- High (green), Medium (yellow/orange), Low (red) availability badges are shown but never explained
|
||||
- Users don't know that availability directly affects download success rate
|
||||
|
||||
### No guidance on what matters for karaoke
|
||||
- 24-bit vs 16-bit doesn't matter much for karaoke (vocals get removed anyway)
|
||||
- Vinyl rips may have surface noise that affects separation quality
|
||||
- Availability matters more than bit depth for reliability
|
||||
- Live versions will sound different from studio versions
|
||||
|
||||
## User Feedback
|
||||
|
||||
### Auto-select for simple cases
|
||||
> "For those simple/standard users who are making karaoke tracks which have commercially available releases which are easy to download (like this Coldplay example), we should probably just make the choice for the user and only show them this more complex set of alternate options if they explicitly click something to show more advanced options."
|
||||
|
||||
### Better guidance for advanced view
|
||||
> "There's also several gotchas which aren't communicated on this view at all, e.g. the fact that vinyl versions, live versions, or other songs entirely may show up (you have to check the filename makes sense for the song you wanted) so even if we keep this view as an 'advanced' or 'show more options' view in the UX rework, we should add better guidance to it to help users know what to look for."
|
||||
|
||||
### Obscure tracks are trickier
|
||||
For Pony Bradshaw - Jehovah (less popular track):
|
||||
- No "BEST CHOICE" section appeared
|
||||
- Only 3 categories: HI-RES 24-BIT (1, Low availability), STUDIO ALBUMS (4, Medium/Low), YOUTUBE/LOSSY (5)
|
||||
- User's choice: Studio Album #1 (Medium availability, 16bit CD) because "it's the most available (and thus will download the fastest) and 24bit input audio is overkill for karaoke"
|
||||
|
||||
### Build auto-select heuristics from real data
|
||||
> "In order to make the system reliably make a good default choice for the user, we probably ought to run searches for a bunch of input tracks with a variety of popularities (we could just look at the last 50 tracks I've actually made through this karaoke generator as they're already a pretty diverse mix) and for every track, capture what audio I would choose in this 'Select Audio Source' modal AND WHY, then use that reasoning information to build a system which auto-chooses for the user."
|
||||
|
||||
## Proposed Design
|
||||
|
||||
### Tier 1: Auto-Select (Simple Cases)
|
||||
When there's a clear winner (BEST CHOICE category with High availability):
|
||||
- **Auto-select it** and show the user a simple confirmation:
|
||||
- "We found a high-quality lossless version of this track from [Album / Year / Label]"
|
||||
- Small "See all options" or "Choose a different version" link for power users
|
||||
- This covers the majority of popular/commercially available tracks
|
||||
|
||||
### Tier 2: Recommended Pick (Medium Confidence)
|
||||
When there's no BEST CHOICE but there are reasonable lossless options:
|
||||
- **Highlight the recommended pick** with clear reasoning: "Recommended: Studio album version with reliable availability"
|
||||
- Show the recommendation prominently, with other options below in a collapsed "Other options" section
|
||||
- Add brief explanation of why this was chosen
|
||||
|
||||
### Tier 3: Manual Selection Required (Low Confidence)
|
||||
When results are very limited, all low availability, or no lossless options:
|
||||
- Show all results with guidance
|
||||
- Add contextual tips at the top:
|
||||
- "Check the filename matches your song title"
|
||||
- "Higher availability = more reliable download"
|
||||
- "Studio album versions typically produce the best karaoke results"
|
||||
- "Vinyl rips may have surface noise"
|
||||
- "YouTube is lower quality but works for rare/live tracks"
|
||||
|
||||
### Advanced View (Always Accessible)
|
||||
Keep the current full category view as an "Advanced options" panel:
|
||||
- Add guidance header explaining the gotchas
|
||||
- Add tooltips on availability badges explaining what they mean
|
||||
- Flag potentially wrong tracks (filename doesn't match search title)
|
||||
- Consider dimming or warning on results where the filename suggests a different song
|
||||
|
||||
## Auto-Select Heuristics Training Plan
|
||||
|
||||
### Data Collection
|
||||
1. Pull the last ~50 completed jobs from Firestore
|
||||
2. For each job that went through audio search:
|
||||
- Retrieve the cached search results (what options were available)
|
||||
- Record which result index was selected
|
||||
- Have the user annotate WHY that choice was made
|
||||
3. Categorize by popularity/availability patterns
|
||||
|
||||
### Heuristic Rules to Codify
|
||||
Based on walkthrough observations:
|
||||
1. **Availability > bit depth** for karaoke (failed download = start over, 24-bit is wasted)
|
||||
2. **Filename must match song title** (compilation results often have wrong tracks)
|
||||
3. **Prefer studio albums** over compilations, vinyl rips, live versions
|
||||
4. **Avoid vinyl rips** for karaoke (surface noise affects vocal separation)
|
||||
5. **YouTube/lossy is last resort** (lower quality, may be different arrangements)
|
||||
6. **When in doubt, pick highest availability** among lossless results
|
||||
|
||||
### Implementation
|
||||
- Could live in flacfetch's ranking logic (already has some of this)
|
||||
- Or as a frontend/backend layer that post-processes flacfetch results
|
||||
- Should be testable: given a set of search results, predict the correct selection
|
||||
|
||||
## Components Affected
|
||||
|
||||
- `frontend/components/audio-search/AudioSearchDialog.tsx` - Major refactor to add tiers
|
||||
- `frontend/lib/api.ts` - May need new endpoint or parameter for auto-select
|
||||
- Possibly `flacfetch` ranking algorithm (separate repo/workstream)
|
||||
- Backend may need a "confidence score" or "recommended index" in search results response
|
||||
@@ -0,0 +1,185 @@
|
||||
# Phase 3: Lyrics Review - UX Plan
|
||||
|
||||
> **Status**: Implemented
|
||||
> **Screenshots**: `phase3-lyrics-review-top.png`, `phase3-lyrics-review-bottom.png`
|
||||
|
||||
## Implementation Summary (2026-03-01)
|
||||
|
||||
### Guidance Panel (replaces stats bar)
|
||||
- `GuidancePanel.tsx` — collapsible panel with color coding legend, workflow tips
|
||||
- Stats hidden behind toggle (previously always visible, overwhelming for new users)
|
||||
- Contextual tips for common correction types (phantom words, mis-heard words, etc.)
|
||||
|
||||
### Gap Navigator
|
||||
- `GapNavigator.tsx` — "Gap 3 of 9" with prev/next buttons
|
||||
- Keyboard shortcuts: J (next gap), K (previous gap)
|
||||
- Auto-scrolls to gap and flashes the relevant words
|
||||
- Scoped to uncorrected gaps only
|
||||
|
||||
### Simplified Toolbar
|
||||
- Advanced Mode toggle (persisted in localStorage)
|
||||
- Default: hides line numbers, delete icons, power-user tools
|
||||
- Advanced: shows Find/Replace, Edit All, Undo Auto Corrections, Timing Offset
|
||||
|
||||
### Edit Tracking & Feedback System
|
||||
- `editLog.ts` — session-based edit log capturing all user edits (word changes, deletions, additions, find/replace, segment operations, reverts)
|
||||
- `EditFeedbackBar.tsx` — slim feedback bar above sticky footer, appears after single-word edits with contextual "why?" buttons (Mis-heard word, Wrong lyrics, Spelling/punctuation, etc.)
|
||||
- Auto-dismisses after 10 seconds, pauses timer while hovered
|
||||
- Edit logs submitted to backend on review completion for transcription model improvement
|
||||
- Replaces the old high-friction `CorrectionAnnotationModal` (9 categories, confidence slider — nobody used it)
|
||||
- Backend endpoints: `POST /api/jobs/{job_id}/edit-log` (GCS storage), `POST /api/review/{job_id}/v1/annotations` (fixed from stub)
|
||||
- 40 tests across frontend and backend
|
||||
|
||||
### Word Component Improvements
|
||||
- Active gap ring indicator (persistent highlight for currently navigated gap)
|
||||
- Color coding preserved: blue = matched/confident, orange = needs review
|
||||
|
||||
## Current State
|
||||
|
||||
The lyrics review page at `/app/jobs#/{jobId}/review` is the most complex screen in the app. It's a combined review flow (lyrics + instrumental selection in one session).
|
||||
|
||||
### Top Stats Bar
|
||||
Four cards showing:
|
||||
- **Correction Handlers** - collapsed section (unclear what this means)
|
||||
- **Anchor Sequences: 19 (94%)** - "Matched sections between transcription and reference", sub-stats: "Words in Anchors: 266", "Multi-source Matches: 19"
|
||||
- **Corrected Gaps: 0 (0%)** - "Successfully corrected sections", sub-stats: "Words Replaced: 0", "Words Added/Deleted: +0/-0"
|
||||
- **Uncorrected Gaps: 9 (6%)** - "Sections that may need manual review", sub-stats: "Words Uncorrected: 18", "Number of Gaps: 9"
|
||||
|
||||
### Toolbar
|
||||
- **Mode buttons**: Edit (selected), Highlight, Delete
|
||||
- **Actions**: Undo All, undo/redo arrows, Find/Replace, Edit All
|
||||
- **Secondary row**: Undo Auto Corrections, Timing Offset, Feedback On
|
||||
- **Playback**: Play button with timeline slider (0:00 to 3:44)
|
||||
|
||||
### Left Panel: Corrected Transcription
|
||||
- Numbered lines (0-49 for Bon Jovi example)
|
||||
- Each line has: line number, delete icon, play icon, lyrics text
|
||||
- **Text/Timeline toggle** at top
|
||||
- Words are color-coded (see Color Coding section below)
|
||||
|
||||
### Right Panel: Reference Lyrics
|
||||
- **Source tabs**: Lrclib (selected), Genius, Spotify, + New
|
||||
- Copy button next to "Reference Lyrics" heading
|
||||
- Reference text with color-coded highlights matching the left panel
|
||||
|
||||
### Bottom Bar (Sticky)
|
||||
- "Lyrics look good?" text
|
||||
- **"Preview Video"** pink button
|
||||
- After preview, user clicks "Proceed to Instrumental Review" (green button) to move to Phase 4
|
||||
|
||||
### Flow: Lyrics → Preview → Instrumental
|
||||
The combined review flow is:
|
||||
1. User reviews/corrects lyrics on this page
|
||||
2. User clicks "Preview Video" to generate a preview with their corrections
|
||||
3. User watches preview to verify sync
|
||||
4. User clicks "Proceed to Instrumental Review" to move to instrumental selection (Phase 4)
|
||||
|
||||
## User Feedback
|
||||
|
||||
### Stats Bar
|
||||
> "This whole section could probably be removed or hidden behind a 'Stats' toggle button or something. Maybe we could use the space in this section to give the user guidance on how to use the tool instead?"
|
||||
|
||||
### Toolbar
|
||||
> "Agreed re. 'no guidance on when to use which' but I'm not really sure how best to resolve that without making the UI even more cluttered/overwhelming. Maybe the section above could be sufficient to give the user guidance on these buttons too, if we can make smart/efficient use of the space. We should also ensure all buttons have really rich, helpful tooltips (but also consider mobile users who may not have access to tooltips)."
|
||||
|
||||
### Left Panel
|
||||
> "All users definitely need the play button beside lines, but the line numbers and delete icons should probably be hidden unless the user enables 'Advanced Mode' or something"
|
||||
|
||||
### Color Coding (User's Explanation)
|
||||
> "Blue means 'matched with reference lyrics, so most likely correct'. Orange means 'unable to match with reference lyrics, so needs to be reviewed and either edited or deleted'."
|
||||
>
|
||||
> "Generally the user should be focusing on the Corrected Transcription panel. Words which are highlighted in blue are highly likely to be correct, so the user should focus on the words which are highlighted in orange (the 'gaps')."
|
||||
|
||||
### Correction Workflow
|
||||
> "I immediately focus on the gaps (highlighted in orange), typically I click the play icon beside those lines to listen to what the singer actually sings in each segment, while visually trying to find the relevant part of the reference lyrics to advise me on what action to take. Then I'll click on the segment and either edit, merge, delete words as necessary, adjust word timings etc. till the lyrics in that segment are correct and well synced, then press enter/click save. I'll repeat that for every gap until I'm confident I've reviewed and corrected (where necessary) all gaps, then I'll hit preview and listen to the whole track once to ensure the sync is fine before proceeding to instrumental review."
|
||||
|
||||
### Common Types of Corrections Needed
|
||||
|
||||
**1. Phantom words (delete)**
|
||||
> "The transcription very commonly puts 'And' at the start of lines during an instrumental section, in which case that word just needs to be deleted by clicking on the segment and clicking the delete icon beside the word."
|
||||
|
||||
**2. Mis-heard words (edit)**
|
||||
> "In many cases, the transcription just has some mistakes where it mis-heard things."
|
||||
|
||||
**3. Stylistic differences (no action needed)**
|
||||
> "In some cases, they may notice it's just a stylistic difference (e.g. the transcription writes '22' whereas reference lyrics write 'twenty two') and there's no action required."
|
||||
|
||||
**4. Reference lyrics are imperfect too**
|
||||
> "Lyrics fetched from the internet are also not 100% accurate, and in some cases are not available at all, so the user should use their best judgement when making these corrections."
|
||||
|
||||
### Difficulty Varies Hugely by Track
|
||||
|
||||
**Easy tracks** (acoustic, country, clear vocals):
|
||||
> "Acoustic or country tracks or pretty much anything with simple clear vocals tend to be transcribed really well and there may be no gaps / corrections to be made at all, or only a couple."
|
||||
|
||||
**Hard tracks** (rock, screamo, unclear vocals):
|
||||
> "Hard rock, screamo, or anything where the vocals aren't super clear can be a challenge - in some bad cases the transcription may be more than 50% incorrect and there can be quite a lot of work to do to get it corrected."
|
||||
|
||||
### Concrete Examples from Walkthrough
|
||||
|
||||
5 tracks at lyrics review stage, showing the full difficulty spectrum:
|
||||
|
||||
| Track | ID | Difficulty | Notes |
|
||||
|-------|-----|-----------|-------|
|
||||
| Coldplay - Parachutes | a95023e8 | Easy | Short song, only 2 mistakes: phantom "And" to delete, "I" → "I'll" |
|
||||
| Bon Jovi - It's My Life | c235f6bd | Easy-Medium | Few gaps, some need no action ("wanna", "calling"), but "Love can't even look, you gotta" is clearly mis-heard |
|
||||
| Silversun Pickups - Well Thought Out Twinkles | 41026cfe | Medium | Several clear transcription errors, e.g. "Share about elliptic views" → "We share apocalyptic views" |
|
||||
| Pony Bradshaw - Jehovah | 3552d63d | Medium | Several clear errors, e.g. "In Dilla, town on fire" → "A dilettante on fire" |
|
||||
| Steve Taylor - Jim Morrisons Grave - Live | ce8f2901 | Hard | Live version from YouTube, whole spoken section at start before singing begins (needs bulk deletion), plus many transcription mistakes e.g. "Jim Morrison, cryin'" → "Jim Morrison's Grave" |
|
||||
|
||||
## Proposed Design
|
||||
|
||||
### Replace Stats Bar with Guidance Panel
|
||||
Use the stats bar space for user guidance instead:
|
||||
- Brief explanation of what this page is for
|
||||
- Color coding legend (blue = matched/confident, orange = needs review)
|
||||
- Quick workflow tip: "Focus on the orange highlighted words. Click the play button to listen, then click the word to edit."
|
||||
- Collapsible "Stats" section for power users who want the numbers
|
||||
- Consider making this dismissible after first visit (remember in localStorage)
|
||||
|
||||
### Toolbar Improvements
|
||||
- Rich, helpful tooltips on all buttons (important: also consider mobile users who can't hover)
|
||||
- Consider "Advanced Mode" toggle that shows/hides power-user tools
|
||||
- Default view: Edit mode, play button, undo/redo, Preview Video
|
||||
- Advanced view: adds Highlight, Delete, Find/Replace, Timing Offset, Edit All
|
||||
|
||||
### Left Panel Simplification
|
||||
- **Hide by default**: Line numbers, delete icons
|
||||
- **Show by default**: Play button, lyrics text with color coding
|
||||
- **Advanced Mode**: Shows line numbers, delete icons, and other power tools
|
||||
- Play button is essential for all users (core to the correction workflow)
|
||||
|
||||
### Guided Gap Review Mode
|
||||
Based on the user's workflow of stepping through gaps:
|
||||
- "Jump to next gap" button/shortcut
|
||||
- Auto-scroll to the next uncorrected gap
|
||||
- Highlight the corresponding section in reference lyrics
|
||||
- Show a count: "Gap 3 of 9" with prev/next navigation
|
||||
|
||||
### Color Coding Legend
|
||||
Persistent but minimal:
|
||||
- Small bar or badge near the top: "🔵 Matched with reference lyrics" | "🟠 Needs your review"
|
||||
- Or integrated into the guidance panel
|
||||
|
||||
### Contextual Tips for Common Corrections
|
||||
Based on the user's experience, show tips like:
|
||||
- "Phantom words: If you see an extra word like 'And' at the start of a line during music, delete it"
|
||||
- "Listen first: Click the play button to hear what's actually sung before editing"
|
||||
- "Reference lyrics aren't perfect either - use your best judgement"
|
||||
- "Stylistic differences (e.g. '22' vs 'twenty two') don't need correcting"
|
||||
|
||||
### Preview & Submit Flow
|
||||
- After correcting gaps, user clicks "Preview Video"
|
||||
- Preview plays; user verifies sync
|
||||
- "Proceed to Instrumental Review" button moves to Phase 4
|
||||
- This flow is already in place - just needs clearer labeling/guidance
|
||||
|
||||
## Components Affected
|
||||
|
||||
- `frontend/components/` - Need to explore the review components in detail
|
||||
- The review UI was originally a separate React+Vite+MUI app (~14k lines) consolidated into the main Next.js frontend in Jan 2026
|
||||
- Key route: `/app/jobs#/{jobId}/review` (hash-based routing)
|
||||
- Stats panel component (replace with guidance panel)
|
||||
- Toolbar component (add tooltips, advanced mode toggle)
|
||||
- Transcription line component (hide line numbers/delete by default)
|
||||
- Need to identify the "gap navigation" mechanism if one exists
|
||||
@@ -0,0 +1,147 @@
|
||||
# Phase 4: Instrumental Review - UX Plan
|
||||
|
||||
> **Status**: User feedback captured, ready for detailed design
|
||||
> **Screenshots**: `phase4-instrumental-review.png`
|
||||
|
||||
## Current State
|
||||
|
||||
The instrumental review page at `/app/jobs#/{jobId}/instrumental` is the final human review stage before the video is generated. It's a significantly simpler interface than the lyrics review.
|
||||
|
||||
### Header Bar
|
||||
- Track name (e.g., "Coldplay - Parachutes")
|
||||
- Three stat badges:
|
||||
- **Segments count** (e.g., "1 segments")
|
||||
- **Backing vocals percentage** (e.g., "4% backing vocals")
|
||||
- **Recommendation badge** (e.g., "Clean recommended" in pink)
|
||||
|
||||
### Audio Player Controls
|
||||
- Play button with current time / total duration
|
||||
- **4 audio toggle buttons**: Original, Backing Vocals Only, Pure Instrumental, Instrumental + Backing
|
||||
- Upload button (for uploading a custom instrumental)
|
||||
- Zoom levels: 1x, 2x, 4x
|
||||
- Keyboard shortcuts: Shift+drag (select region), Space (play/pause)
|
||||
|
||||
### Waveform Visualization
|
||||
- Two waveform tracks displayed with timeline markers
|
||||
- Shows the audio waveform across the full track duration
|
||||
- Interactive - users can click/drag to select regions
|
||||
|
||||
### Mute Regions Panel (Bottom Left)
|
||||
- "Click segments below or Shift + drag on waveform"
|
||||
- Shows detected backing vocal segments as clickable buttons (e.g., "0:38 - 0:40")
|
||||
- Users can add custom mute regions by shift+dragging on the waveform
|
||||
|
||||
### Final Selection Panel (Bottom Right)
|
||||
Three options:
|
||||
1. **Clean Instrumental** - "No backing vocals" - shown with "Recommended" badge when backing vocals % is low
|
||||
2. **With Backing Vocals** - "All backing vocals included"
|
||||
3. **Original Audio** - "Full original with lead vocals"
|
||||
- **"Confirm & Continue"** button to finalize and proceed to video generation
|
||||
|
||||
## User Feedback
|
||||
|
||||
### No explanation of what this page is or how to use it
|
||||
> "The page doesn't explain to the user what it is and how to use it."
|
||||
|
||||
The page drops users in with no context about what they're looking at or what they should do.
|
||||
|
||||
### The Primary Workflow Users Should Follow
|
||||
|
||||
> "The primary thing they should start with is clicking on any pink sections in the waveform to listen to how the backing vocals sound, decide if the backing vocals should be kept or if we should use the clean instrumental, and if they want the backing vocals but they're mixed in with lead vocals for some sections of the song, they need to create a custom instrumental by shift-dragging on the waveform to mark sections for muting, clicking 'Create Custom', then selecting that."
|
||||
|
||||
The intended workflow is:
|
||||
1. **Listen to pink sections** - Click on any pink (backing vocal) segments in the waveform to hear what they sound like
|
||||
2. **Decide: keep or remove?** - Do the backing vocals add to the karaoke experience, or should they be removed?
|
||||
3. **If keeping backing vocals but some sections have lead vocal bleed**: Create a custom instrumental by shift+dragging on the waveform to mark problem sections for muting, click "Create Custom", then select that custom version
|
||||
4. **Confirm selection** and proceed to video generation
|
||||
|
||||
### Three Possible Outcomes
|
||||
|
||||
**Simple case (clean)**: Backing vocals are minimal or unwanted → select "Clean Instrumental" → Confirm
|
||||
|
||||
**Simple case (keep backing vocals)**: Backing vocals sound good throughout → select "With Backing Vocals" → Confirm
|
||||
|
||||
**Complex case (custom)**: Want backing vocals but some sections have lead vocal bleed → mute problem sections → "Create Custom" → select custom version → Confirm
|
||||
|
||||
## Observations
|
||||
|
||||
### What's Working Well
|
||||
- The page is much simpler than lyrics review - clear, focused decision
|
||||
- The recommendation badge ("Clean recommended") is helpful
|
||||
- Audio toggle buttons let users A/B test between instrumental options
|
||||
- Waveform visualization with pink backing vocal highlights is intuitive once you know what to do
|
||||
|
||||
### Potential Issues for New Users
|
||||
|
||||
#### 1. No onboarding or explanation
|
||||
- Users don't know what "backing vocals" are or why this review exists
|
||||
- No guidance on what to do first (click pink sections to listen)
|
||||
- The whole purpose of the page needs a brief introduction
|
||||
|
||||
#### 2. The workflow isn't communicated
|
||||
- Users should start by listening to backing vocal segments, but nothing tells them this
|
||||
- The decision tree (clean vs backing vocals vs custom) isn't explained
|
||||
- "Create Custom" workflow (shift+drag → mute → create) is completely hidden
|
||||
|
||||
#### 3. Mute Regions / Custom Instrumental flow is opaque
|
||||
- "Click segments below or Shift + drag on waveform" is the only guidance
|
||||
- Users don't know WHEN they'd want to mute regions (answer: when backing vocals are mixed with lead vocal bleed in specific sections)
|
||||
- The connection between muting sections and creating a "Custom" instrumental option isn't clear
|
||||
|
||||
#### 4. What does "Upload" do?
|
||||
- The Upload button near the audio toggles isn't explained
|
||||
- Needs a tooltip or brief explanation
|
||||
|
||||
#### 5. Stats badges are jargon-heavy
|
||||
- "1 segments" and "4% backing vocals" - what do these mean to a new user?
|
||||
- The recommendation badge is good, but the numbers without context may confuse
|
||||
|
||||
## Proposed Design
|
||||
|
||||
### Replace Stats Bar with Guided Onboarding (Consistent with Phase 3 Approach)
|
||||
Replace the stats badges area with a guidance panel that explains:
|
||||
- **What this page is**: "This is where you choose your karaoke backing track. The AI has separated the vocals from the music - now you decide which version sounds best."
|
||||
- **What backing vocals are**: "Backing vocals are the harmony/chorus voices that sing along with the lead singer. Some karaoke singers prefer to keep them for guidance, others prefer a pure instrumental."
|
||||
- **What to do first**: "Start by clicking the pink highlighted sections in the waveform to listen to the backing vocals. Then decide if you want to keep them or use a clean instrumental."
|
||||
- Collapsible/dismissible for returning users (localStorage)
|
||||
|
||||
### Guided Workflow Steps
|
||||
Present the decision as a clear flow:
|
||||
|
||||
**Step 1: Listen** - "Click the pink sections in the waveform to hear the backing vocals"
|
||||
|
||||
**Step 2: Decide** - "Do you want to keep the backing vocals?"
|
||||
- If no → "Select Clean Instrumental and confirm"
|
||||
- If yes → "Select With Backing Vocals. If some sections have unwanted lead vocal bleed, continue to Step 3"
|
||||
|
||||
**Step 3 (if needed): Customize** - "Shift+drag on the waveform to mark sections where lead vocals bleed through, then click Create Custom to generate a custom instrumental with those sections muted"
|
||||
|
||||
### Contextual Recommendations
|
||||
The system already recommends "Clean" when backing vocals are low (4%). Enhance this with:
|
||||
- Clear reasoning: "We recommend Clean Instrumental because this track has very few backing vocals (4%)"
|
||||
- For tracks with high backing vocal %, recommend "With Backing Vocals" and explain why
|
||||
|
||||
### Simplify for Default Users
|
||||
- For tracks where the recommendation is clear, the guidance could suggest just confirming
|
||||
- "This track has very little backing vocal content. We recommend the Clean Instrumental - confirm below to proceed!"
|
||||
- The "Confirm & Continue" button could be more prominent
|
||||
|
||||
### Improve Mute Regions / Custom Instrumental UX
|
||||
- Explain WHEN users need this: "If you want backing vocals but notice lead vocal bleed in certain sections, you can mute those sections to create a custom mix"
|
||||
- Make the shift+drag → Create Custom flow more discoverable
|
||||
- Consider a more guided approach: "Hear something that shouldn't be there? Shift+drag over that section to mark it for muting"
|
||||
|
||||
## Flow After Confirmation
|
||||
|
||||
After clicking "Confirm & Continue":
|
||||
- The job progresses to video generation
|
||||
- This is the final human review step
|
||||
- User then waits for the video to be rendered and can download it
|
||||
|
||||
## Components Affected
|
||||
|
||||
- Need to explore the instrumental review components in detail
|
||||
- Key route: `/app/jobs#/{jobId}/instrumental` (hash-based routing)
|
||||
- The audio player with waveform visualization
|
||||
- The backing vocal detection/mute regions system
|
||||
- The final selection radio group
|
||||
|
After Width: | Height: | Size: 162 KiB |
|
After Width: | Height: | Size: 150 KiB |
|
After Width: | Height: | Size: 161 KiB |
|
After Width: | Height: | Size: 131 KiB |
|
After Width: | Height: | Size: 141 KiB |
|
After Width: | Height: | Size: 132 KiB |
|
After Width: | Height: | Size: 103 KiB |
|
After Width: | Height: | Size: 154 KiB |
|
After Width: | Height: | Size: 91 KiB |
|
After Width: | Height: | Size: 185 KiB |
|
After Width: | Height: | Size: 155 KiB |
|
After Width: | Height: | Size: 155 KiB |
|
After Width: | Height: | Size: 83 KiB |
|
After Width: | Height: | Size: 168 KiB |
|
After Width: | Height: | Size: 167 KiB |
|
After Width: | Height: | Size: 59 KiB |
@@ -4,3 +4,11 @@ playwright-report-prod/
|
||||
# Use this pattern for ad-hoc testing: test-*.local.{js,cjs,mjs,ts}
|
||||
test-*.local.*
|
||||
debug-*.local.*
|
||||
|
||||
# Search result fixtures (large raw data, regenerate with fetch-search-fixtures.mjs)
|
||||
# The index.json is tracked for reference; individual result files are gitignored
|
||||
e2e/fixtures/data/search-results/*.json
|
||||
!e2e/fixtures/data/search-results/index.json
|
||||
|
||||
# Chrome profile for interactive fixture review (auto-created by playwright.review.config.ts)
|
||||
.review-profile/
|
||||
@@ -2,7 +2,7 @@
|
||||
* Unit tests for job-status.ts utility functions
|
||||
*/
|
||||
|
||||
import { getJobStep, formatStepIndicator, isBlockingStatus, getJobProgressPercent, getJobPriority, sortJobsByPriority, getDisplayJobs, JobStep } from '../lib/job-status';
|
||||
import { getJobStep, formatStepIndicator, isBlockingStatus, isNotifiableBlockingStatus, getJobProgressPercent, getJobPriority, sortJobsByPriority, getDisplayJobs, JobStep } from '../lib/job-status';
|
||||
import type { Job } from '../lib/api';
|
||||
|
||||
// Helper to create a minimal Job object for testing
|
||||
@@ -426,6 +426,41 @@ describe('isBlockingStatus', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('isNotifiableBlockingStatus', () => {
|
||||
it('returns true for awaiting_review', () => {
|
||||
expect(isNotifiableBlockingStatus('awaiting_review')).toBe(true);
|
||||
});
|
||||
|
||||
it('returns true for in_review', () => {
|
||||
expect(isNotifiableBlockingStatus('in_review')).toBe(true);
|
||||
});
|
||||
|
||||
it('returns true for awaiting_instrumental_selection', () => {
|
||||
expect(isNotifiableBlockingStatus('awaiting_instrumental_selection')).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false for awaiting_audio_selection (user already engaged)', () => {
|
||||
expect(isNotifiableBlockingStatus('awaiting_audio_selection')).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false for non-blocking statuses', () => {
|
||||
expect(isNotifiableBlockingStatus('pending')).toBe(false);
|
||||
expect(isNotifiableBlockingStatus('downloading')).toBe(false);
|
||||
expect(isNotifiableBlockingStatus('complete')).toBe(false);
|
||||
expect(isNotifiableBlockingStatus('failed')).toBe(false);
|
||||
});
|
||||
|
||||
it('handles case insensitivity', () => {
|
||||
expect(isNotifiableBlockingStatus('AWAITING_REVIEW')).toBe(true);
|
||||
expect(isNotifiableBlockingStatus('AWAITING_AUDIO_SELECTION')).toBe(false);
|
||||
});
|
||||
|
||||
it('handles null/undefined gracefully', () => {
|
||||
expect(isNotifiableBlockingStatus(null as unknown as string)).toBe(false);
|
||||
expect(isNotifiableBlockingStatus(undefined as unknown as string)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getJobProgressPercent', () => {
|
||||
it('returns 0 for terminal states (step 0)', () => {
|
||||
const job = createJob('failed');
|
||||
|
||||
@@ -19,7 +19,7 @@ import { Music2, RefreshCw, Loader2, Moon, Sun, Eye, EyeOff } from "lucide-react
|
||||
import { sortJobsByPriority, getDisplayJobs } from "@/lib/job-status"
|
||||
import { WarmingUpLoader } from "@/components/WarmingUpLoader"
|
||||
import { JobCard } from "@/components/job"
|
||||
import { JobSubmission } from "@/components/job/JobSubmission"
|
||||
import { GuidedJobFlow } from "@/components/job/GuidedJobFlow"
|
||||
import { AuthStatus } from "@/components/auth"
|
||||
import { AutoProcessor } from "@/components/AutoProcessor"
|
||||
import { VersionFooter } from "@/components/version-footer"
|
||||
@@ -57,10 +57,16 @@ function AppPageContent() {
|
||||
// Check if user is admin (for exclude_test parameter)
|
||||
const isAdmin = user?.role === "admin" || user?.email?.endsWith("@nomadkaraoke.com")
|
||||
|
||||
// Derive displayed jobs from allJobs + display limit + filter (instant, no re-fetch)
|
||||
// Filter out in-progress search jobs (managed by the guided flow, not standalone cards)
|
||||
const visibleJobs = useMemo(
|
||||
() => allJobs.filter(job => job.status !== 'awaiting_audio_selection'),
|
||||
[allJobs]
|
||||
)
|
||||
|
||||
// Derive displayed jobs from visibleJobs + display limit + filter (instant, no re-fetch)
|
||||
const { displayedJobs: jobs, totalFetched } = useMemo(
|
||||
() => getDisplayJobs(allJobs, jobLimit, hideCompleted),
|
||||
[allJobs, jobLimit, hideCompleted]
|
||||
() => getDisplayJobs(visibleJobs, jobLimit, hideCompleted),
|
||||
[visibleJobs, jobLimit, hideCompleted]
|
||||
)
|
||||
|
||||
// Memoize loadJobs for use with visibility refresh
|
||||
@@ -236,11 +242,11 @@ function AppPageContent() {
|
||||
<CardHeader>
|
||||
<CardTitle style={{ color: 'var(--text)' }}>Create Karaoke Video</CardTitle>
|
||||
<CardDescription style={{ color: 'var(--text-muted)' }}>
|
||||
Upload an audio file, provide a YouTube URL, or search for audio by artist & title
|
||||
Turn any song into a karaoke video with synced lyrics
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<JobSubmission onJobCreated={loadJobs} />
|
||||
<GuidedJobFlow onJobCreated={loadJobs} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type React from "react"
|
||||
import type { Metadata } from "next"
|
||||
import localFont from "next/font/local"
|
||||
import { ThemeProvider } from "@/components/theme-provider"
|
||||
import { TenantProvider } from "@/components/tenant-provider"
|
||||
import { ImpersonationBannerWrapper } from "@/components/impersonation-banner-wrapper"
|
||||
@@ -7,6 +8,14 @@ import { ServiceWorkerRegistration } from "@/components/service-worker-registrat
|
||||
import { GoogleAnalytics } from "@/components/google-analytics"
|
||||
import "./globals.css"
|
||||
|
||||
// AvenirNext Bold - matches the font used in actual Nomad theme title card generation
|
||||
// (karaoke_gen/resources/AvenirNext-Bold.ttf)
|
||||
const titleCardFont = localFont({
|
||||
src: "../public/fonts/AvenirNext-Bold.ttf",
|
||||
display: "swap",
|
||||
variable: "--font-title-card",
|
||||
})
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Nomad Karaoke: Generator",
|
||||
description: "Generate professional karaoke videos with AI-powered vocal separation and synchronized lyrics",
|
||||
@@ -28,7 +37,7 @@ export default function RootLayout({
|
||||
}>) {
|
||||
return (
|
||||
<html lang="en" suppressHydrationWarning>
|
||||
<body className="font-sans antialiased" style={{ background: 'var(--bg)', color: 'var(--text)' }}>
|
||||
<body className={`font-sans antialiased ${titleCardFont.variable}`} style={{ background: 'var(--bg)', color: 'var(--text)' }}>
|
||||
<GoogleAnalytics />
|
||||
<ServiceWorkerRegistration />
|
||||
<ThemeProvider
|
||||
|
||||
@@ -1,10 +1,20 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect, useMemo } from "react"
|
||||
import { api, AudioSearchResult } from "@/lib/api"
|
||||
import { api } from "@/lib/api"
|
||||
import {
|
||||
ExtendedAudioSearchResult,
|
||||
groupResults,
|
||||
getDisplayName,
|
||||
formatCount,
|
||||
formatMetadata,
|
||||
formatQuality,
|
||||
getAvailabilityLabel,
|
||||
checkFilenameMismatch,
|
||||
} from "@/lib/audio-search-utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"
|
||||
import { Loader2, Music2, ChevronDown, ChevronUp } from "lucide-react"
|
||||
import { Loader2, Music2, ChevronDown, ChevronUp, Lightbulb } from "lucide-react"
|
||||
|
||||
// Version from pyproject.toml (single source of truth)
|
||||
const APP_VERSION = process.env.NEXT_PUBLIC_APP_VERSION || "0.0.0"
|
||||
@@ -14,117 +24,16 @@ interface AudioSearchDialogProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onSelect: () => void
|
||||
searchTitle?: string
|
||||
}
|
||||
|
||||
// Extended result type to include all backend fields
|
||||
interface ExtendedAudioSearchResult extends AudioSearchResult {
|
||||
channel?: string
|
||||
view_count?: number
|
||||
formatted_duration?: string
|
||||
formatted_size?: string
|
||||
release_type?: string
|
||||
label?: string
|
||||
edition_info?: string
|
||||
target_file?: string
|
||||
quality_data?: {
|
||||
format?: string
|
||||
bit_depth?: number
|
||||
sample_rate?: number
|
||||
bitrate?: number
|
||||
media?: string
|
||||
}
|
||||
}
|
||||
|
||||
// Category configuration matching flacfetch
|
||||
interface CategoryConfig {
|
||||
name: string
|
||||
maxDisplay: number
|
||||
color: string
|
||||
borderColor: string
|
||||
}
|
||||
|
||||
const CATEGORY_CONFIG: Record<string, CategoryConfig> = {
|
||||
'BEST CHOICE': { name: 'BEST CHOICE', maxDisplay: 3, color: 'text-amber-400', borderColor: 'border-amber-500/30' },
|
||||
'HI-RES 24-BIT': { name: 'HI-RES 24-BIT', maxDisplay: 3, color: 'text-purple-400', borderColor: 'border-purple-500/30' },
|
||||
'STUDIO ALBUMS': { name: 'STUDIO ALBUMS', maxDisplay: 3, color: 'text-blue-400', borderColor: 'border-blue-500/30' },
|
||||
'SINGLES': { name: 'SINGLES', maxDisplay: 2, color: 'text-cyan-400', borderColor: 'border-cyan-500/30' },
|
||||
'LIVE VERSIONS': { name: 'LIVE VERSIONS', maxDisplay: 2, color: 'text-pink-400', borderColor: 'border-pink-500/30' },
|
||||
'COMPILATIONS': { name: 'COMPILATIONS', maxDisplay: 2, color: 'text-teal-400', borderColor: 'border-teal-500/30' },
|
||||
'VINYL RIPS': { name: 'VINYL RIPS', maxDisplay: 2, color: 'text-orange-400', borderColor: 'border-orange-500/30' },
|
||||
'YOUTUBE/LOSSY': { name: 'YOUTUBE/LOSSY', maxDisplay: 3, color: 'text-red-400', borderColor: 'border-red-500/30' },
|
||||
'OTHER': { name: 'OTHER', maxDisplay: 3, color: 'text-muted-foreground', borderColor: 'border-border' },
|
||||
}
|
||||
|
||||
const CATEGORY_ORDER = [
|
||||
'BEST CHOICE',
|
||||
'HI-RES 24-BIT',
|
||||
'STUDIO ALBUMS',
|
||||
'SINGLES',
|
||||
'LIVE VERSIONS',
|
||||
'COMPILATIONS',
|
||||
'VINYL RIPS',
|
||||
'YOUTUBE/LOSSY',
|
||||
'OTHER'
|
||||
]
|
||||
|
||||
// Categorize a single result based on flacfetch logic
|
||||
function categorizeResult(result: ExtendedAudioSearchResult): string {
|
||||
const isLossless = result.is_lossless === true
|
||||
const is24Bit = result.quality_data?.bit_depth === 24
|
||||
const seeders = result.seeders ?? 0
|
||||
const provider = result.provider?.toLowerCase() ?? ''
|
||||
const releaseType = result.release_type?.toLowerCase() ?? ''
|
||||
const media = result.quality_data?.media?.toLowerCase() ?? ''
|
||||
|
||||
// YouTube and lossy sources
|
||||
if (provider === 'youtube' || !isLossless) {
|
||||
return 'YOUTUBE/LOSSY'
|
||||
}
|
||||
|
||||
// Best choice (50+ seeders, lossless)
|
||||
if (isLossless && seeders >= 50) {
|
||||
return 'BEST CHOICE'
|
||||
}
|
||||
|
||||
// Hi-res 24-bit
|
||||
if (isLossless && is24Bit) {
|
||||
return 'HI-RES 24-BIT'
|
||||
}
|
||||
|
||||
// Vinyl rips
|
||||
if (isLossless && media === 'vinyl') {
|
||||
return 'VINYL RIPS'
|
||||
}
|
||||
|
||||
// Live versions
|
||||
if (isLossless && (releaseType === 'live album' || releaseType === 'bootleg' || releaseType.includes('live'))) {
|
||||
return 'LIVE VERSIONS'
|
||||
}
|
||||
|
||||
// Compilations
|
||||
if (isLossless && (releaseType === 'compilation' || releaseType === 'soundtrack' || releaseType === 'anthology')) {
|
||||
return 'COMPILATIONS'
|
||||
}
|
||||
|
||||
// Singles/EPs
|
||||
if (isLossless && (releaseType === 'single' || releaseType === 'ep')) {
|
||||
return 'SINGLES'
|
||||
}
|
||||
|
||||
// Studio albums
|
||||
if (isLossless && (releaseType === 'album' || !releaseType)) {
|
||||
return 'STUDIO ALBUMS'
|
||||
}
|
||||
|
||||
return 'OTHER'
|
||||
}
|
||||
|
||||
export function AudioSearchDialog({ jobId, open, onClose, onSelect }: AudioSearchDialogProps) {
|
||||
export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle }: AudioSearchDialogProps) {
|
||||
const [results, setResults] = useState<ExtendedAudioSearchResult[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [isSelecting, setIsSelecting] = useState<number | null>(null)
|
||||
const [error, setError] = useState("")
|
||||
const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set())
|
||||
const [showGuidance, setShowGuidance] = useState(false)
|
||||
|
||||
// Debug: Log component version on mount
|
||||
useEffect(() => {
|
||||
@@ -137,6 +46,7 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect }: AudioSearc
|
||||
console.log(`[AudioSearchDialog v${APP_VERSION}] Dialog opened for job: ${jobId}`)
|
||||
loadResults()
|
||||
setExpandedCategories(new Set()) // Reset expanded state
|
||||
setShowGuidance(false)
|
||||
}
|
||||
}, [open, jobId])
|
||||
|
||||
@@ -158,31 +68,7 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect }: AudioSearc
|
||||
}
|
||||
|
||||
// Group results by category
|
||||
const groupedResults = useMemo(() => {
|
||||
const groups: Record<string, ExtendedAudioSearchResult[]> = {}
|
||||
|
||||
for (const result of results) {
|
||||
const category = categorizeResult(result)
|
||||
if (!groups[category]) {
|
||||
groups[category] = []
|
||||
}
|
||||
groups[category].push(result)
|
||||
}
|
||||
|
||||
// Sort by category order
|
||||
const sortedGroups: Array<{ category: string; results: ExtendedAudioSearchResult[]; config: CategoryConfig }> = []
|
||||
for (const cat of CATEGORY_ORDER) {
|
||||
if (groups[cat] && groups[cat].length > 0) {
|
||||
sortedGroups.push({
|
||||
category: cat,
|
||||
results: groups[cat],
|
||||
config: CATEGORY_CONFIG[cat]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return sortedGroups
|
||||
}, [results])
|
||||
const groupedResults = useMemo(() => groupResults(results), [results])
|
||||
|
||||
// Count total categories
|
||||
const totalCategories = groupedResults.length
|
||||
@@ -214,51 +100,6 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect }: AudioSearc
|
||||
})
|
||||
}
|
||||
|
||||
// Get display name - use channel for YouTube, artist for others
|
||||
function getDisplayName(result: ExtendedAudioSearchResult): string {
|
||||
if (result.provider === "YouTube" && result.channel) {
|
||||
return result.channel
|
||||
}
|
||||
return result.artist || ""
|
||||
}
|
||||
|
||||
// Format views/seeders compactly
|
||||
function formatCount(count?: number): string {
|
||||
if (!count && count !== 0) return "-"
|
||||
if (count >= 1000000) return `${(count / 1000000).toFixed(1)}M`
|
||||
if (count >= 1000) return `${(count / 1000).toFixed(1)}K`
|
||||
return count.toString()
|
||||
}
|
||||
|
||||
// Format release metadata line
|
||||
function formatMetadata(result: ExtendedAudioSearchResult): string {
|
||||
const parts: string[] = []
|
||||
|
||||
if (result.release_type) parts.push(result.release_type)
|
||||
if (result.year) parts.push(result.year.toString())
|
||||
if (result.label) parts.push(result.label)
|
||||
if (result.edition_info) parts.push(result.edition_info)
|
||||
if (result.quality_data?.media) parts.push(result.quality_data.media)
|
||||
|
||||
return parts.length > 0 ? `[${parts.join(' / ')}]` : ''
|
||||
}
|
||||
|
||||
// Get quality display string
|
||||
function formatQuality(result: ExtendedAudioSearchResult): string {
|
||||
if (result.quality) return result.quality
|
||||
|
||||
const qd = result.quality_data
|
||||
if (!qd) return '-'
|
||||
|
||||
const parts: string[] = []
|
||||
if (qd.format) parts.push(qd.format)
|
||||
if (qd.bit_depth) parts.push(`${qd.bit_depth}bit`)
|
||||
if (qd.bitrate) parts.push(`${qd.bitrate}kbps`)
|
||||
if (qd.media) parts.push(qd.media)
|
||||
|
||||
return parts.join(' ') || '-'
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="max-w-7xl w-[95vw] max-h-[90vh] flex flex-col bg-card border-border !p-0 gap-0 overflow-hidden">
|
||||
@@ -272,6 +113,29 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect }: AudioSearc
|
||||
</DialogTitle>
|
||||
</div>
|
||||
|
||||
{/* Guidance header (collapsed by default) */}
|
||||
{!isLoading && results.length > 0 && (
|
||||
<div className="px-4 py-1.5 border-b border-border bg-secondary/30">
|
||||
<button
|
||||
onClick={() => setShowGuidance(!showGuidance)}
|
||||
className="flex items-center gap-1.5 text-[10px] text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<Lightbulb className="w-3 h-3" />
|
||||
Tips for choosing
|
||||
{showGuidance ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
|
||||
</button>
|
||||
{showGuidance && (
|
||||
<ul className="text-[10px] text-muted-foreground mt-1.5 ml-5 space-y-0.5 pb-1">
|
||||
<li>Check the filename matches your song title</li>
|
||||
<li>Green availability badge = more reliable download</li>
|
||||
<li>Studio album versions produce the best karaoke results</li>
|
||||
<li>Avoid vinyl rips (surface noise affects separation)</li>
|
||||
<li>YouTube is a last resort — lossless sources sound better</li>
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="px-4 py-2 text-xs text-red-400 bg-red-500/10 border-b border-border">
|
||||
{error}
|
||||
@@ -322,89 +186,112 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect }: AudioSearc
|
||||
|
||||
{/* Results in category */}
|
||||
<div className="divide-y divide-slate-700/50">
|
||||
{displayResults.map((result) => (
|
||||
<div
|
||||
key={result.index}
|
||||
className="px-3 py-1.5 hover:bg-secondary/50 flex items-center gap-2 text-xs"
|
||||
>
|
||||
{/* Index */}
|
||||
<span className="w-5 text-muted-foreground font-mono shrink-0 text-[10px]">
|
||||
{result.index + 1}.
|
||||
</span>
|
||||
{displayResults.map((result) => {
|
||||
const mismatch = searchTitle ? checkFilenameMismatch(searchTitle, result) : null
|
||||
const hasMismatch = mismatch?.isMismatch ?? false
|
||||
|
||||
{/* Main content - 2 lines */}
|
||||
<div className="flex-1 min-w-0">
|
||||
{/* Line 1: badges + artist + title + quality + size + availability */}
|
||||
<div className="flex items-center gap-1 flex-wrap">
|
||||
{result.is_lossless && (
|
||||
<span className="text-[8px] px-1 py-0.5 rounded bg-green-600/20 text-green-400 font-medium">
|
||||
LOSSLESS
|
||||
return (
|
||||
<div
|
||||
key={result.index}
|
||||
className={`px-3 py-1.5 hover:bg-secondary/50 flex items-center gap-2 text-xs ${
|
||||
hasMismatch ? 'opacity-60' : ''
|
||||
}`}
|
||||
>
|
||||
{/* Index */}
|
||||
<span className="w-5 text-muted-foreground font-mono shrink-0 text-[10px]">
|
||||
{result.index + 1}.
|
||||
</span>
|
||||
|
||||
{/* Main content - 2 lines */}
|
||||
<div className="flex-1 min-w-0">
|
||||
{/* Line 1: badges + artist + title + quality + size + availability */}
|
||||
<div className="flex items-center gap-1 flex-wrap">
|
||||
{result.is_lossless && (
|
||||
<span className="text-[8px] px-1 py-0.5 rounded bg-green-600/20 text-green-400 font-medium">
|
||||
LOSSLESS
|
||||
</span>
|
||||
)}
|
||||
{result.quality_data?.media?.toLowerCase() === 'vinyl' && (
|
||||
<span className="text-[8px] px-1 py-0.5 rounded bg-red-600/20 text-red-400 font-medium">
|
||||
VINYL
|
||||
</span>
|
||||
)}
|
||||
{result.provider === "YouTube" && (
|
||||
<span className="text-[8px] px-1 py-0.5 rounded font-medium bg-red-600/20 text-red-400">
|
||||
YouTube
|
||||
</span>
|
||||
)}
|
||||
{hasMismatch && (
|
||||
<span
|
||||
title={`Expected "${searchTitle}" but filename is "${mismatch!.filename}"${mismatch!.suggestedTrack ? ` (looks like "${mismatch!.suggestedTrack}")` : ''}`}
|
||||
className="text-[8px] px-1 py-0.5 rounded font-medium bg-yellow-600/20 text-yellow-400 cursor-help"
|
||||
>
|
||||
Wrong track?
|
||||
</span>
|
||||
)}
|
||||
<span className="text-green-400 font-medium">{getDisplayName(result)}</span>
|
||||
<span className="text-muted-foreground">-</span>
|
||||
<span className="text-foreground">{result.title}</span>
|
||||
<span className={`text-[10px] ${result.is_lossless ? "text-green-400" : "text-muted-foreground"}`}>
|
||||
({formatQuality(result)})
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground">{result.formatted_size || '-'}</span>
|
||||
{result.seeders !== undefined && result.seeders !== null ? (
|
||||
(() => {
|
||||
const { text, tooltip } = getAvailabilityLabel(result.seeders)
|
||||
return (
|
||||
<span
|
||||
title={tooltip}
|
||||
className={`text-[8px] px-1 py-0.5 rounded font-medium cursor-help ${
|
||||
result.seeders >= 50 ? 'bg-green-600/20 text-green-400' :
|
||||
result.seeders >= 10 ? 'bg-yellow-600/20 text-yellow-400' :
|
||||
'bg-red-600/20 text-red-400'
|
||||
}`}
|
||||
>
|
||||
{text} availability
|
||||
</span>
|
||||
)
|
||||
})()
|
||||
) : result.view_count !== undefined ? (
|
||||
<span className={`text-[8px] px-1 py-0.5 rounded font-medium ${
|
||||
result.view_count >= 1000000 ? 'bg-green-600/20 text-green-400' :
|
||||
result.view_count >= 10000 ? 'bg-yellow-600/20 text-yellow-400' :
|
||||
'bg-muted text-muted-foreground'
|
||||
}`}>
|
||||
{formatCount(result.view_count)} views
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{/* Line 2: metadata + filename */}
|
||||
{(formatMetadata(result) || result.target_file) && (
|
||||
<div className="flex items-center gap-1.5 text-[10px] text-muted-foreground">
|
||||
{formatMetadata(result) && (
|
||||
<span className="truncate">{formatMetadata(result)}</span>
|
||||
)}
|
||||
{result.target_file && (
|
||||
<span className="font-mono truncate">"{result.target_file}"</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{result.quality_data?.media?.toLowerCase() === 'vinyl' && (
|
||||
<span className="text-[8px] px-1 py-0.5 rounded bg-red-600/20 text-red-400 font-medium">
|
||||
VINYL
|
||||
</span>
|
||||
)}
|
||||
{result.provider === "YouTube" && (
|
||||
<span className="text-[8px] px-1 py-0.5 rounded font-medium bg-red-600/20 text-red-400">
|
||||
YouTube
|
||||
</span>
|
||||
)}
|
||||
<span className="text-green-400 font-medium">{getDisplayName(result)}</span>
|
||||
<span className="text-muted-foreground">-</span>
|
||||
<span className="text-foreground">{result.title}</span>
|
||||
<span className={`text-[10px] ${result.is_lossless ? "text-green-400" : "text-muted-foreground"}`}>
|
||||
({formatQuality(result)})
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground">{result.formatted_size || '-'}</span>
|
||||
{result.seeders !== undefined && result.seeders !== null ? (
|
||||
<span className={`text-[8px] px-1 py-0.5 rounded font-medium ${
|
||||
result.seeders >= 50 ? 'bg-green-600/20 text-green-400' :
|
||||
result.seeders >= 10 ? 'bg-yellow-600/20 text-yellow-400' :
|
||||
'bg-red-600/20 text-red-400'
|
||||
}`}>
|
||||
{result.seeders >= 50 ? 'High' : result.seeders >= 10 ? 'Medium' : 'Low'} availability
|
||||
</span>
|
||||
) : result.view_count !== undefined ? (
|
||||
<span className={`text-[8px] px-1 py-0.5 rounded font-medium ${
|
||||
result.view_count >= 1000000 ? 'bg-green-600/20 text-green-400' :
|
||||
result.view_count >= 10000 ? 'bg-yellow-600/20 text-yellow-400' :
|
||||
'bg-muted text-muted-foreground'
|
||||
}`}>
|
||||
{formatCount(result.view_count)} views
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{/* Line 2: metadata + filename */}
|
||||
{(formatMetadata(result) || result.target_file) && (
|
||||
<div className="flex items-center gap-1.5 text-[10px] text-muted-foreground">
|
||||
{formatMetadata(result) && (
|
||||
<span className="truncate">{formatMetadata(result)}</span>
|
||||
)}
|
||||
{result.target_file && (
|
||||
<span className="font-mono truncate">"{result.target_file}"</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{/* Select button */}
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => handleSelect(result.index)}
|
||||
disabled={isSelecting !== null}
|
||||
className="w-14 h-6 text-[9px] bg-amber-600 hover:bg-amber-500 text-foreground px-2 shrink-0"
|
||||
>
|
||||
{isSelecting === result.index ? (
|
||||
<Loader2 className="w-3 h-3 animate-spin" />
|
||||
) : (
|
||||
"Select"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Select button */}
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => handleSelect(result.index)}
|
||||
disabled={isSelecting !== null}
|
||||
className="w-14 h-6 text-[9px] bg-amber-600 hover:bg-amber-500 text-foreground px-2 shrink-0"
|
||||
>
|
||||
{isSelecting === result.index ? (
|
||||
<Loader2 className="w-3 h-3 animate-spin" />
|
||||
) : (
|
||||
"Select"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { Lightbulb, X } from "lucide-react"
|
||||
import type { BackingVocalAnalysis, AudibleSegment } from "@/lib/api"
|
||||
|
||||
interface InstrumentalGuidancePanelProps {
|
||||
analysis: BackingVocalAnalysis
|
||||
audibleSegments: AudibleSegment[]
|
||||
}
|
||||
|
||||
export function InstrumentalGuidancePanel({
|
||||
analysis,
|
||||
audibleSegments,
|
||||
}: InstrumentalGuidancePanelProps) {
|
||||
const [guidanceDismissed, setGuidanceDismissed] = useState(() => {
|
||||
if (typeof window === "undefined") return false
|
||||
return localStorage.getItem("instrumentalReviewGuidanceDismissed") === "true"
|
||||
})
|
||||
|
||||
const handleDismiss = () => {
|
||||
setGuidanceDismissed(true)
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.setItem("instrumentalReviewGuidanceDismissed", "true")
|
||||
}
|
||||
}
|
||||
|
||||
const handleShowTips = () => {
|
||||
setGuidanceDismissed(false)
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.removeItem("instrumentalReviewGuidanceDismissed")
|
||||
}
|
||||
}
|
||||
|
||||
const isCleanRecommended = analysis.recommended_selection === "clean"
|
||||
const percentage = analysis.audible_percentage
|
||||
const hasSegments = audibleSegments.length > 0
|
||||
|
||||
if (guidanceDismissed) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 text-xs">
|
||||
<button
|
||||
className="text-amber-500 hover:text-amber-400 transition-colors"
|
||||
onClick={handleShowTips}
|
||||
>
|
||||
Show tips
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Simple case: clean recommended with low backing vocals
|
||||
if (isCleanRecommended && percentage < 10) {
|
||||
return (
|
||||
<div className="flex items-start gap-2 p-2.5 rounded-md bg-amber-500/10 border border-amber-500/20">
|
||||
<Lightbulb className="h-4 w-4 text-amber-500 shrink-0 mt-0.5" />
|
||||
<div className="text-xs text-muted-foreground flex-1 leading-relaxed space-y-1.5">
|
||||
<p>
|
||||
<strong>Choose your karaoke backing track.</strong> The AI separated
|
||||
the vocals from the music — now pick which version sounds best.
|
||||
</p>
|
||||
<p>
|
||||
This track has very little backing vocal content ({percentage.toFixed(0)}%).
|
||||
We recommend the <strong>Clean Instrumental</strong> — just confirm
|
||||
below to proceed.
|
||||
</p>
|
||||
<p className="text-muted-foreground/70">
|
||||
Want to hear the difference? Use the audio buttons above to compare,
|
||||
or click the{" "}
|
||||
<span className="inline-block w-2 h-2 rounded-full bg-pink-500/60 align-middle" />{" "}
|
||||
pink sections in the waveform to listen to the backing vocals.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
className="text-muted-foreground hover:text-foreground transition-colors shrink-0"
|
||||
onClick={handleDismiss}
|
||||
aria-label="Dismiss tip"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Complex case: backing vocals present, needs review
|
||||
return (
|
||||
<div className="flex items-start gap-2 p-2.5 rounded-md bg-amber-500/10 border border-amber-500/20">
|
||||
<Lightbulb className="h-4 w-4 text-amber-500 shrink-0 mt-0.5" />
|
||||
<div className="text-xs text-muted-foreground flex-1 leading-relaxed space-y-1.5">
|
||||
<p>
|
||||
<strong>Choose your karaoke backing track.</strong> The AI separated
|
||||
the vocals from the music — now pick which version sounds best.
|
||||
</p>
|
||||
<p>
|
||||
<strong>Backing vocals</strong> are the harmony/chorus voices that sing
|
||||
along with the lead. Some karaoke singers prefer to keep them for guidance,
|
||||
others prefer a clean instrumental.
|
||||
</p>
|
||||
<div className="space-y-1 pl-2 border-l-2 border-amber-500/30">
|
||||
<p>
|
||||
<strong>Step 1:</strong> Click the{" "}
|
||||
<span className="inline-block w-2 h-2 rounded-full bg-pink-500/60 align-middle" />{" "}
|
||||
pink sections in the waveform to hear the backing vocals
|
||||
{hasSegments && ` (${audibleSegments.length} detected)`}.
|
||||
</p>
|
||||
<p>
|
||||
<strong>Step 2:</strong> Decide — keep them or use the clean
|
||||
instrumental? Use the audio toggle buttons above to compare.
|
||||
</p>
|
||||
<p>
|
||||
<strong>Step 3</strong> (if needed): If you want backing vocals but
|
||||
some sections have unwanted lead vocal bleed,{" "}
|
||||
<kbd className="px-1 py-0.5 rounded bg-muted text-[0.65rem] font-mono">
|
||||
Shift
|
||||
</kbd>
|
||||
+drag on the waveform to mark those sections, then click{" "}
|
||||
<strong>Create Custom</strong>.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
className="text-muted-foreground hover:text-foreground transition-colors shrink-0"
|
||||
onClick={handleDismiss}
|
||||
aria-label="Dismiss tip"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import { WaveformViewer } from "./WaveformViewer"
|
||||
import { MuteRegionEditor } from "./MuteRegionEditor"
|
||||
import { SelectionOptions } from "./SelectionOptions"
|
||||
import { CustomUpload } from "./CustomUpload"
|
||||
import { InstrumentalGuidancePanel } from "./InstrumentalGuidancePanel"
|
||||
|
||||
interface InstrumentalSelectorProps {
|
||||
job: Job
|
||||
@@ -78,6 +79,12 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
const [isShiftHeld, setIsShiftHeld] = useState(false)
|
||||
const [isAudioLoading, setIsAudioLoading] = useState(false)
|
||||
|
||||
// Hover highlight state
|
||||
const [hoveredItem, setHoveredItem] = useState<{
|
||||
type: "region" | "segment"
|
||||
index: number
|
||||
} | null>(null)
|
||||
|
||||
// Derived state
|
||||
const hasOriginal = analysisData?.has_original ?? false
|
||||
const hasWithBacking = !!analysisData?.audio_urls.with_backing
|
||||
@@ -86,6 +93,13 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
[analysisData?.analysis.audible_segments]
|
||||
)
|
||||
|
||||
const highlightedTimeRange = useMemo(() => {
|
||||
if (!hoveredItem) return null
|
||||
const source = hoveredItem.type === "region" ? muteRegions : audibleSegments
|
||||
const item = source[hoveredItem.index]
|
||||
return item ? { start: item.start_seconds, end: item.end_seconds } : null
|
||||
}, [hoveredItem, muteRegions, audibleSegments])
|
||||
|
||||
// Toggle play/pause - defined early so it can be used in keyboard shortcuts
|
||||
const togglePlayPause = useCallback(() => {
|
||||
const audio = audioRef.current
|
||||
@@ -543,36 +557,27 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
const amplitudes = waveformData?.amplitudes ?? []
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-screen bg-background p-4 gap-3 overflow-hidden">
|
||||
<div className="flex flex-col min-h-screen bg-background p-2 md:p-4 gap-2 md:gap-3">
|
||||
{/* Header */}
|
||||
<header className="flex items-center justify-between flex-shrink-0">
|
||||
<header className="flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between flex-shrink-0">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-lg font-semibold flex items-center gap-2">
|
||||
<img
|
||||
src="https://gen.nomadkaraoke.com/nomad-karaoke-logo.svg"
|
||||
alt="Nomad Karaoke"
|
||||
className="h-10"
|
||||
className="h-8 md:h-10"
|
||||
onError={(e) => {
|
||||
e.currentTarget.style.display = "none"
|
||||
}}
|
||||
/>
|
||||
Instrumental Review
|
||||
<span className="sm:hidden">Review</span>
|
||||
<span className="hidden sm:inline">Instrumental Review</span>
|
||||
</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
<span className="text-xs md:text-sm text-muted-foreground truncate">
|
||||
{job.artist} {job.artist && job.title ? "-" : ""} {job.title}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{audibleSegments.length > 0 && (
|
||||
<>
|
||||
<span className="px-2.5 py-1 rounded-full text-xs bg-secondary text-muted-foreground">
|
||||
{audibleSegments.length} segments
|
||||
</span>
|
||||
<span className="px-2.5 py-1 rounded-full text-xs bg-secondary text-muted-foreground">
|
||||
{analysisData?.analysis.audible_percentage.toFixed(0)}% backing vocals
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
<span
|
||||
className={`px-2.5 py-1 rounded-full text-xs ${
|
||||
analysisData?.analysis.recommended_selection === "clean"
|
||||
@@ -582,20 +587,28 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
>
|
||||
{analysisData?.analysis.recommended_selection === "clean"
|
||||
? "Clean recommended"
|
||||
: "Review needed"}
|
||||
: "Review backing vocals"}
|
||||
</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Guidance panel */}
|
||||
{analysisData && (
|
||||
<InstrumentalGuidancePanel
|
||||
analysis={analysisData.analysis}
|
||||
audibleSegments={audibleSegments}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Waveform Player */}
|
||||
<div className="flex-1 flex flex-col bg-card border border-border rounded-xl overflow-hidden min-h-0">
|
||||
<div className="min-h-[200px] md:min-h-[250px] lg:flex-1 lg:min-h-0 flex flex-col bg-card border border-border rounded-xl overflow-hidden">
|
||||
{/* Toolbar */}
|
||||
<div className="flex items-center justify-between px-4 py-2.5 bg-secondary border-b border-border gap-3 flex-shrink-0 flex-wrap">
|
||||
<div className="flex items-center justify-between px-2 md:px-4 py-2 md:py-2.5 bg-secondary border-b border-border gap-3 flex-shrink-0 flex-wrap">
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
size="icon"
|
||||
onClick={togglePlayPause}
|
||||
className="rounded-full w-8 h-8"
|
||||
className="rounded-full w-9 h-9 md:w-8 md:h-8"
|
||||
>
|
||||
{isPlaying ? (
|
||||
<Pause className="w-4 h-4" />
|
||||
@@ -620,7 +633,6 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
uploadedFilename={uploadedFilename}
|
||||
isLoading={isAudioLoading}
|
||||
/>
|
||||
<CustomUpload onUpload={handleUpload} isUploading={isUploading} />
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
@@ -630,7 +642,7 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
key={level}
|
||||
type="button"
|
||||
onClick={() => setZoomLevel(level)}
|
||||
className={`w-7 h-7 rounded text-xs font-medium transition-colors ${
|
||||
className={`w-9 h-9 md:w-7 md:h-7 rounded text-xs font-medium transition-colors ${
|
||||
zoomLevel === level
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "text-muted-foreground hover:bg-secondary hover:text-foreground"
|
||||
@@ -640,13 +652,13 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
<span className="hidden md:inline text-[10px] text-muted-foreground">
|
||||
<kbd className="px-1.5 py-0.5 bg-background border border-border rounded text-[10px] font-mono">
|
||||
Shift
|
||||
</kbd>
|
||||
+drag
|
||||
</span>
|
||||
<kbd className="px-1.5 py-0.5 bg-background border border-border rounded text-[10px] font-mono">
|
||||
<kbd className="hidden md:inline px-1.5 py-0.5 bg-background border border-border rounded text-[10px] font-mono">
|
||||
Space
|
||||
</kbd>
|
||||
</div>
|
||||
@@ -664,6 +676,7 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
onSeek={seekTo}
|
||||
onRegionCreate={addRegion}
|
||||
isShiftHeld={isShiftHeld}
|
||||
highlightedTimeRange={highlightedTimeRange}
|
||||
/>
|
||||
{isAudioLoading && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-background/50 backdrop-blur-sm">
|
||||
@@ -674,37 +687,54 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Time axis */}
|
||||
<div className="flex justify-between px-3 py-1 text-[10px] text-muted-foreground bg-black/40 flex-shrink-0">
|
||||
<span>0:00</span>
|
||||
<span>{formatTime(duration * 0.25)}</span>
|
||||
<span>{formatTime(duration * 0.5)}</span>
|
||||
<span>{formatTime(duration * 0.75)}</span>
|
||||
<span>{formatTime(duration)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Hidden audio element */}
|
||||
<audio ref={audioRef} src={getAudioUrl()} className="hidden" />
|
||||
|
||||
{/* Bottom section */}
|
||||
<div className="flex gap-3 flex-shrink-0">
|
||||
{/* Mute regions panel */}
|
||||
<MuteRegionEditor
|
||||
regions={muteRegions}
|
||||
audibleSegments={audibleSegments}
|
||||
hasCustom={hasCustom}
|
||||
isCreatingCustom={isCreatingCustom}
|
||||
onRemoveRegion={removeRegion}
|
||||
onClearAll={clearAllRegions}
|
||||
onCreateCustom={handleCreateCustom}
|
||||
onSeekTo={seekTo}
|
||||
onAddSegment={addSegmentAsRegion}
|
||||
/>
|
||||
<div className="flex flex-col lg:flex-row gap-2 md:gap-3 flex-shrink-0">
|
||||
{/* Left column: Custom Mix + Alternate Instrumental */}
|
||||
<div className="flex flex-col gap-2 md:gap-3 lg:flex-1 lg:min-w-0">
|
||||
<MuteRegionEditor
|
||||
regions={muteRegions}
|
||||
audibleSegments={audibleSegments}
|
||||
hasCustom={hasCustom}
|
||||
isCreatingCustom={isCreatingCustom}
|
||||
onRemoveRegion={removeRegion}
|
||||
onClearAll={clearAllRegions}
|
||||
onCreateCustom={handleCreateCustom}
|
||||
onSeekTo={seekTo}
|
||||
onAddSegment={addSegmentAsRegion}
|
||||
onHoverRegion={(index) =>
|
||||
setHoveredItem(index !== null ? { type: "region", index } : null)
|
||||
}
|
||||
onHoverSegment={(index) =>
|
||||
setHoveredItem(index !== null ? { type: "segment", index } : null)
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Selection panel */}
|
||||
<div className="w-[340px] bg-card border border-border rounded-lg p-3 flex flex-col gap-2">
|
||||
{/* Alternate Instrumental section */}
|
||||
<div className="bg-card border border-border rounded-lg p-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-semibold">Alternate Instrumental</span>
|
||||
<CustomUpload onUpload={handleUpload} isUploading={isUploading} />
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mt-1.5">
|
||||
Have your own instrumental track? Upload it here. The file must be the
|
||||
same duration as the original audio ({formatTime(duration)}) so the
|
||||
synced lyrics stay aligned.
|
||||
</p>
|
||||
{hasUploaded && uploadedFilename && (
|
||||
<p className="text-xs text-green-500 mt-1">
|
||||
✓ Using: {uploadedFilename}
|
||||
</p>
|
||||
)}
|
||||
</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">
|
||||
<SelectionOptions
|
||||
value={selectedOption}
|
||||
onChange={setSelectedOption}
|
||||
@@ -720,9 +750,10 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
id="submit-btn"
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitting}
|
||||
className="mt-auto w-full"
|
||||
size="lg"
|
||||
className="mt-auto w-full min-h-[44px] text-base font-semibold"
|
||||
>
|
||||
<Check className="w-4 h-4 mr-2" />
|
||||
<Check className="w-5 h-5 mr-2" />
|
||||
{isSubmitting ? "Submitting..." : "Confirm & Continue"}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -14,6 +14,8 @@ interface MuteRegionEditorProps {
|
||||
onCreateCustom: () => void
|
||||
onSeekTo: (time: number) => void
|
||||
onAddSegment: (index: number) => void
|
||||
onHoverRegion?: (index: number | null) => void
|
||||
onHoverSegment?: (index: number | null) => void
|
||||
}
|
||||
|
||||
function formatTime(seconds: number): string {
|
||||
@@ -33,16 +35,18 @@ export function MuteRegionEditor({
|
||||
onCreateCustom,
|
||||
onSeekTo,
|
||||
onAddSegment,
|
||||
onHoverRegion,
|
||||
onHoverSegment,
|
||||
}: MuteRegionEditorProps) {
|
||||
const hasRegions = regions.length > 0
|
||||
const hasSegments = audibleSegments.length > 0
|
||||
|
||||
return (
|
||||
<div className="flex-1 bg-card border border-border rounded-lg p-3 flex flex-col gap-2 max-h-[140px]">
|
||||
<div className="bg-card border border-border rounded-lg p-3 flex flex-col gap-2 max-h-[180px] lg:max-h-[140px]">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-semibold">
|
||||
Mute Regions {hasRegions && `(${regions.length})`}
|
||||
Custom Mix {hasRegions && `(${regions.length} muted)`}
|
||||
</span>
|
||||
{hasRegions && (
|
||||
<div className="flex gap-1.5">
|
||||
@@ -75,6 +79,8 @@ export function MuteRegionEditor({
|
||||
<div
|
||||
key={index}
|
||||
className="inline-flex items-center gap-1 px-2 py-1 bg-secondary rounded text-xs"
|
||||
onMouseEnter={() => onHoverRegion?.(index)}
|
||||
onMouseLeave={() => onHoverRegion?.(null)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
@@ -94,10 +100,24 @@ export function MuteRegionEditor({
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{hasSegments
|
||||
? "Click segments below or Shift + drag on waveform"
|
||||
: "No backing vocals detected - clean instrumental recommended"}
|
||||
<div className="text-xs text-muted-foreground space-y-1">
|
||||
{hasSegments ? (
|
||||
<>
|
||||
<p>
|
||||
Want backing vocals but hear lead vocal bleed in some sections?
|
||||
Mute those sections to create a custom mix.
|
||||
</p>
|
||||
<p className="text-muted-foreground/70">
|
||||
Click a segment below to mute it, or{" "}
|
||||
<kbd className="px-1 py-0.5 rounded bg-muted text-[0.65rem] font-mono">
|
||||
Shift
|
||||
</kbd>
|
||||
+drag on the waveform to mark a custom region.
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<p>No backing vocals detected — clean instrumental recommended.</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -109,6 +129,8 @@ export function MuteRegionEditor({
|
||||
key={index}
|
||||
type="button"
|
||||
onClick={() => onAddSegment(index)}
|
||||
onMouseEnter={() => onHoverSegment?.(index)}
|
||||
onMouseLeave={() => onHoverSegment?.(null)}
|
||||
title="Add to mute regions"
|
||||
className="px-1.5 py-0.5 bg-background border border-border rounded text-[10px] text-muted-foreground hover:border-primary hover:text-primary transition-colors"
|
||||
>
|
||||
|
||||
@@ -110,6 +110,13 @@ export function SelectionOptions({
|
||||
<div className="text-xs text-muted-foreground truncate">
|
||||
{option.description}
|
||||
</div>
|
||||
{backingVocalAnalysis?.recommended_selection === option.value && (
|
||||
<div className="text-[10px] text-green-500/80 mt-0.5">
|
||||
{option.value === "clean"
|
||||
? `Very few backing vocals detected (${backingVocalAnalysis.audible_percentage.toFixed(0)}%)`
|
||||
: `Significant backing vocals (${backingVocalAnalysis.audible_percentage.toFixed(0)}%) — may enhance the karaoke experience`}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
|
||||
@@ -13,6 +13,42 @@ interface WaveformViewerProps {
|
||||
onSeek: (time: number) => void
|
||||
onRegionCreate: (start: number, end: number) => void
|
||||
isShiftHeld: boolean
|
||||
highlightedTimeRange?: { start: number; end: number } | null
|
||||
}
|
||||
|
||||
function formatTime(seconds: number): string {
|
||||
if (!Number.isFinite(seconds)) return "0:00"
|
||||
const mins = Math.floor(seconds / 60)
|
||||
const secs = Math.floor(seconds % 60)
|
||||
return `${mins}:${secs.toString().padStart(2, "0")}`
|
||||
}
|
||||
|
||||
const RULER_HEIGHT = 20
|
||||
const NICE_INTERVALS = [1, 2, 5, 10, 15, 30, 60]
|
||||
|
||||
function getTickInterval(duration: number, canvasWidth: number): { major: number; minor: number } {
|
||||
const targetPx = 120
|
||||
const secondsPerPixel = duration / canvasWidth
|
||||
const targetInterval = secondsPerPixel * targetPx
|
||||
|
||||
let major = NICE_INTERVALS[NICE_INTERVALS.length - 1]
|
||||
for (const interval of NICE_INTERVALS) {
|
||||
if (interval >= targetInterval) {
|
||||
major = interval
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Minor ticks: subdivide major interval
|
||||
let minor = major / 4
|
||||
if (major >= 60) minor = 15
|
||||
else if (major >= 30) minor = 10
|
||||
else if (major >= 10) minor = 5
|
||||
else if (major >= 5) minor = 1
|
||||
else if (major >= 2) minor = 0.5
|
||||
else minor = 0.25
|
||||
|
||||
return { major, minor }
|
||||
}
|
||||
|
||||
export function WaveformViewer({
|
||||
@@ -25,6 +61,7 @@ export function WaveformViewer({
|
||||
onSeek,
|
||||
onRegionCreate,
|
||||
isShiftHeld,
|
||||
highlightedTimeRange,
|
||||
}: WaveformViewerProps) {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
@@ -42,7 +79,8 @@ export function WaveformViewer({
|
||||
|
||||
const width = canvas.width
|
||||
const height = canvas.height
|
||||
const centerY = height / 2
|
||||
const waveformHeight = height - RULER_HEIGHT
|
||||
const centerY = waveformHeight / 2
|
||||
|
||||
// Clear with dark background
|
||||
ctx.fillStyle = "#0d1117"
|
||||
@@ -62,7 +100,7 @@ export function WaveformViewer({
|
||||
|
||||
amplitudes.forEach((amp, i) => {
|
||||
const x = i * barWidth
|
||||
const barHeight = Math.max(2, amp * height * 0.9)
|
||||
const barHeight = Math.max(2, amp * waveformHeight * 0.9)
|
||||
const y = centerY - barHeight / 2
|
||||
const time = (i / amplitudes.length) * duration
|
||||
|
||||
@@ -89,7 +127,79 @@ export function WaveformViewer({
|
||||
|
||||
ctx.fillRect(x, y, Math.max(1, barWidth - 0.5), barHeight)
|
||||
})
|
||||
}, [amplitudes, duration, muteRegions, audibleSegments])
|
||||
|
||||
// Draw highlight overlay
|
||||
if (highlightedTimeRange && duration > 0) {
|
||||
const startX = (highlightedTimeRange.start / duration) * width
|
||||
const endX = (highlightedTimeRange.end / duration) * width
|
||||
|
||||
// Semi-transparent white overlay on waveform area
|
||||
ctx.fillStyle = "rgba(255, 255, 255, 0.12)"
|
||||
ctx.fillRect(startX, 0, endX - startX, waveformHeight)
|
||||
|
||||
// Vertical edge lines
|
||||
ctx.strokeStyle = "rgba(255, 255, 255, 0.5)"
|
||||
ctx.lineWidth = 1
|
||||
ctx.setLineDash([])
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(startX, 0)
|
||||
ctx.lineTo(startX, waveformHeight)
|
||||
ctx.moveTo(endX, 0)
|
||||
ctx.lineTo(endX, waveformHeight)
|
||||
ctx.stroke()
|
||||
|
||||
// Pink tint in ruler area for highlighted range
|
||||
ctx.fillStyle = "rgba(236, 72, 153, 0.3)"
|
||||
ctx.fillRect(startX, waveformHeight, endX - startX, RULER_HEIGHT)
|
||||
}
|
||||
|
||||
// Draw time ruler
|
||||
const rulerY = waveformHeight
|
||||
ctx.fillStyle = "rgba(0, 0, 0, 0.5)"
|
||||
ctx.fillRect(0, rulerY, width, RULER_HEIGHT)
|
||||
|
||||
// Ruler top border
|
||||
ctx.strokeStyle = "rgba(255, 255, 255, 0.15)"
|
||||
ctx.lineWidth = 1
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(0, rulerY)
|
||||
ctx.lineTo(width, rulerY)
|
||||
ctx.stroke()
|
||||
|
||||
if (duration > 0) {
|
||||
const { major, minor } = getTickInterval(duration, width)
|
||||
|
||||
// Draw minor ticks
|
||||
ctx.strokeStyle = "rgba(255, 255, 255, 0.15)"
|
||||
ctx.lineWidth = 1
|
||||
for (let t = 0; t <= duration; t += minor) {
|
||||
const x = (t / duration) * width
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(x, rulerY)
|
||||
ctx.lineTo(x, rulerY + 4)
|
||||
ctx.stroke()
|
||||
}
|
||||
|
||||
// Draw major ticks with labels
|
||||
ctx.strokeStyle = "rgba(255, 255, 255, 0.4)"
|
||||
ctx.fillStyle = "rgba(255, 255, 255, 0.6)"
|
||||
ctx.font = "10px monospace"
|
||||
ctx.textBaseline = "bottom"
|
||||
for (let t = 0; t <= duration; t += major) {
|
||||
const x = (t / duration) * width
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(x, rulerY)
|
||||
ctx.lineTo(x, rulerY + 8)
|
||||
ctx.stroke()
|
||||
|
||||
const label = formatTime(t)
|
||||
const textWidth = ctx.measureText(label).width
|
||||
// Avoid drawing label past right edge
|
||||
const labelX = Math.min(x + 3, width - textWidth - 2)
|
||||
ctx.fillText(label, Math.max(2, labelX), rulerY + RULER_HEIGHT - 2)
|
||||
}
|
||||
}
|
||||
}, [amplitudes, duration, muteRegions, audibleSegments, highlightedTimeRange])
|
||||
|
||||
// Resize canvas
|
||||
const resizeCanvas = useCallback(() => {
|
||||
@@ -118,6 +228,23 @@ export function WaveformViewer({
|
||||
return () => window.removeEventListener("resize", handleResize)
|
||||
}, [resizeCanvas, drawWaveform])
|
||||
|
||||
// Auto-scroll to show highlighted range when zoomed
|
||||
useEffect(() => {
|
||||
const container = containerRef.current
|
||||
const canvas = canvasRef.current
|
||||
if (!container || !canvas || !highlightedTimeRange || !duration || zoomLevel <= 1) return
|
||||
|
||||
const startFraction = highlightedTimeRange.start / duration
|
||||
const endFraction = highlightedTimeRange.end / duration
|
||||
const centerFraction = (startFraction + endFraction) / 2
|
||||
const targetScrollLeft = centerFraction * canvas.width - container.clientWidth / 2
|
||||
|
||||
container.scrollTo({
|
||||
left: Math.max(0, targetScrollLeft),
|
||||
behavior: "smooth",
|
||||
})
|
||||
}, [highlightedTimeRange, duration, zoomLevel])
|
||||
|
||||
// Calculate playhead position
|
||||
const playheadPosition =
|
||||
duration > 0 && canvasRef.current
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
import { render, screen } from "@testing-library/react"
|
||||
import userEvent from "@testing-library/user-event"
|
||||
import { InstrumentalGuidancePanel } from "../InstrumentalGuidancePanel"
|
||||
import type { BackingVocalAnalysis, AudibleSegment } from "@/lib/api"
|
||||
|
||||
// Mock localStorage
|
||||
const localStorageMock = (() => {
|
||||
let store: Record<string, string> = {}
|
||||
return {
|
||||
getItem: jest.fn((key: string) => store[key] || null),
|
||||
setItem: jest.fn((key: string, value: string) => {
|
||||
store[key] = value
|
||||
}),
|
||||
removeItem: jest.fn((key: string) => {
|
||||
delete store[key]
|
||||
}),
|
||||
clear: jest.fn(() => {
|
||||
store = {}
|
||||
}),
|
||||
}
|
||||
})()
|
||||
Object.defineProperty(window, "localStorage", { value: localStorageMock })
|
||||
|
||||
const makeAnalysis = (
|
||||
overrides: Partial<BackingVocalAnalysis> = {}
|
||||
): BackingVocalAnalysis => ({
|
||||
audible_segments: [],
|
||||
audible_percentage: 4,
|
||||
recommended_selection: "clean",
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const makeSegments = (count: number): AudibleSegment[] =>
|
||||
Array.from({ length: count }, (_, i) => ({
|
||||
start_seconds: i * 10,
|
||||
end_seconds: i * 10 + 2,
|
||||
}))
|
||||
|
||||
describe("InstrumentalGuidancePanel", () => {
|
||||
beforeEach(() => {
|
||||
localStorageMock.clear()
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
describe("simple case - clean recommended with low backing vocals", () => {
|
||||
it("shows simplified guidance when clean recommended and < 10% backing vocals", () => {
|
||||
render(
|
||||
<InstrumentalGuidancePanel
|
||||
analysis={makeAnalysis({ audible_percentage: 4, recommended_selection: "clean" })}
|
||||
audibleSegments={[]}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText(/Choose your karaoke backing track/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/very little backing vocal content/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/Clean Instrumental/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("shows the backing vocal percentage", () => {
|
||||
render(
|
||||
<InstrumentalGuidancePanel
|
||||
analysis={makeAnalysis({ audible_percentage: 4 })}
|
||||
audibleSegments={[]}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText(/4%/)).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe("complex case - backing vocals need review", () => {
|
||||
it("shows full workflow steps when backing vocals are significant", () => {
|
||||
render(
|
||||
<InstrumentalGuidancePanel
|
||||
analysis={makeAnalysis({
|
||||
audible_percentage: 25,
|
||||
recommended_selection: "with_backing",
|
||||
})}
|
||||
audibleSegments={makeSegments(5)}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText(/Step 1:/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/Step 2:/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/Step 3/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("shows segment count in step 1", () => {
|
||||
render(
|
||||
<InstrumentalGuidancePanel
|
||||
analysis={makeAnalysis({
|
||||
audible_percentage: 25,
|
||||
recommended_selection: "with_backing",
|
||||
})}
|
||||
audibleSegments={makeSegments(3)}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText(/3 detected/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("explains what backing vocals are", () => {
|
||||
render(
|
||||
<InstrumentalGuidancePanel
|
||||
analysis={makeAnalysis({
|
||||
audible_percentage: 25,
|
||||
recommended_selection: "with_backing",
|
||||
})}
|
||||
audibleSegments={makeSegments(2)}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText(/harmony\/chorus voices/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("shows full steps when clean recommended but >= 10% backing vocals", () => {
|
||||
render(
|
||||
<InstrumentalGuidancePanel
|
||||
analysis={makeAnalysis({
|
||||
audible_percentage: 15,
|
||||
recommended_selection: "clean",
|
||||
})}
|
||||
audibleSegments={makeSegments(3)}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText(/Step 1:/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/Step 2:/)).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe("dismissal and persistence", () => {
|
||||
it("dismisses tip and stores in localStorage", async () => {
|
||||
const user = userEvent.setup()
|
||||
render(
|
||||
<InstrumentalGuidancePanel
|
||||
analysis={makeAnalysis()}
|
||||
audibleSegments={[]}
|
||||
/>
|
||||
)
|
||||
|
||||
await user.click(screen.getByLabelText("Dismiss tip"))
|
||||
|
||||
expect(localStorageMock.setItem).toHaveBeenCalledWith(
|
||||
"instrumentalReviewGuidanceDismissed",
|
||||
"true"
|
||||
)
|
||||
expect(screen.queryByText(/Choose your karaoke backing track/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows "Show tips" link after dismissal', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(
|
||||
<InstrumentalGuidancePanel
|
||||
analysis={makeAnalysis()}
|
||||
audibleSegments={[]}
|
||||
/>
|
||||
)
|
||||
|
||||
await user.click(screen.getByLabelText("Dismiss tip"))
|
||||
expect(screen.getByText("Show tips")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('restores tip when "Show tips" is clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(
|
||||
<InstrumentalGuidancePanel
|
||||
analysis={makeAnalysis()}
|
||||
audibleSegments={[]}
|
||||
/>
|
||||
)
|
||||
|
||||
await user.click(screen.getByLabelText("Dismiss tip"))
|
||||
await user.click(screen.getByText("Show tips"))
|
||||
|
||||
expect(screen.getByText(/Choose your karaoke backing track/)).toBeInTheDocument()
|
||||
expect(localStorageMock.removeItem).toHaveBeenCalledWith(
|
||||
"instrumentalReviewGuidanceDismissed"
|
||||
)
|
||||
})
|
||||
|
||||
it("starts dismissed if localStorage has been set", () => {
|
||||
localStorageMock.getItem.mockReturnValueOnce("true")
|
||||
|
||||
render(
|
||||
<InstrumentalGuidancePanel
|
||||
analysis={makeAnalysis()}
|
||||
audibleSegments={[]}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.queryByText(/Choose your karaoke backing track/)).not.toBeInTheDocument()
|
||||
expect(screen.getByText("Show tips")).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,118 @@
|
||||
import { render, screen } from "@testing-library/react"
|
||||
import userEvent from "@testing-library/user-event"
|
||||
import { MuteRegionEditor } from "../MuteRegionEditor"
|
||||
import type { AudibleSegment } from "@/lib/api"
|
||||
|
||||
const defaultProps = {
|
||||
regions: [],
|
||||
audibleSegments: [] as AudibleSegment[],
|
||||
hasCustom: false,
|
||||
isCreatingCustom: false,
|
||||
onRemoveRegion: jest.fn(),
|
||||
onClearAll: jest.fn(),
|
||||
onCreateCustom: jest.fn(),
|
||||
onSeekTo: jest.fn(),
|
||||
onAddSegment: jest.fn(),
|
||||
onHoverRegion: jest.fn(),
|
||||
onHoverSegment: jest.fn(),
|
||||
}
|
||||
|
||||
describe("MuteRegionEditor", () => {
|
||||
it("shows contextual help when segments exist but no regions", () => {
|
||||
const segments: AudibleSegment[] = [
|
||||
{ start_seconds: 10, end_seconds: 12 },
|
||||
{ start_seconds: 30, end_seconds: 35 },
|
||||
]
|
||||
|
||||
render(
|
||||
<MuteRegionEditor {...defaultProps} audibleSegments={segments} />
|
||||
)
|
||||
|
||||
expect(screen.getByText(/lead vocal bleed/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/custom mix/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("shows clean recommendation when no segments detected", () => {
|
||||
render(<MuteRegionEditor {...defaultProps} />)
|
||||
|
||||
expect(screen.getByText(/No backing vocals detected/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/clean instrumental recommended/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("shows shift+drag instruction", () => {
|
||||
const segments: AudibleSegment[] = [
|
||||
{ start_seconds: 10, end_seconds: 12 },
|
||||
]
|
||||
|
||||
render(
|
||||
<MuteRegionEditor {...defaultProps} audibleSegments={segments} />
|
||||
)
|
||||
|
||||
expect(screen.getByText(/drag on the waveform/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows header as "Custom Mix" instead of "Mute Regions"', () => {
|
||||
render(<MuteRegionEditor {...defaultProps} />)
|
||||
|
||||
expect(screen.getByText("Custom Mix")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("shows region count in header when regions exist", () => {
|
||||
render(
|
||||
<MuteRegionEditor
|
||||
{...defaultProps}
|
||||
regions={[
|
||||
{ start_seconds: 10, end_seconds: 12 },
|
||||
{ start_seconds: 30, end_seconds: 35 },
|
||||
]}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText("Custom Mix (2 muted)")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("calls onHoverRegion on mouse enter/leave of region tags", async () => {
|
||||
const onHoverRegion = jest.fn()
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<MuteRegionEditor
|
||||
{...defaultProps}
|
||||
onHoverRegion={onHoverRegion}
|
||||
regions={[
|
||||
{ start_seconds: 10, end_seconds: 12 },
|
||||
]}
|
||||
/>
|
||||
)
|
||||
|
||||
const regionTag = screen.getByText("0:10 - 0:12").closest("div")!
|
||||
await user.hover(regionTag)
|
||||
expect(onHoverRegion).toHaveBeenCalledWith(0)
|
||||
|
||||
await user.unhover(regionTag)
|
||||
expect(onHoverRegion).toHaveBeenCalledWith(null)
|
||||
})
|
||||
|
||||
it("calls onHoverSegment on mouse enter/leave of segment buttons", async () => {
|
||||
const onHoverSegment = jest.fn()
|
||||
const user = userEvent.setup()
|
||||
const segments: AudibleSegment[] = [
|
||||
{ start_seconds: 10, end_seconds: 12 },
|
||||
]
|
||||
|
||||
render(
|
||||
<MuteRegionEditor
|
||||
{...defaultProps}
|
||||
onHoverSegment={onHoverSegment}
|
||||
audibleSegments={segments}
|
||||
/>
|
||||
)
|
||||
|
||||
const segmentBtn = screen.getByText("0:10 - 0:12")
|
||||
await user.hover(segmentBtn)
|
||||
expect(onHoverSegment).toHaveBeenCalledWith(0)
|
||||
|
||||
await user.unhover(segmentBtn)
|
||||
expect(onHoverSegment).toHaveBeenCalledWith(null)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,85 @@
|
||||
import { render, screen } from "@testing-library/react"
|
||||
import { SelectionOptions } from "../SelectionOptions"
|
||||
import type { BackingVocalAnalysis } from "@/lib/api"
|
||||
|
||||
const defaultProps = {
|
||||
value: "clean" as const,
|
||||
onChange: jest.fn(),
|
||||
hasWithBacking: true,
|
||||
hasOriginal: false,
|
||||
hasCustom: false,
|
||||
hasUploaded: false,
|
||||
muteRegionsCount: 0,
|
||||
}
|
||||
|
||||
describe("SelectionOptions", () => {
|
||||
it("shows recommendation reasoning for clean instrumental", () => {
|
||||
const analysis: BackingVocalAnalysis = {
|
||||
audible_segments: [],
|
||||
audible_percentage: 4,
|
||||
recommended_selection: "clean",
|
||||
}
|
||||
|
||||
render(
|
||||
<SelectionOptions
|
||||
{...defaultProps}
|
||||
backingVocalAnalysis={analysis}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText("Recommended")).toBeInTheDocument()
|
||||
expect(screen.getByText(/Very few backing vocals detected \(4%\)/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("shows recommendation reasoning for with_backing", () => {
|
||||
const analysis: BackingVocalAnalysis = {
|
||||
audible_segments: [],
|
||||
audible_percentage: 25,
|
||||
recommended_selection: "with_backing",
|
||||
}
|
||||
|
||||
render(
|
||||
<SelectionOptions
|
||||
{...defaultProps}
|
||||
value="with_backing"
|
||||
backingVocalAnalysis={analysis}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText("Recommended")).toBeInTheDocument()
|
||||
expect(screen.getByText(/Significant backing vocals \(25%\)/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("does not show reasoning for non-recommended options", () => {
|
||||
const analysis: BackingVocalAnalysis = {
|
||||
audible_segments: [],
|
||||
audible_percentage: 4,
|
||||
recommended_selection: "clean",
|
||||
}
|
||||
|
||||
render(
|
||||
<SelectionOptions
|
||||
{...defaultProps}
|
||||
backingVocalAnalysis={analysis}
|
||||
/>
|
||||
)
|
||||
|
||||
// Only one recommendation reasoning text
|
||||
const reasoningTexts = screen.getAllByText(/backing vocals/)
|
||||
// "No backing vocals" (description) + "Very few backing vocals detected" (reasoning) + "All backing vocals included" (description)
|
||||
expect(reasoningTexts.length).toBeGreaterThanOrEqual(1)
|
||||
})
|
||||
|
||||
it("shows custom option with region count when available", () => {
|
||||
render(
|
||||
<SelectionOptions
|
||||
{...defaultProps}
|
||||
hasCustom={true}
|
||||
muteRegionsCount={3}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText("Custom")).toBeInTheDocument()
|
||||
expect(screen.getByText("3 regions muted")).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,359 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { useTenant } from "@/lib/tenant"
|
||||
import { api, ApiError } from "@/lib/api"
|
||||
import { AlertTriangle, CheckCircle2, Music } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import Link from "next/link"
|
||||
import { SongInfoStep } from "./steps/SongInfoStep"
|
||||
import { AudioSourceStep } from "./steps/AudioSourceStep"
|
||||
import { CustomizeStep } from "./steps/CustomizeStep"
|
||||
|
||||
interface GuidedJobFlowProps {
|
||||
onJobCreated: () => void
|
||||
}
|
||||
|
||||
type Step = 1 | 2 | 3
|
||||
|
||||
const STEP_LABELS = ["Song Info", "Choose Audio", "Customize & Create"]
|
||||
|
||||
export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
const { user } = useAuth()
|
||||
const { features } = useTenant()
|
||||
const isAdmin = user?.role === "admin"
|
||||
const noCredits = !isAdmin && user?.credits === 0
|
||||
|
||||
const [step, setStep] = useState<Step>(1)
|
||||
const [showSuccess, setShowSuccess] = useState(false)
|
||||
|
||||
// Form state (persists across steps)
|
||||
const [artist, setArtist] = useState("")
|
||||
const [title, setTitle] = useState("")
|
||||
const [displayArtist, setDisplayArtist] = useState("")
|
||||
const [displayTitle, setDisplayTitle] = useState("")
|
||||
const [isPrivate, setIsPrivate] = useState(false)
|
||||
|
||||
// Job tracking
|
||||
const [jobId, setJobId] = useState<string | null>(null)
|
||||
const [audioSource, setAudioSource] = useState<"search" | "upload" | "url">("search")
|
||||
const [selectedResultIndex, setSelectedResultIndex] = useState<number | null>(null)
|
||||
|
||||
// Submission state
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [submitError, setSubmitError] = useState("")
|
||||
|
||||
function handleJobCreated(id: string, source: "search" | "upload" | "url") {
|
||||
setJobId(id)
|
||||
setAudioSource(source)
|
||||
}
|
||||
|
||||
function handleSearchResultChosen(resultIndex: number) {
|
||||
// Just store the choice — don't call selectAudioResult yet
|
||||
// The job stays in awaiting_audio_selection (hidden from Recent Jobs)
|
||||
setSelectedResultIndex(resultIndex)
|
||||
setStep(3)
|
||||
}
|
||||
|
||||
function handleFallbackComplete() {
|
||||
// Upload/URL jobs are already processing — show success directly
|
||||
onJobCreated()
|
||||
setShowSuccess(true)
|
||||
}
|
||||
|
||||
async function handleConfirm() {
|
||||
if (!jobId || selectedResultIndex === null) return
|
||||
|
||||
setIsSubmitting(true)
|
||||
setSubmitError("")
|
||||
try {
|
||||
// NOW we trigger the actual audio selection + processing
|
||||
await api.selectAudioResult(jobId, selectedResultIndex)
|
||||
onJobCreated()
|
||||
setShowSuccess(true)
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError) {
|
||||
setSubmitError(err.message)
|
||||
} else {
|
||||
setSubmitError("Failed to start processing. Please try again.")
|
||||
}
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleBackFromAudio(jobIdToCleanup: string | null) {
|
||||
// Clean up the stale job (best-effort, don't block on failure)
|
||||
if (jobIdToCleanup) {
|
||||
api.deleteJob(jobIdToCleanup).catch(() => {
|
||||
// Silently ignore cleanup failures
|
||||
})
|
||||
}
|
||||
setJobId(null)
|
||||
setAudioSource("search")
|
||||
setSelectedResultIndex(null)
|
||||
setStep(1)
|
||||
}
|
||||
|
||||
function resetFlow() {
|
||||
setStep(1)
|
||||
setShowSuccess(false)
|
||||
setArtist("")
|
||||
setTitle("")
|
||||
setDisplayArtist("")
|
||||
setDisplayTitle("")
|
||||
setIsPrivate(false)
|
||||
setJobId(null)
|
||||
setAudioSource("search")
|
||||
setSelectedResultIndex(null)
|
||||
setSubmitError("")
|
||||
}
|
||||
|
||||
// Success state
|
||||
if (showSuccess) {
|
||||
const effectiveArtist = displayArtist.trim() || artist
|
||||
const effectiveTitle = displayTitle.trim() || title
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div className="flex flex-col items-center text-center py-5 space-y-3">
|
||||
<div
|
||||
className="w-12 h-12 rounded-full flex items-center justify-center"
|
||||
style={{ backgroundColor: 'rgba(34, 197, 94, 0.15)' }}
|
||||
>
|
||||
<CheckCircle2 className="w-7 h-7 text-green-500" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold" style={{ color: 'var(--text)' }}>
|
||||
Job Created
|
||||
</h2>
|
||||
<p className="text-sm mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
<span className="font-medium" style={{ color: 'var(--text)' }}>{effectiveArtist} - {effectiveTitle}</span>
|
||||
</p>
|
||||
{jobId && (
|
||||
<p className="text-xs mt-0.5 font-mono" style={{ color: 'var(--text-muted)' }} data-testid="created-job-id">
|
||||
ID: {jobId.slice(0, 8)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Timeline */}
|
||||
<p className="text-xs font-semibold uppercase tracking-wider" style={{ color: 'var(--text-muted)' }}>What happens next</p>
|
||||
<div className="space-y-0 mt-3">
|
||||
{/* Step 1: Automated processing */}
|
||||
<div className="flex gap-3">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0 bg-blue-500/15">
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" className="text-blue-400">
|
||||
<path d="M8 1.5a1.25 1.25 0 0 1 1.177.825l.573 1.608 1.608.573a1.25 1.25 0 0 1 0 2.354l-1.608.573-.573 1.608a1.25 1.25 0 0 1-2.354 0l-.573-1.608-1.608-.573a1.25 1.25 0 0 1 0-2.354l1.608-.573.573-1.608A1.25 1.25 0 0 1 8 1.5Z" fill="currentColor" opacity="0.85"/>
|
||||
<path d="M12 9a1 1 0 0 1 .94.66l.36 1.02 1.02.36a1 1 0 0 1 0 1.884l-1.02.36-.36 1.02a1 1 0 0 1-1.88 0l-.36-1.02-1.02-.36a1 1 0 0 1 0-1.884l1.02-.36.36-1.02A1 1 0 0 1 12 9Z" fill="currentColor" opacity="0.55"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div className="w-px flex-1 min-h-[20px]" style={{ backgroundColor: 'var(--card-border)' }} />
|
||||
</div>
|
||||
<div className="pb-4 pt-1">
|
||||
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>Audio processing</p>
|
||||
<p className="text-xs mt-0.5" style={{ color: 'var(--text-muted)' }}>
|
||||
We download the audio, separate vocals from the instrumental, and transcribe the lyrics. <span className="font-medium" style={{ color: 'var(--text)' }}>~10 minutes</span>
|
||||
</p>
|
||||
<span className="inline-block mt-1.5 text-[10px] px-1.5 py-0.5 rounded-full font-medium bg-blue-500/15 text-blue-400">
|
||||
Automatic
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Step 2: User review */}
|
||||
<div className="flex gap-3">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0" style={{ backgroundColor: 'rgba(255, 122, 204, 0.15)' }}>
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" style={{ color: 'var(--brand-pink)' }}>
|
||||
<path d="M8 2a3 3 0 1 0 0 6 3 3 0 0 0 0-6ZM3.5 13.5c0-2.485 2.015-4.5 4.5-4.5s4.5 2.015 4.5 4.5a.5.5 0 0 1-.5.5h-8a.5.5 0 0 1-.5-.5Z" fill="currentColor" opacity="0.85"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div className="w-px flex-1 min-h-[20px]" style={{ backgroundColor: 'var(--card-border)' }} />
|
||||
</div>
|
||||
<div className="pb-4 pt-1">
|
||||
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>You review the lyrics & instrumental</p>
|
||||
<p className="text-xs mt-0.5" style={{ color: 'var(--text-muted)' }}>
|
||||
Check the lyrics and listen to the instrumental. Fix any errors and approve.
|
||||
</p>
|
||||
<div className="flex items-center gap-2 mt-1.5 flex-wrap">
|
||||
<span className="inline-block text-[10px] px-1.5 py-0.5 rounded-full font-medium" style={{ backgroundColor: 'rgba(255, 122, 204, 0.15)', color: 'var(--brand-pink)' }}>
|
||||
You
|
||||
</span>
|
||||
<span className="flex items-center gap-1 text-[10px]" style={{ color: 'var(--text-muted)' }}>
|
||||
<svg width="12" height="12" viewBox="0 0 16 16" fill="none">
|
||||
<path d="M2 3.5A1.5 1.5 0 0 1 3.5 2h9A1.5 1.5 0 0 1 14 3.5v.401a1 1 0 0 1-.373.78L8.707 8.79a1 1 0 0 1-1.414 0L2.373 4.68A1 1 0 0 1 2 3.9V3.5Z" fill="currentColor" opacity="0.7"/>
|
||||
<path d="M2 6.12l4.586 3.59a2 2 0 0 0 2.828 0L14 6.12V12.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 12.5V6.12Z" fill="currentColor" opacity="0.5"/>
|
||||
</svg>
|
||||
Email + chime when ready
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Step 3: Final render */}
|
||||
<div className="flex gap-3">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0 bg-green-500/15">
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" className="text-green-400">
|
||||
<path d="M3 2.5A1.5 1.5 0 0 1 4.5 1h7A1.5 1.5 0 0 1 13 2.5v11a.5.5 0 0 1-.765.424L8 11.28l-4.235 2.644A.5.5 0 0 1 3 13.5v-11Z" fill="currentColor" opacity="0.5"/>
|
||||
<path d="M6.354 7.854 7.5 9l2.146-2.146a.5.5 0 0 0-.708-.708L7.5 7.586l-.646-.647a.5.5 0 1 0-.708.708l.208.207Z" fill="currentColor"/>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<div className="pt-1">
|
||||
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>Video delivered</p>
|
||||
<p className="text-xs mt-0.5" style={{ color: 'var(--text-muted)' }}>
|
||||
After you approve, your karaoke video is rendered and uploaded. <span className="font-medium" style={{ color: 'var(--text)' }}>~10 minutes</span>
|
||||
</p>
|
||||
<div className="flex items-center gap-2 mt-1.5 flex-wrap">
|
||||
<span className="inline-block text-[10px] px-1.5 py-0.5 rounded-full font-medium bg-green-500/15 text-green-400">
|
||||
Automatic
|
||||
</span>
|
||||
<span className="flex items-center gap-1 text-[10px]" style={{ color: 'var(--text-muted)' }}>
|
||||
<svg width="12" height="12" viewBox="0 0 16 16" fill="none">
|
||||
<path d="M2 3.5A1.5 1.5 0 0 1 3.5 2h9A1.5 1.5 0 0 1 14 3.5v.401a1 1 0 0 1-.373.78L8.707 8.79a1 1 0 0 1-1.414 0L2.373 4.68A1 1 0 0 1 2 3.9V3.5Z" fill="currentColor" opacity="0.7"/>
|
||||
<path d="M2 6.12l4.586 3.59a2 2 0 0 0 2.828 0L14 6.12V12.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 12.5V6.12Z" fill="currentColor" opacity="0.5"/>
|
||||
</svg>
|
||||
Email with link to view
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-[10px] text-center" style={{ color: 'var(--text-muted)' }}>
|
||||
Track progress in the <span className="font-medium" style={{ color: 'var(--text)' }}>Recent Jobs</span> list. Keep this tab open to hear the chime.
|
||||
</p>
|
||||
|
||||
<Button
|
||||
onClick={resetFlow}
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
style={{ borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
>
|
||||
<Music className="w-4 h-4 mr-2" />
|
||||
Create Another
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Zero-credit warning banner */}
|
||||
{noCredits && (
|
||||
<div className="flex items-start gap-2 rounded-lg p-3 border border-amber-500/30 bg-amber-500/10">
|
||||
<AlertTriangle className="w-5 h-5 text-amber-500 shrink-0 mt-0.5" />
|
||||
<div className="text-sm" style={{ color: 'var(--text)' }}>
|
||||
<p>You have no credits remaining. Buy credits to create new karaoke videos.</p>
|
||||
<Link
|
||||
href="/#pricing"
|
||||
className="inline-block mt-1 text-sm font-medium underline"
|
||||
style={{ color: 'var(--brand-pink)' }}
|
||||
>
|
||||
Buy Credits
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Step indicator */}
|
||||
<div className="flex items-center gap-1" role="navigation" aria-label="Progress">
|
||||
{STEP_LABELS.map((label, i) => {
|
||||
const stepNum = (i + 1) as Step
|
||||
const isActive = step === stepNum
|
||||
const isCompleted = step > stepNum
|
||||
|
||||
return (
|
||||
<div key={label} className="flex items-center gap-1 flex-1">
|
||||
<div className="flex items-center gap-1.5 shrink-0">
|
||||
<div
|
||||
className={`w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-semibold shrink-0 transition-colors ${
|
||||
isActive
|
||||
? 'bg-[var(--brand-pink)] text-white'
|
||||
: isCompleted
|
||||
? 'bg-[var(--brand-pink)]/20 text-[var(--brand-pink)]'
|
||||
: 'bg-[var(--secondary)] text-[var(--text-muted)]'
|
||||
}`}
|
||||
>
|
||||
{isCompleted ? "\u2713" : stepNum}
|
||||
</div>
|
||||
<span
|
||||
className={`text-[10px] whitespace-nowrap transition-colors ${
|
||||
isActive ? 'font-medium' : ''
|
||||
}`}
|
||||
style={{ color: isActive ? 'var(--text)' : 'var(--text-muted)' }}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
{i < STEP_LABELS.length - 1 && (
|
||||
<div
|
||||
className="h-px flex-1 mx-1 hidden sm:block"
|
||||
style={{
|
||||
backgroundColor: isCompleted ? 'var(--brand-pink)' : 'var(--card-border)',
|
||||
opacity: isCompleted ? 0.4 : 1,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Submit error */}
|
||||
{submitError && (
|
||||
<div className="text-sm text-red-400 bg-red-500/10 rounded p-3">
|
||||
<p>{submitError}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Step content */}
|
||||
{step === 1 && (
|
||||
<SongInfoStep
|
||||
artist={artist}
|
||||
title={title}
|
||||
onArtistChange={setArtist}
|
||||
onTitleChange={setTitle}
|
||||
onNext={() => setStep(2)}
|
||||
disabled={noCredits}
|
||||
/>
|
||||
)}
|
||||
|
||||
{step === 2 && (
|
||||
<AudioSourceStep
|
||||
artist={artist}
|
||||
title={title}
|
||||
displayArtist={displayArtist}
|
||||
displayTitle={displayTitle}
|
||||
isPrivate={isPrivate}
|
||||
onJobCreated={handleJobCreated}
|
||||
onSearchResultChosen={handleSearchResultChosen}
|
||||
onFallbackComplete={handleFallbackComplete}
|
||||
onBack={handleBackFromAudio}
|
||||
noCredits={noCredits}
|
||||
/>
|
||||
)}
|
||||
|
||||
{step === 3 && (
|
||||
<CustomizeStep
|
||||
artist={artist}
|
||||
title={title}
|
||||
displayArtist={displayArtist}
|
||||
displayTitle={displayTitle}
|
||||
onDisplayArtistChange={setDisplayArtist}
|
||||
onDisplayTitleChange={setDisplayTitle}
|
||||
isPrivate={isPrivate}
|
||||
onPrivateChange={setIsPrivate}
|
||||
onConfirm={handleConfirm}
|
||||
onBack={() => setStep(2)}
|
||||
isSubmitting={isSubmitting}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -200,6 +200,7 @@ export function JobCard({ job, onRefresh }: JobCardProps) {
|
||||
open={showAudioSearch}
|
||||
onClose={() => setShowAudioSearch(false)}
|
||||
onSelect={onRefresh}
|
||||
searchTitle={job.title}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -63,10 +63,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
const [displayTitle, setDisplayTitle] = useState("")
|
||||
const [showDisplayAs, setShowDisplayAs] = useState(false)
|
||||
|
||||
// Non-interactive mode (shared across all tabs)
|
||||
const [nonInteractive, setNonInteractive] = useState(false)
|
||||
|
||||
// Private (non-published) mode - Dropbox only, no YouTube/GDrive
|
||||
// Private (no YouTube upload) mode - Dropbox only, no YouTube/GDrive
|
||||
const [isPrivate, setIsPrivate] = useState(false)
|
||||
|
||||
// Credit enforcement
|
||||
@@ -89,7 +86,6 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
await api.uploadJob(uploadFile, uploadArtist.trim(), uploadTitle.trim(), {
|
||||
non_interactive: nonInteractive,
|
||||
is_private: isPrivate,
|
||||
})
|
||||
setUploadFile(null)
|
||||
@@ -131,7 +127,6 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
youtubeArtist.trim(),
|
||||
youtubeTitle.trim(),
|
||||
{
|
||||
non_interactive: nonInteractive,
|
||||
is_private: isPrivate,
|
||||
}
|
||||
)
|
||||
@@ -166,7 +161,6 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
await api.searchAudio(searchArtist.trim(), searchTitle.trim(), false, {
|
||||
non_interactive: nonInteractive,
|
||||
is_private: isPrivate,
|
||||
// Display overrides (empty string means use search values)
|
||||
display_artist: displayArtist.trim() || undefined,
|
||||
@@ -322,32 +316,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
<span className="text-amber-500 font-medium">Note:</span> Format these exactly as you want them on the title card and video filename.
|
||||
</p>
|
||||
|
||||
{/* Non-interactive mode (admin only) */}
|
||||
{isAdmin && (
|
||||
<div className="space-y-2 pt-4 border-t" style={{ borderColor: 'var(--card-border)' }}>
|
||||
<div className="flex items-start gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="non-interactive-upload"
|
||||
checked={nonInteractive}
|
||||
onChange={(e) => setNonInteractive(e.target.checked)}
|
||||
disabled={isSubmitting}
|
||||
className="mt-1 w-4 h-4 rounded border-border bg-secondary accent-[var(--brand-pink)] focus:ring-[var(--brand-pink)] focus:ring-offset-background"
|
||||
/>
|
||||
<div>
|
||||
<Label htmlFor="non-interactive-upload" className="cursor-pointer" style={{ color: 'var(--text)' }}>
|
||||
Skip lyrics review (non-interactive)
|
||||
</Label>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
<span className="text-amber-500 font-medium">Warning:</span> auto lyrics correction isn't perfect.
|
||||
Skipping review will likely result in incorrect words in your karaoke video.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Private (non-published) mode */}
|
||||
{/* Private (no YouTube upload) mode */}
|
||||
<div className="space-y-2 pt-4 border-t" style={{ borderColor: 'var(--card-border)' }}>
|
||||
<div className="flex items-start gap-3">
|
||||
<input
|
||||
@@ -360,7 +329,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
/>
|
||||
<div>
|
||||
<Label htmlFor="private-upload" className="cursor-pointer" style={{ color: 'var(--text)' }}>
|
||||
Private (non-published)
|
||||
Private (no YouTube upload)
|
||||
</Label>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
Files delivered via Dropbox only. No YouTube or Google Drive upload.
|
||||
@@ -444,32 +413,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
<span className="text-amber-500 font-medium">Note:</span> Format these exactly as you want them on the title card and video filename.
|
||||
</p>
|
||||
|
||||
{/* Non-interactive mode (admin only) */}
|
||||
{isAdmin && (
|
||||
<div className="space-y-2 pt-4 border-t" style={{ borderColor: 'var(--card-border)' }}>
|
||||
<div className="flex items-start gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="non-interactive-url"
|
||||
checked={nonInteractive}
|
||||
onChange={(e) => setNonInteractive(e.target.checked)}
|
||||
disabled={isSubmitting}
|
||||
className="mt-1 w-4 h-4 rounded border-border bg-secondary accent-[var(--brand-pink)] focus:ring-[var(--brand-pink)] focus:ring-offset-background"
|
||||
/>
|
||||
<div>
|
||||
<Label htmlFor="non-interactive-url" className="cursor-pointer" style={{ color: 'var(--text)' }}>
|
||||
Skip lyrics review (non-interactive)
|
||||
</Label>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
<span className="text-amber-500 font-medium">Warning:</span> auto lyrics correction isn't perfect.
|
||||
Skipping review will likely result in incorrect words in your karaoke video.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Private (non-published) mode */}
|
||||
{/* Private (no YouTube upload) mode */}
|
||||
<div className="space-y-2 pt-4 border-t" style={{ borderColor: 'var(--card-border)' }}>
|
||||
<div className="flex items-start gap-3">
|
||||
<input
|
||||
@@ -482,7 +426,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
/>
|
||||
<div>
|
||||
<Label htmlFor="private-url" className="cursor-pointer" style={{ color: 'var(--text)' }}>
|
||||
Private (non-published)
|
||||
Private (no YouTube upload)
|
||||
</Label>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
Files delivered via Dropbox only. No YouTube or Google Drive upload.
|
||||
@@ -604,32 +548,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Non-interactive mode (admin only) */}
|
||||
{isAdmin && (
|
||||
<div className="space-y-2 pt-4 border-t" style={{ borderColor: 'var(--card-border)' }}>
|
||||
<div className="flex items-start gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="non-interactive-search"
|
||||
checked={nonInteractive}
|
||||
onChange={(e) => setNonInteractive(e.target.checked)}
|
||||
disabled={isSubmitting}
|
||||
className="mt-1 w-4 h-4 rounded border-border bg-secondary accent-[var(--brand-pink)] focus:ring-[var(--brand-pink)] focus:ring-offset-background"
|
||||
/>
|
||||
<div>
|
||||
<Label htmlFor="non-interactive-search" className="cursor-pointer" style={{ color: 'var(--text)' }}>
|
||||
Skip lyrics review (non-interactive)
|
||||
</Label>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
<span className="text-amber-500 font-medium">Warning:</span> auto lyrics correction isn't perfect.
|
||||
Skipping review will likely result in incorrect words in your karaoke video.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Private (non-published) mode */}
|
||||
{/* Private (no YouTube upload) mode */}
|
||||
<div className="space-y-2 pt-4 border-t" style={{ borderColor: 'var(--card-border)' }}>
|
||||
<div className="flex items-start gap-3">
|
||||
<input
|
||||
@@ -642,7 +561,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
/>
|
||||
<div>
|
||||
<Label htmlFor="private-search" className="cursor-pointer" style={{ color: 'var(--text)' }}>
|
||||
Private (non-published)
|
||||
Private (no YouTube upload)
|
||||
</Label>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
Files delivered via Dropbox only. No YouTube or Google Drive upload.
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
"use client"
|
||||
|
||||
import { useRef, useEffect, useCallback } from "react"
|
||||
|
||||
interface TitleCardPreviewProps {
|
||||
artist: string
|
||||
title: string
|
||||
}
|
||||
|
||||
// Matches the Nomad theme title card (style_params.json from GCS):
|
||||
// - 3840x2160 canvas (16:9)
|
||||
// - Background: karaoke-title-screen-background-nomad-4k.png
|
||||
// - Font: AvenirNext-Bold.ttf
|
||||
// - Title: white (#ffffff), uppercase, region 370,980,3100,350
|
||||
// - Artist: golden yellow (#ffdf6b), uppercase, region 370,1400,3100,450
|
||||
|
||||
const CANVAS_W = 3840
|
||||
const CANVAS_H = 2160
|
||||
|
||||
// Title region: x=370, y=980, w=3100, h=350
|
||||
const TITLE_X = 370
|
||||
const TITLE_Y = 980
|
||||
const TITLE_W = 3100
|
||||
const TITLE_H = 350
|
||||
|
||||
// Artist region: x=370, y=1400, w=3100, h=450
|
||||
const ARTIST_X = 370
|
||||
const ARTIST_Y = 1400
|
||||
const ARTIST_W = 3100
|
||||
const ARTIST_H = 450
|
||||
|
||||
const TITLE_COLOR = "#ffffff"
|
||||
const ARTIST_COLOR = "#ffdf6b"
|
||||
|
||||
let bgImageCache: HTMLImageElement | null = null
|
||||
|
||||
function loadBgImage(): Promise<HTMLImageElement> {
|
||||
if (bgImageCache?.complete) return Promise.resolve(bgImageCache)
|
||||
return new Promise((resolve, reject) => {
|
||||
const img = new Image()
|
||||
img.onload = () => {
|
||||
bgImageCache = img
|
||||
resolve(img)
|
||||
}
|
||||
img.onerror = reject
|
||||
img.src = "/title-card-bg.png"
|
||||
})
|
||||
}
|
||||
|
||||
function fitText(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
text: string,
|
||||
maxWidth: number,
|
||||
maxHeight: number,
|
||||
fontFamily: string,
|
||||
): { fontSize: number; lines: string[] } {
|
||||
for (let size = 500; size >= 40; size -= 10) {
|
||||
ctx.font = `700 ${size}px ${fontFamily}`
|
||||
const metrics = ctx.measureText(text)
|
||||
|
||||
if (metrics.width <= maxWidth) {
|
||||
return { fontSize: size, lines: [text] }
|
||||
}
|
||||
|
||||
// Try 2-line split
|
||||
const words = text.split(" ")
|
||||
if (words.length >= 2) {
|
||||
let bestSplit = 1
|
||||
let bestDiff = Infinity
|
||||
for (let i = 1; i < words.length; i++) {
|
||||
const line1 = words.slice(0, i).join(" ")
|
||||
const line2 = words.slice(i).join(" ")
|
||||
const diff = Math.abs(ctx.measureText(line1).width - ctx.measureText(line2).width)
|
||||
if (diff < bestDiff) {
|
||||
bestDiff = diff
|
||||
bestSplit = i
|
||||
}
|
||||
}
|
||||
const line1 = words.slice(0, bestSplit).join(" ")
|
||||
const line2 = words.slice(bestSplit).join(" ")
|
||||
const w1 = ctx.measureText(line1).width
|
||||
const w2 = ctx.measureText(line2).width
|
||||
const lineHeight = size * 1.1
|
||||
|
||||
if (Math.max(w1, w2) <= maxWidth && lineHeight * 2 <= maxHeight) {
|
||||
return { fontSize: size, lines: [line1, line2] }
|
||||
}
|
||||
}
|
||||
}
|
||||
return { fontSize: 40, lines: [text] }
|
||||
}
|
||||
|
||||
function drawTextBlock(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
text: string,
|
||||
regionX: number,
|
||||
regionY: number,
|
||||
regionW: number,
|
||||
regionH: number,
|
||||
color: string,
|
||||
fontFamily: string,
|
||||
) {
|
||||
if (!text) return
|
||||
|
||||
ctx.fillStyle = color
|
||||
ctx.textAlign = "center"
|
||||
ctx.textBaseline = "middle"
|
||||
|
||||
const { fontSize, lines } = fitText(ctx, text, regionW, regionH, fontFamily)
|
||||
ctx.font = `700 ${fontSize}px ${fontFamily}`
|
||||
|
||||
const lineHeight = fontSize * 1.1
|
||||
const totalHeight = lineHeight * lines.length
|
||||
const startY = regionY + (regionH - totalHeight) / 2 + lineHeight / 2
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
ctx.fillText(lines[i], regionX + regionW / 2, startY + i * lineHeight)
|
||||
}
|
||||
}
|
||||
|
||||
export function TitleCardPreview({ artist, title }: TitleCardPreviewProps) {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
|
||||
const draw = useCallback(async () => {
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas) return
|
||||
const ctx = canvas.getContext("2d")
|
||||
if (!ctx) return
|
||||
|
||||
// Draw background image (or black fallback)
|
||||
try {
|
||||
const bgImg = await loadBgImage()
|
||||
ctx.drawImage(bgImg, 0, 0, CANVAS_W, CANVAS_H)
|
||||
} catch {
|
||||
ctx.fillStyle = "#000000"
|
||||
ctx.fillRect(0, 0, CANVAS_W, CANVAS_H)
|
||||
}
|
||||
|
||||
// Get computed font family from CSS variable
|
||||
const computedFont = getComputedStyle(canvas).getPropertyValue("--font-title-card").trim()
|
||||
const fontFamily = computedFont || "'AvenirNext-Bold', 'Avenir Next', sans-serif"
|
||||
|
||||
// Apply uppercase transform (matching style_params.json title_text_transform/artist_text_transform)
|
||||
const titleText = (title || "Song Title").toUpperCase()
|
||||
const artistText = (artist || "Artist").toUpperCase()
|
||||
|
||||
// Draw title (white)
|
||||
drawTextBlock(
|
||||
ctx,
|
||||
titleText,
|
||||
TITLE_X, TITLE_Y, TITLE_W, TITLE_H,
|
||||
title ? TITLE_COLOR : "rgba(255,255,255,0.25)",
|
||||
fontFamily,
|
||||
)
|
||||
|
||||
// Draw artist (golden yellow)
|
||||
drawTextBlock(
|
||||
ctx,
|
||||
artistText,
|
||||
ARTIST_X, ARTIST_Y, ARTIST_W, ARTIST_H,
|
||||
artist ? ARTIST_COLOR : "rgba(255,223,107,0.25)",
|
||||
fontFamily,
|
||||
)
|
||||
}, [artist, title])
|
||||
|
||||
useEffect(() => {
|
||||
draw()
|
||||
}, [draw])
|
||||
|
||||
// Re-draw when fonts load
|
||||
useEffect(() => {
|
||||
document.fonts.ready.then(() => draw())
|
||||
}, [draw])
|
||||
|
||||
return (
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
width={CANVAS_W}
|
||||
height={CANVAS_H}
|
||||
className="w-full rounded-lg"
|
||||
style={{
|
||||
aspectRatio: "16/9",
|
||||
border: "1px solid var(--card-border)",
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,995 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect, useMemo, useCallback, useRef } from "react"
|
||||
import { api, ApiError } from "@/lib/api"
|
||||
import {
|
||||
ExtendedAudioSearchResult,
|
||||
groupResults,
|
||||
getSearchConfidence,
|
||||
getAvailabilityLabel,
|
||||
checkFilenameMismatch,
|
||||
getDisplayName,
|
||||
formatCount,
|
||||
formatMetadata,
|
||||
formatQuality,
|
||||
SearchConfidence,
|
||||
} from "@/lib/audio-search-utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Loader2, Music2, ChevronDown, ChevronUp, Upload, Youtube, ArrowLeft, Check, AlertTriangle, CheckCircle2, Lightbulb } from "lucide-react"
|
||||
import Link from "next/link"
|
||||
|
||||
interface AudioSourceStepProps {
|
||||
artist: string
|
||||
title: string
|
||||
displayArtist: string
|
||||
displayTitle: string
|
||||
isPrivate: boolean
|
||||
onJobCreated: (jobId: string, source: "search" | "upload" | "url") => void
|
||||
onSearchResultChosen: (resultIndex: number) => void
|
||||
onFallbackComplete: () => void
|
||||
onBack: (jobIdToCleanup: string | null) => void
|
||||
noCredits: boolean
|
||||
}
|
||||
|
||||
/** Render an availability badge with tooltip */
|
||||
function AvailabilityBadge({ seeders }: { seeders: number | undefined | null }) {
|
||||
if (seeders === undefined || seeders === null) return null
|
||||
const { text, tooltip } = getAvailabilityLabel(seeders)
|
||||
if (!text) return null
|
||||
|
||||
return (
|
||||
<span
|
||||
title={tooltip}
|
||||
className={`text-[8px] px-1 py-0.5 rounded font-medium cursor-help ${
|
||||
seeders >= 50 ? 'bg-green-600/20 text-green-400' :
|
||||
seeders >= 10 ? 'bg-yellow-600/20 text-yellow-400' :
|
||||
'bg-red-600/20 text-red-400'
|
||||
}`}
|
||||
>
|
||||
{text} avail.
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** Render a color-coded view count badge */
|
||||
function ViewCountBadge({ viewCount }: { viewCount: number | undefined | null }) {
|
||||
if (viewCount === undefined || viewCount === null) return null
|
||||
|
||||
const color = viewCount >= 1_000_000 ? 'bg-green-600/20 text-green-400' :
|
||||
viewCount >= 100_000 ? 'bg-yellow-600/20 text-yellow-400' :
|
||||
'bg-[var(--secondary)] text-[var(--text-muted)]'
|
||||
|
||||
const tooltip = viewCount >= 1_000_000 ? 'Very popular — likely the right track' :
|
||||
viewCount >= 100_000 ? 'Moderately popular' :
|
||||
'Low view count — verify this is the right track'
|
||||
|
||||
return (
|
||||
<span
|
||||
title={tooltip}
|
||||
className={`text-[8px] px-1 py-0.5 rounded font-medium cursor-help ${color}`}
|
||||
>
|
||||
{formatCount(viewCount)} views
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** Render a filename mismatch badge */
|
||||
function MismatchBadge({ searchTitle, result }: { searchTitle: string; result: ExtendedAudioSearchResult }) {
|
||||
const mismatch = useMemo(() => checkFilenameMismatch(searchTitle, result), [searchTitle, result])
|
||||
if (!mismatch.isMismatch) return null
|
||||
|
||||
return (
|
||||
<span
|
||||
title={`Expected "${searchTitle}" but filename is "${mismatch.filename}"${mismatch.suggestedTrack ? ` (looks like "${mismatch.suggestedTrack}")` : ''}`}
|
||||
className="text-[8px] px-1 py-0.5 rounded font-medium bg-yellow-600/20 text-yellow-400 cursor-help"
|
||||
>
|
||||
Wrong track?
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export function AudioSourceStep({
|
||||
artist,
|
||||
title,
|
||||
displayArtist,
|
||||
displayTitle,
|
||||
isPrivate,
|
||||
onJobCreated,
|
||||
onSearchResultChosen,
|
||||
onFallbackComplete,
|
||||
onBack,
|
||||
noCredits,
|
||||
}: AudioSourceStepProps) {
|
||||
const [results, setResults] = useState<ExtendedAudioSearchResult[]>([])
|
||||
const [isSearching, setIsSearching] = useState(true)
|
||||
const [jobId, setJobId] = useState<string | null>(null)
|
||||
const [error, setError] = useState("")
|
||||
const [isCreditError, setIsCreditError] = useState(false)
|
||||
const [showOtherOptions, setShowOtherOptions] = useState(false)
|
||||
const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set())
|
||||
const searchTriggered = useRef(false)
|
||||
|
||||
// Fallback form state
|
||||
const [uploadFile, setUploadFile] = useState<File | null>(null)
|
||||
const [youtubeUrl, setYoutubeUrl] = useState("")
|
||||
const [isSubmittingFallback, setIsSubmittingFallback] = useState(false)
|
||||
const [fallbackMode, setFallbackMode] = useState<"upload" | "url" | null>(null)
|
||||
|
||||
// Auto-trigger search on mount
|
||||
const triggerSearch = useCallback(async () => {
|
||||
if (searchTriggered.current) return
|
||||
searchTriggered.current = true
|
||||
|
||||
setIsSearching(true)
|
||||
setError("")
|
||||
setIsCreditError(false)
|
||||
try {
|
||||
const response = await api.searchAudio(artist, title, false, {
|
||||
is_private: isPrivate,
|
||||
display_artist: displayArtist.trim() || undefined,
|
||||
display_title: displayTitle.trim() || undefined,
|
||||
})
|
||||
setJobId(response.job_id)
|
||||
onJobCreated(response.job_id, "search")
|
||||
|
||||
// Now poll for results
|
||||
await pollForResults(response.job_id)
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 402) {
|
||||
setIsCreditError(true)
|
||||
setError("You're out of credits. Buy more to continue creating karaoke videos.")
|
||||
} else if (err instanceof ApiError) {
|
||||
setError(err.message)
|
||||
} else {
|
||||
setError("Failed to search for audio")
|
||||
}
|
||||
setIsSearching(false)
|
||||
}
|
||||
}, [artist, title, displayArtist, displayTitle, isPrivate, onJobCreated])
|
||||
|
||||
useEffect(() => {
|
||||
triggerSearch()
|
||||
}, [triggerSearch])
|
||||
|
||||
async function pollForResults(jid: string) {
|
||||
const maxAttempts = 30
|
||||
const interval = 2000
|
||||
|
||||
for (let i = 0; i < maxAttempts; i++) {
|
||||
try {
|
||||
const data = await api.getAudioSearchResults(jid)
|
||||
if (data.results && data.results.length > 0) {
|
||||
setResults(data.results as ExtendedAudioSearchResult[])
|
||||
setIsSearching(false)
|
||||
return
|
||||
}
|
||||
// Check if search is still in progress
|
||||
if (data.status === "search_complete" || data.status === "audio_search_complete") {
|
||||
// Search finished but no results
|
||||
setResults([])
|
||||
setIsSearching(false)
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
// Ignore errors during polling - keep trying
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, interval))
|
||||
}
|
||||
// Timeout
|
||||
setError("Search is taking longer than expected. You can try the fallback options below.")
|
||||
setIsSearching(false)
|
||||
}
|
||||
|
||||
const confidence = useMemo(() => getSearchConfidence(results, title), [results, title])
|
||||
const groupedResults = useMemo(() => groupResults(results), [results])
|
||||
const otherResultsCount = results.length > 0 && confidence.bestResult ? results.length - 1 : 0
|
||||
|
||||
function handleSelect(index: number) {
|
||||
// Don't call the API here — defer selectAudioResult to the Customize & Create step
|
||||
// so the job stays in awaiting_audio_selection (hidden from Recent Jobs) until confirmed
|
||||
onSearchResultChosen(index)
|
||||
}
|
||||
|
||||
function handleBack() {
|
||||
onBack(jobId)
|
||||
}
|
||||
|
||||
function toggleCategory(category: string) {
|
||||
setExpandedCategories(prev => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(category)) {
|
||||
next.delete(category)
|
||||
} else {
|
||||
next.add(category)
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
async function handleUploadSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
if (!uploadFile) return
|
||||
|
||||
setIsSubmittingFallback(true)
|
||||
setError("")
|
||||
setIsCreditError(false)
|
||||
try {
|
||||
const response = await api.uploadJob(uploadFile, artist.trim(), title.trim(), {
|
||||
is_private: isPrivate,
|
||||
})
|
||||
onJobCreated(response.job_id, "upload")
|
||||
onFallbackComplete()
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 402) {
|
||||
setIsCreditError(true)
|
||||
setError("You're out of credits. Buy more to continue creating karaoke videos.")
|
||||
} else if (err instanceof ApiError) {
|
||||
setError(err.message)
|
||||
} else {
|
||||
setError("Failed to upload file")
|
||||
}
|
||||
} finally {
|
||||
setIsSubmittingFallback(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleUrlSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
if (!youtubeUrl.trim()) return
|
||||
|
||||
setIsSubmittingFallback(true)
|
||||
setError("")
|
||||
setIsCreditError(false)
|
||||
try {
|
||||
const response = await api.createJobFromUrl(youtubeUrl.trim(), artist.trim(), title.trim(), {
|
||||
is_private: isPrivate,
|
||||
})
|
||||
onJobCreated(response.job_id, "url")
|
||||
onFallbackComplete()
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 402) {
|
||||
setIsCreditError(true)
|
||||
setError("You're out of credits. Buy more to continue creating karaoke videos.")
|
||||
} else if (err instanceof ApiError) {
|
||||
setError(err.message)
|
||||
} else {
|
||||
setError("Failed to create job from URL")
|
||||
}
|
||||
} finally {
|
||||
setIsSubmittingFallback(false)
|
||||
}
|
||||
}
|
||||
|
||||
const isLossyBest = confidence.bestCategory === 'YOUTUBE'
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>
|
||||
Searching for <span className="font-medium" style={{ color: 'var(--text)' }}>{artist} - {title}</span>
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleBack}
|
||||
disabled={isSubmittingFallback}
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4 mr-1" />
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Error display */}
|
||||
{error && (
|
||||
<div className="text-sm text-red-400 bg-red-500/10 rounded p-3">
|
||||
<p>{error}</p>
|
||||
{isCreditError && (
|
||||
<Link href="/#pricing" className="inline-block mt-1 font-medium underline" style={{ color: 'var(--brand-pink)' }}>Buy Credits</Link>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Loading state */}
|
||||
{isSearching && (
|
||||
<div className="flex flex-col items-center justify-center py-12 gap-3">
|
||||
<Loader2 className="w-8 h-8 animate-spin" style={{ color: 'var(--brand-pink)' }} />
|
||||
<div className="text-center">
|
||||
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>Searching for audio sources...</p>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
This usually takes 15-30 seconds
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Tier 1: Perfect match found */}
|
||||
{!isSearching && confidence.tier === 1 && confidence.bestResult && (
|
||||
<PickCard
|
||||
confidence={confidence}
|
||||
variant="perfect"
|
||||
searchTitle={title}
|
||||
onSelect={handleSelect}
|
||||
noCredits={noCredits}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Tier 2: Recommended with reasoning */}
|
||||
{!isSearching && confidence.tier === 2 && confidence.bestResult && (
|
||||
<PickCard
|
||||
confidence={confidence}
|
||||
variant="recommended"
|
||||
searchTitle={title}
|
||||
onSelect={handleSelect}
|
||||
noCredits={noCredits}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Tier 3: Guidance banner + fallback FIRST, then search results below */}
|
||||
{!isSearching && confidence.tier === 3 && results.length > 0 && (
|
||||
<>
|
||||
<GuidanceBanner results={results} />
|
||||
<FallbackSection
|
||||
tier={confidence.tier}
|
||||
hasResults={results.length > 0}
|
||||
fallbackMode={fallbackMode}
|
||||
setFallbackMode={setFallbackMode}
|
||||
youtubeUrl={youtubeUrl}
|
||||
setYoutubeUrl={setYoutubeUrl}
|
||||
uploadFile={uploadFile}
|
||||
setUploadFile={setUploadFile}
|
||||
isSubmittingFallback={isSubmittingFallback}
|
||||
noCredits={noCredits}
|
||||
onUrlSubmit={handleUrlSubmit}
|
||||
onUploadSubmit={handleUploadSubmit}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Other options section — varies by tier */}
|
||||
{!isSearching && results.length > 0 && (
|
||||
<OtherOptionsSection
|
||||
confidence={confidence}
|
||||
groupedResults={groupedResults}
|
||||
otherResultsCount={otherResultsCount}
|
||||
showOtherOptions={showOtherOptions}
|
||||
setShowOtherOptions={setShowOtherOptions}
|
||||
expandedCategories={expandedCategories}
|
||||
toggleCategory={toggleCategory}
|
||||
searchTitle={title}
|
||||
onSelect={handleSelect}
|
||||
noCredits={noCredits}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* No results */}
|
||||
{!isSearching && results.length === 0 && !error && (
|
||||
<div className="flex flex-col items-center justify-center py-8" style={{ color: 'var(--text-muted)' }}>
|
||||
<Music2 className="w-8 h-8 mb-2 opacity-50" />
|
||||
<p className="text-sm">No audio sources found for this song.</p>
|
||||
<p className="text-xs mt-1">Try the options below instead.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Fallback section for Tier 1/2 and no-results — at the bottom */}
|
||||
{!isSearching && confidence.tier !== 3 && (
|
||||
<FallbackSection
|
||||
tier={confidence.tier}
|
||||
hasResults={results.length > 0}
|
||||
fallbackMode={fallbackMode}
|
||||
setFallbackMode={setFallbackMode}
|
||||
youtubeUrl={youtubeUrl}
|
||||
setYoutubeUrl={setYoutubeUrl}
|
||||
uploadFile={uploadFile}
|
||||
setUploadFile={setUploadFile}
|
||||
isSubmittingFallback={isSubmittingFallback}
|
||||
noCredits={noCredits}
|
||||
onUrlSubmit={handleUrlSubmit}
|
||||
onUploadSubmit={handleUploadSubmit}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Pick card for Tier 1 and Tier 2 */
|
||||
function PickCard({
|
||||
confidence,
|
||||
variant,
|
||||
searchTitle,
|
||||
onSelect,
|
||||
noCredits,
|
||||
}: {
|
||||
confidence: SearchConfidence
|
||||
variant: "perfect" | "recommended"
|
||||
searchTitle: string
|
||||
onSelect: (index: number) => void
|
||||
noCredits: boolean
|
||||
}) {
|
||||
const bestResult = confidence.bestResult!
|
||||
const isPerfect = variant === "perfect"
|
||||
const isLossyBest = confidence.bestCategory === 'YOUTUBE'
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`border rounded-lg overflow-hidden ${
|
||||
isPerfect
|
||||
? 'border-green-500/40 bg-green-500/5'
|
||||
: 'border-amber-500/40 bg-amber-500/5'
|
||||
}`}
|
||||
data-testid="pick-card"
|
||||
data-confidence-tier={confidence.tier}
|
||||
>
|
||||
<div className={`px-3 py-2 flex items-center gap-2 ${
|
||||
isPerfect ? 'bg-green-500/10' : 'bg-amber-500/10'
|
||||
}`}>
|
||||
{isPerfect ? (
|
||||
<CheckCircle2 className="w-3.5 h-3.5 text-green-400" />
|
||||
) : null}
|
||||
<span className={`text-xs font-semibold ${isPerfect ? 'text-green-400' : 'text-amber-400'}`}>
|
||||
{isPerfect ? 'Perfect match found' : 'Recommended'}
|
||||
</span>
|
||||
{bestResult.is_lossless && (
|
||||
<span className="text-[8px] px-1 py-0.5 rounded bg-green-600/20 text-green-400 font-medium">
|
||||
LOSSLESS
|
||||
</span>
|
||||
)}
|
||||
{bestResult.provider === "YouTube" && (
|
||||
<span className="text-[8px] px-1 py-0.5 rounded font-medium bg-red-600/20 text-red-400">
|
||||
YouTube
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="px-3 py-3 space-y-2">
|
||||
{/* Confidence reason */}
|
||||
<p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
|
||||
{confidence.reason}
|
||||
</p>
|
||||
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-baseline gap-1.5">
|
||||
<span className="text-[10px] shrink-0" style={{ color: 'var(--text-muted)' }}>Release:</span>
|
||||
<span className="font-medium text-sm" style={{ color: 'var(--text)' }}>
|
||||
{getDisplayName(bestResult)} - {bestResult.title}
|
||||
</span>
|
||||
</div>
|
||||
{bestResult.target_file && (
|
||||
<div className="flex items-baseline gap-1.5 mt-0.5">
|
||||
<span className="text-[10px] shrink-0" style={{ color: 'var(--text-muted)' }}>Filename:</span>
|
||||
<span className="font-medium text-xs font-mono break-all" style={{ color: 'var(--text)' }}>
|
||||
{bestResult.target_file}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-1.5 flex-wrap mt-1.5">
|
||||
<span className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
|
||||
{formatQuality(bestResult)}
|
||||
</span>
|
||||
<AvailabilityBadge seeders={bestResult.seeders} />
|
||||
{!bestResult.seeders && (
|
||||
<ViewCountBadge viewCount={bestResult.view_count} />
|
||||
)}
|
||||
<MismatchBadge searchTitle={searchTitle} result={bestResult} />
|
||||
</div>
|
||||
{formatMetadata(bestResult) && (
|
||||
<div className="text-[10px] mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
{formatMetadata(bestResult)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Warnings */}
|
||||
{confidence.warnings.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
{confidence.warnings.map((warning, i) => (
|
||||
<div key={i} className="flex items-start gap-2 rounded p-2 text-[10px] bg-yellow-600/10 text-yellow-400">
|
||||
<AlertTriangle className="w-3.5 h-3.5 shrink-0 mt-0.5" />
|
||||
<span>{warning}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Lossy quality warning (separate from confidence warnings) */}
|
||||
{isLossyBest && !confidence.warnings.some(w => w.includes('lossless')) && (
|
||||
<div className="flex items-start gap-2 rounded p-2 text-[10px] bg-yellow-600/10 text-yellow-400">
|
||||
<AlertTriangle className="w-3.5 h-3.5 shrink-0 mt-0.5" />
|
||||
<span>This is a YouTube/lossy source. Lossless audio produces better karaoke results when available.</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button
|
||||
onClick={() => onSelect(bestResult.index)}
|
||||
disabled={noCredits}
|
||||
className={`w-full text-white ${
|
||||
isPerfect
|
||||
? 'bg-green-600 hover:bg-green-500'
|
||||
: 'bg-amber-600 hover:bg-amber-500'
|
||||
}`}
|
||||
>
|
||||
<Check className="w-4 h-4 mr-1.5" />
|
||||
Use This Audio
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Guidance banner for Tier 3 */
|
||||
function GuidanceBanner({ results }: { results: ExtendedAudioSearchResult[] }) {
|
||||
const tips = useMemo(() => getGuidanceTips(results), [results])
|
||||
|
||||
return (
|
||||
<div
|
||||
className="border rounded-lg p-3 space-y-2 border-[var(--card-border)] bg-[var(--secondary)]/30"
|
||||
data-testid="guidance-banner"
|
||||
data-confidence-tier={3}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Lightbulb className="w-4 h-4 text-amber-400 shrink-0" />
|
||||
<span className="text-xs font-semibold" style={{ color: 'var(--text)' }}>
|
||||
Limited sources found
|
||||
</span>
|
||||
</div>
|
||||
<ul className="text-[10px] space-y-1 ml-6" style={{ color: 'var(--text-muted)' }}>
|
||||
{tips.map((tip, i) => <li key={i}>{tip}</li>)}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Build context-aware guidance tips based on actual result composition */
|
||||
function getGuidanceTips(results: ExtendedAudioSearchResult[]): string[] {
|
||||
const hasFiles = results.some(r => r.target_file)
|
||||
const hasYoutube = results.some(r => r.provider?.toLowerCase() === 'youtube')
|
||||
const hasSpotify = results.some(r => r.provider?.toLowerCase() === 'spotify')
|
||||
const hasLossless = results.some(r => r.is_lossless && !['youtube', 'spotify'].includes(r.provider?.toLowerCase() ?? ''))
|
||||
const hasVinyl = results.some(r => r.quality_data?.media?.toLowerCase() === 'vinyl')
|
||||
const hasSeeders = results.some(r => r.seeders !== undefined && r.seeders !== null)
|
||||
const noLossless = !hasLossless
|
||||
|
||||
const tips: string[] = []
|
||||
|
||||
if (hasFiles) {
|
||||
tips.push('Check the filename matches your song title')
|
||||
}
|
||||
if (hasSeeders) {
|
||||
tips.push('Green availability badge = more reliable download')
|
||||
}
|
||||
if (hasLossless) {
|
||||
tips.push('Studio album versions produce the best karaoke results')
|
||||
}
|
||||
if (hasVinyl) {
|
||||
tips.push('Avoid vinyl rips (surface noise affects separation)')
|
||||
}
|
||||
if (hasYoutube && hasLossless) {
|
||||
tips.push('YouTube is a last resort — lossless sources sound better')
|
||||
}
|
||||
if (noLossless) {
|
||||
tips.push('No high quality lossless sources were found')
|
||||
}
|
||||
if (hasSpotify && hasYoutube) {
|
||||
tips.push('Spotify results are higher quality than YouTube')
|
||||
}
|
||||
if (noLossless && hasYoutube) {
|
||||
tips.push('If YouTube is the only option, official music videos or audio-only uploads tend to have the best quality')
|
||||
}
|
||||
|
||||
return tips
|
||||
}
|
||||
|
||||
/** Other options section — render differently per tier */
|
||||
function OtherOptionsSection({
|
||||
confidence,
|
||||
groupedResults,
|
||||
otherResultsCount,
|
||||
showOtherOptions,
|
||||
setShowOtherOptions,
|
||||
expandedCategories,
|
||||
toggleCategory,
|
||||
searchTitle,
|
||||
onSelect,
|
||||
noCredits,
|
||||
}: {
|
||||
confidence: SearchConfidence
|
||||
groupedResults: ReturnType<typeof groupResults>
|
||||
otherResultsCount: number
|
||||
showOtherOptions: boolean
|
||||
setShowOtherOptions: (show: boolean) => void
|
||||
expandedCategories: Set<string>
|
||||
toggleCategory: (category: string) => void
|
||||
searchTitle: string
|
||||
onSelect: (index: number) => void
|
||||
noCredits: boolean
|
||||
}) {
|
||||
const isTier3 = confidence.tier === 3
|
||||
|
||||
// For Tier 3, always show results expanded (no toggle needed)
|
||||
// For Tier 1/2, show toggle to expand other options
|
||||
if (isTier3) {
|
||||
return (
|
||||
<div className="border-t pt-4 space-y-2" style={{ borderColor: 'var(--card-border)' }}>
|
||||
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
Search results (may not match your song):
|
||||
</p>
|
||||
<ResultCategories
|
||||
groupedResults={groupedResults}
|
||||
bestResult={null} // Don't filter any result for Tier 3
|
||||
expandedCategories={expandedCategories}
|
||||
toggleCategory={toggleCategory}
|
||||
searchTitle={searchTitle}
|
||||
onSelect={onSelect}
|
||||
noCredits={noCredits}
|
||||
defaultExpanded
|
||||
alwaysShowMatchBadge
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (otherResultsCount <= 0) return null
|
||||
|
||||
return (
|
||||
<div>
|
||||
<button
|
||||
onClick={() => setShowOtherOptions(!showOtherOptions)}
|
||||
className="flex items-center gap-1.5 text-xs hover:opacity-80 transition-opacity"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
{showOtherOptions ? (
|
||||
<><ChevronUp className="w-3.5 h-3.5" /> Hide other options</>
|
||||
) : (
|
||||
<><ChevronDown className="w-3.5 h-3.5" /> See all {otherResultsCount} other option{otherResultsCount !== 1 ? 's' : ''}</>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{showOtherOptions && (
|
||||
<div className="mt-2 space-y-2">
|
||||
<p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
|
||||
Check the filename matches your song. Higher availability (green) = more reliable. Studio album versions produce the best results.
|
||||
</p>
|
||||
<ResultCategories
|
||||
groupedResults={groupedResults}
|
||||
bestResult={confidence.bestResult}
|
||||
expandedCategories={expandedCategories}
|
||||
toggleCategory={toggleCategory}
|
||||
searchTitle={searchTitle}
|
||||
onSelect={onSelect}
|
||||
noCredits={noCredits}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Render categorized result groups */
|
||||
function ResultCategories({
|
||||
groupedResults,
|
||||
bestResult,
|
||||
expandedCategories,
|
||||
toggleCategory,
|
||||
searchTitle,
|
||||
onSelect,
|
||||
noCredits,
|
||||
defaultExpanded,
|
||||
alwaysShowMatchBadge,
|
||||
}: {
|
||||
groupedResults: ReturnType<typeof groupResults>
|
||||
bestResult: ExtendedAudioSearchResult | null
|
||||
expandedCategories: Set<string>
|
||||
toggleCategory: (category: string) => void
|
||||
searchTitle: string
|
||||
onSelect: (index: number) => void
|
||||
noCredits: boolean
|
||||
defaultExpanded?: boolean
|
||||
alwaysShowMatchBadge?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-2 max-h-[350px] overflow-y-auto pr-1">
|
||||
{groupedResults.map(({ category, results: catResults, config }) => {
|
||||
const isExpanded = defaultExpanded || expandedCategories.has(category)
|
||||
// Filter out the best result from "other options" (when best result shown separately)
|
||||
const filteredResults = bestResult
|
||||
? catResults.filter(r => r.index !== bestResult.index)
|
||||
: catResults
|
||||
if (filteredResults.length === 0) return null
|
||||
|
||||
// Check mismatch status for each result
|
||||
const mismatchFlags = filteredResults.map(r => checkFilenameMismatch(searchTitle, r).isMismatch)
|
||||
const hasAnyMatch = mismatchFlags.some(m => !m)
|
||||
const hasAnyMismatch = mismatchFlags.some(m => m)
|
||||
// Show match/mismatch badges when there's a mix, or always in Tier 3
|
||||
const showMatchBadges = (hasAnyMatch && hasAnyMismatch) || (alwaysShowMatchBadge && hasAnyMatch)
|
||||
|
||||
// Sort matching results to top when there's a mix
|
||||
const sortedResults = hasAnyMatch && hasAnyMismatch
|
||||
? [...filteredResults].sort((a, b) => {
|
||||
const aMismatch = checkFilenameMismatch(searchTitle, a).isMismatch
|
||||
const bMismatch = checkFilenameMismatch(searchTitle, b).isMismatch
|
||||
if (aMismatch === bMismatch) return 0
|
||||
return aMismatch ? 1 : -1
|
||||
})
|
||||
: filteredResults
|
||||
|
||||
const displayResults = isExpanded
|
||||
? sortedResults
|
||||
: sortedResults.slice(0, config.maxDisplay)
|
||||
const hiddenCount = filteredResults.length - config.maxDisplay
|
||||
const hasMore = hiddenCount > 0
|
||||
|
||||
return (
|
||||
<div
|
||||
key={category}
|
||||
className="border rounded-lg overflow-hidden border-[var(--card-border)] bg-[var(--secondary)]/20"
|
||||
>
|
||||
{/* Category Header */}
|
||||
<div className="px-3 py-1.5 flex items-center justify-between bg-[var(--secondary)]">
|
||||
<div className="flex items-center gap-2 text-xs font-semibold">
|
||||
<span className={config.color}>{category}</span>
|
||||
<span style={{ color: 'var(--text-muted)' }} className="font-normal">({filteredResults.length})</span>
|
||||
</div>
|
||||
{hasMore && !defaultExpanded && (
|
||||
<button
|
||||
onClick={() => toggleCategory(category)}
|
||||
className="text-[10px] hover:opacity-80 flex items-center gap-1"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
{isExpanded ? (
|
||||
<>Show less <ChevronUp className="w-3 h-3" /></>
|
||||
) : (
|
||||
<>+{hiddenCount} more <ChevronDown className="w-3 h-3" /></>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Results */}
|
||||
<div className="divide-y" style={{ borderColor: 'var(--card-border)' }}>
|
||||
{displayResults.map((result) => (
|
||||
<ResultRow
|
||||
key={result.index}
|
||||
result={result}
|
||||
searchTitle={searchTitle}
|
||||
showMatchBadges={showMatchBadges}
|
||||
onSelect={onSelect}
|
||||
noCredits={noCredits}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Single result row in the "other options" list */
|
||||
function ResultRow({
|
||||
result,
|
||||
searchTitle,
|
||||
showMatchBadges,
|
||||
onSelect,
|
||||
noCredits,
|
||||
}: {
|
||||
result: ExtendedAudioSearchResult
|
||||
searchTitle: string
|
||||
showMatchBadges: boolean
|
||||
onSelect: (index: number) => void
|
||||
noCredits: boolean
|
||||
}) {
|
||||
const mismatch = useMemo(() => checkFilenameMismatch(searchTitle, result), [searchTitle, result])
|
||||
// Only show "Title match" when we actually verified a match (filename is non-empty)
|
||||
const isMatch = showMatchBadges && !mismatch.isMismatch && mismatch.filename !== ''
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`px-3 py-2 flex items-center gap-3 text-xs transition-colors ${isMatch ? 'bg-green-600/5' : 'hover:bg-[var(--secondary)]/50'}`}
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-1.5 flex-wrap">
|
||||
{result.is_lossless && (
|
||||
<span className="text-[8px] px-1 py-0.5 rounded bg-green-600/20 text-green-400 font-medium">
|
||||
LOSSLESS
|
||||
</span>
|
||||
)}
|
||||
{result.provider === "Spotify" && (
|
||||
<span className="text-[8px] px-1 py-0.5 rounded font-medium bg-green-600/20 text-green-400">
|
||||
Spotify
|
||||
</span>
|
||||
)}
|
||||
{result.provider === "YouTube" && (
|
||||
<span className="text-[8px] px-1 py-0.5 rounded font-medium bg-red-600/20 text-red-400">
|
||||
YouTube
|
||||
</span>
|
||||
)}
|
||||
<span className="font-medium" style={{ color: 'var(--text)' }}>
|
||||
{getDisplayName(result)} - {result.title}
|
||||
</span>
|
||||
<span className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
|
||||
({formatQuality(result)})
|
||||
</span>
|
||||
<AvailabilityBadge seeders={result.seeders} />
|
||||
{!result.seeders && (
|
||||
<ViewCountBadge viewCount={result.view_count} />
|
||||
)}
|
||||
{isMatch ? (
|
||||
<span className="text-[8px] px-1 py-0.5 rounded font-medium bg-green-600/20 text-green-400">
|
||||
Title match
|
||||
</span>
|
||||
) : (
|
||||
<MismatchBadge searchTitle={searchTitle} result={result} />
|
||||
)}
|
||||
</div>
|
||||
{formatMetadata(result) && (
|
||||
<div className="text-[10px] mt-0.5" style={{ color: 'var(--text-muted)' }}>
|
||||
{formatMetadata(result)}
|
||||
</div>
|
||||
)}
|
||||
{result.target_file && (
|
||||
<div className="text-[10px] mt-0.5 font-mono break-all" style={{ color: 'var(--text-muted)' }}>
|
||||
<span className="font-sans">Filename: </span>{result.target_file}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => onSelect(result.index)}
|
||||
disabled={noCredits}
|
||||
className="h-7 px-3 text-xs shrink-0 bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white"
|
||||
>
|
||||
<Check className="w-3 h-3 mr-1" />
|
||||
Select
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Fallback section — upload or YouTube URL */
|
||||
function FallbackSection({
|
||||
tier,
|
||||
hasResults,
|
||||
fallbackMode,
|
||||
setFallbackMode,
|
||||
youtubeUrl,
|
||||
setYoutubeUrl,
|
||||
uploadFile,
|
||||
setUploadFile,
|
||||
isSubmittingFallback,
|
||||
noCredits,
|
||||
onUrlSubmit,
|
||||
onUploadSubmit,
|
||||
}: {
|
||||
tier: number
|
||||
hasResults: boolean
|
||||
fallbackMode: "upload" | "url" | null
|
||||
setFallbackMode: (mode: "upload" | "url" | null) => void
|
||||
youtubeUrl: string
|
||||
setYoutubeUrl: (url: string) => void
|
||||
uploadFile: File | null
|
||||
setUploadFile: (file: File | null) => void
|
||||
isSubmittingFallback: boolean
|
||||
noCredits: boolean
|
||||
onUrlSubmit: (e: React.FormEvent) => void
|
||||
onUploadSubmit: (e: React.FormEvent) => void
|
||||
}) {
|
||||
const isTier3WithResults = tier === 3 && hasResults
|
||||
return (
|
||||
<div className={`${isTier3WithResults ? '' : 'border-t pt-4 '}space-y-3`} style={{ borderColor: 'var(--card-border)' }}>
|
||||
<p className={isTier3WithResults ? 'text-xs font-medium' : 'text-xs'} style={{ color: 'var(--text-muted)' }}>
|
||||
{isTier3WithResults
|
||||
? "Have your own audio? Upload it or paste a YouTube URL:"
|
||||
: 'Not finding what you need? Try simplifying your search, or provide your own audio:'
|
||||
}
|
||||
</p>
|
||||
|
||||
{/* Two equally prominent buttons */}
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => { setFallbackMode(fallbackMode === "url" ? null : "url"); }}
|
||||
className={`h-9 text-xs ${fallbackMode === "url" ? 'border-[var(--brand-pink)] bg-[var(--brand-pink)]/10' : ''}`}
|
||||
style={{ borderColor: fallbackMode === "url" ? 'var(--brand-pink)' : 'var(--card-border)', color: 'var(--text)' }}
|
||||
>
|
||||
<Youtube className="w-3.5 h-3.5 mr-1.5" />
|
||||
YouTube URL
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => { setFallbackMode(fallbackMode === "upload" ? null : "upload"); }}
|
||||
className={`h-9 text-xs ${fallbackMode === "upload" ? 'border-[var(--brand-pink)] bg-[var(--brand-pink)]/10' : ''}`}
|
||||
style={{ borderColor: fallbackMode === "upload" ? 'var(--brand-pink)' : 'var(--card-border)', color: 'var(--text)' }}
|
||||
>
|
||||
<Upload className="w-3.5 h-3.5 mr-1.5" />
|
||||
Upload file
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* YouTube URL form */}
|
||||
{fallbackMode === "url" && (
|
||||
<form onSubmit={onUrlSubmit} className="space-y-2 p-3 rounded-lg" style={{ backgroundColor: 'var(--secondary)' }}>
|
||||
<div className="relative">
|
||||
<Youtube className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4" style={{ color: 'var(--text-muted)' }} />
|
||||
<Input
|
||||
type="url"
|
||||
placeholder="https://youtube.com/watch?v=..."
|
||||
value={youtubeUrl}
|
||||
onChange={(e) => setYoutubeUrl(e.target.value)}
|
||||
className="pl-10 text-xs"
|
||||
style={{ backgroundColor: 'var(--background)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
disabled={isSubmittingFallback}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
disabled={!youtubeUrl.trim() || isSubmittingFallback || noCredits}
|
||||
className="w-full bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white"
|
||||
>
|
||||
{isSubmittingFallback ? (
|
||||
<><Loader2 className="w-3 h-3 mr-1 animate-spin" /> Creating...</>
|
||||
) : (
|
||||
"Use This URL"
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{/* Upload form */}
|
||||
{fallbackMode === "upload" && (
|
||||
<form onSubmit={onUploadSubmit} className="space-y-3 p-3 rounded-lg" style={{ backgroundColor: 'var(--secondary)' }}>
|
||||
<div
|
||||
className="relative border-2 border-dashed rounded-lg p-4 text-center transition-colors cursor-pointer"
|
||||
style={{
|
||||
borderColor: uploadFile ? 'rgba(255, 122, 204, 0.5)' : 'var(--card-border)',
|
||||
backgroundColor: uploadFile ? 'rgba(255, 122, 204, 0.05)' : 'transparent',
|
||||
}}
|
||||
>
|
||||
<Input
|
||||
type="file"
|
||||
accept=".mp3,.wav,.flac,.m4a,.ogg,audio/*"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) setUploadFile(file)
|
||||
}}
|
||||
className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
|
||||
disabled={isSubmittingFallback}
|
||||
/>
|
||||
{uploadFile ? (
|
||||
<div>
|
||||
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>{uploadFile.name}</p>
|
||||
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>{(uploadFile.size / 1024 / 1024).toFixed(2)} MB</p>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<Upload className="w-6 h-6 mx-auto mb-1" style={{ color: 'var(--text-muted)' }} />
|
||||
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>MP3, WAV, FLAC, M4A, or OGG</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
disabled={!uploadFile || isSubmittingFallback || noCredits}
|
||||
className="w-full bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white"
|
||||
>
|
||||
{isSubmittingFallback ? (
|
||||
<><Loader2 className="w-3 h-3 mr-1 animate-spin" /> Uploading...</>
|
||||
) : (
|
||||
"Upload & Create"
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
"use client"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { ArrowLeft, Loader2 } from "lucide-react"
|
||||
import { TitleCardPreview } from "../TitleCardPreview"
|
||||
|
||||
interface CustomizeStepProps {
|
||||
artist: string
|
||||
title: string
|
||||
displayArtist: string
|
||||
displayTitle: string
|
||||
onDisplayArtistChange: (value: string) => void
|
||||
onDisplayTitleChange: (value: string) => void
|
||||
isPrivate: boolean
|
||||
onPrivateChange: (value: boolean) => void
|
||||
onConfirm: () => void
|
||||
onBack: () => void
|
||||
isSubmitting: boolean
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
export function CustomizeStep({
|
||||
artist,
|
||||
title,
|
||||
displayArtist,
|
||||
displayTitle,
|
||||
onDisplayArtistChange,
|
||||
onDisplayTitleChange,
|
||||
isPrivate,
|
||||
onPrivateChange,
|
||||
onConfirm,
|
||||
onBack,
|
||||
isSubmitting,
|
||||
disabled,
|
||||
}: CustomizeStepProps) {
|
||||
// The displayed artist/title on the title card
|
||||
const previewArtist = displayArtist.trim() || artist
|
||||
const previewTitle = displayTitle.trim() || title
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold" style={{ color: 'var(--text)' }}>
|
||||
Customize & Create
|
||||
</h2>
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>
|
||||
Preview your title card and confirm your settings.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onBack}
|
||||
disabled={disabled || isSubmitting}
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4 mr-1" />
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Title card preview - half width, centered */}
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs" style={{ color: 'var(--text-muted)' }}>Title Card Preview</Label>
|
||||
<div className="mx-auto w-full sm:w-1/2">
|
||||
<TitleCardPreview artist={previewArtist} title={previewTitle} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Display override fields */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="guided-display-artist" className="text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
Title Card Artist
|
||||
{!displayArtist.trim() && artist.trim() && (
|
||||
<span className="ml-1 opacity-50">(same as above)</span>
|
||||
)}
|
||||
</Label>
|
||||
<Input
|
||||
id="guided-display-artist"
|
||||
placeholder={artist || "Artist on title card"}
|
||||
value={displayArtist}
|
||||
onChange={(e) => onDisplayArtistChange(e.target.value)}
|
||||
disabled={disabled || isSubmitting}
|
||||
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="guided-display-title" className="text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
Title Card Title
|
||||
{!displayTitle.trim() && title.trim() && (
|
||||
<span className="ml-1 opacity-50">(same as above)</span>
|
||||
)}
|
||||
</Label>
|
||||
<Input
|
||||
id="guided-display-title"
|
||||
placeholder={title || "Title on title card"}
|
||||
value={displayTitle}
|
||||
onChange={(e) => onDisplayTitleChange(e.target.value)}
|
||||
disabled={disabled || isSubmitting}
|
||||
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
|
||||
These default to your search values. Override for soundtracks, covers, or alternate formatting.
|
||||
</p>
|
||||
|
||||
{/* Privacy toggle */}
|
||||
<div className="space-y-2 pt-2 border-t" style={{ borderColor: 'var(--card-border)' }}>
|
||||
<div className="flex items-start gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="guided-private"
|
||||
checked={isPrivate}
|
||||
onChange={(e) => onPrivateChange(e.target.checked)}
|
||||
disabled={disabled || isSubmitting}
|
||||
className="mt-1 w-4 h-4 rounded border-border bg-secondary accent-[var(--brand-pink)] focus:ring-[var(--brand-pink)] focus:ring-offset-background"
|
||||
/>
|
||||
<div>
|
||||
<Label htmlFor="guided-private" className="cursor-pointer" style={{ color: 'var(--text)' }}>
|
||||
Private (no YouTube upload)
|
||||
</Label>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
Files delivered via Dropbox only. No YouTube or Google Drive upload.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Create button */}
|
||||
<Button
|
||||
onClick={onConfirm}
|
||||
disabled={disabled || isSubmitting}
|
||||
className="w-full bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white shadow-[0_0_15px_rgba(255,122,204,0.3)] hover:shadow-[0_0_20px_rgba(255,122,204,0.5)] h-11 text-base"
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Creating...
|
||||
</>
|
||||
) : (
|
||||
"Create Karaoke Video"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
"use client"
|
||||
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ArrowRight, Lightbulb, Pencil, Search, Upload, Youtube } from "lucide-react"
|
||||
|
||||
interface SongInfoStepProps {
|
||||
artist: string
|
||||
title: string
|
||||
onArtistChange: (value: string) => void
|
||||
onTitleChange: (value: string) => void
|
||||
onNext: () => void
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
export function SongInfoStep({
|
||||
artist,
|
||||
title,
|
||||
onArtistChange,
|
||||
onTitleChange,
|
||||
onNext,
|
||||
disabled,
|
||||
}: SongInfoStepProps) {
|
||||
const canProceed = artist.trim() && title.trim()
|
||||
|
||||
function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
if (canProceed) onNext()
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-5">
|
||||
{/* How it works - compact visual */}
|
||||
<div className="flex items-center gap-3 text-xs flex-wrap" style={{ color: 'var(--text-muted)' }}>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Search className="w-3.5 h-3.5" style={{ color: 'var(--brand-pink)' }} />
|
||||
<span>We find the best audio</span>
|
||||
</div>
|
||||
<span className="opacity-40">or</span>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Upload className="w-3.5 h-3.5 text-amber-400" />
|
||||
<span>upload a file</span>
|
||||
</div>
|
||||
<span className="opacity-40">/</span>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Youtube className="w-3.5 h-3.5 text-red-400" />
|
||||
<span>YouTube URL</span>
|
||||
</div>
|
||||
<span className="opacity-50">(on next page)</span>
|
||||
</div>
|
||||
|
||||
{/* Search artist/title */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="guided-artist" style={{ color: 'var(--text)' }}>Artist</Label>
|
||||
<Input
|
||||
id="guided-artist"
|
||||
data-testid="guided-artist-input"
|
||||
placeholder="e.g. Queen"
|
||||
value={artist}
|
||||
onChange={(e) => onArtistChange(e.target.value)}
|
||||
disabled={disabled}
|
||||
autoFocus
|
||||
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="guided-title" style={{ color: 'var(--text)' }}>Title</Label>
|
||||
<Input
|
||||
id="guided-title"
|
||||
data-testid="guided-title-input"
|
||||
placeholder="e.g. Bohemian Rhapsody"
|
||||
value={title}
|
||||
onChange={(e) => onTitleChange(e.target.value)}
|
||||
disabled={disabled}
|
||||
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tip callout */}
|
||||
<div
|
||||
className="flex items-start gap-2.5 rounded-lg p-3 text-xs"
|
||||
style={{ backgroundColor: 'var(--secondary)', color: 'var(--text-muted)' }}
|
||||
>
|
||||
<Lightbulb className="w-4 h-4 shrink-0 mt-0.5 text-amber-400" />
|
||||
<p>
|
||||
Looking for a specific version (live, cover, remix)? Include those details in the title - e.g. "Bohemian Rhapsody - Live at Wembley".
|
||||
<br className="mt-1" />
|
||||
If we can't find the right audio, you can provide a YouTube URL or upload a file on the next page.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Custom lyrics note */}
|
||||
<div
|
||||
className="flex items-start gap-2.5 rounded-lg p-3 text-xs"
|
||||
style={{ backgroundColor: 'var(--secondary)', color: 'var(--text-muted)' }}
|
||||
>
|
||||
<Pencil className="w-4 h-4 shrink-0 mt-0.5 text-purple-400" />
|
||||
<p>
|
||||
Making a video with custom lyrics? Start with the artist/title of the original song here - you can change the title screen and lyrics later.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={!canProceed || disabled}
|
||||
className="w-full bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white shadow-[0_0_15px_rgba(255,122,204,0.3)] hover:shadow-[0_0_20px_rgba(255,122,204,0.5)]"
|
||||
>
|
||||
Choose Audio
|
||||
<ArrowRight className="w-4 h-4 ml-2" />
|
||||
</Button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -25,6 +25,7 @@ interface CorrectedWordWithActionsProps {
|
||||
backgroundColor?: string
|
||||
shouldFlash?: boolean
|
||||
showActions?: boolean
|
||||
id?: string
|
||||
}
|
||||
|
||||
export default function CorrectedWordWithActions({
|
||||
@@ -37,6 +38,7 @@ export default function CorrectedWordWithActions({
|
||||
backgroundColor,
|
||||
shouldFlash,
|
||||
showActions = true,
|
||||
id,
|
||||
}: CorrectedWordWithActionsProps) {
|
||||
const handleAction = (e: React.MouseEvent, action: () => void) => {
|
||||
e.stopPropagation()
|
||||
@@ -45,6 +47,7 @@ export default function CorrectedWordWithActions({
|
||||
|
||||
return (
|
||||
<span
|
||||
id={id}
|
||||
className={cn(
|
||||
'inline-flex items-center gap-0.5 px-[3px] py-[1px] rounded-sm cursor-pointer relative',
|
||||
'hover:bg-green-500/35',
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef, useCallback } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { X } from 'lucide-react'
|
||||
import type { EditLogEntry, EditFeedbackReason } from '@/lib/lyrics-review/types'
|
||||
|
||||
const REASONS_BY_OP: Record<string, { label: string; reason: EditFeedbackReason }[]> = {
|
||||
word_change: [
|
||||
{ label: 'Mis-heard word', reason: 'misheard_word' },
|
||||
{ label: 'Wrong lyrics', reason: 'wrong_lyrics' },
|
||||
{ label: 'Spelling/punctuation', reason: 'spelling_punctuation' },
|
||||
{ label: 'Other', reason: 'other' },
|
||||
],
|
||||
word_delete: [
|
||||
{ label: 'Phantom word', reason: 'phantom_word' },
|
||||
{ label: 'Duplicate', reason: 'duplicate_word' },
|
||||
{ label: 'Mis-heard word', reason: 'misheard_word' },
|
||||
{ label: 'Other', reason: 'other' },
|
||||
],
|
||||
word_add: [
|
||||
{ label: 'Missing word', reason: 'missing_word' },
|
||||
{ label: 'Split word', reason: 'split_word' },
|
||||
{ label: 'Other', reason: 'other' },
|
||||
],
|
||||
}
|
||||
|
||||
function getQuestionText(entry: EditLogEntry): string {
|
||||
const before = entry.text_before.trim()
|
||||
const after = entry.text_after.trim()
|
||||
switch (entry.operation) {
|
||||
case 'word_change':
|
||||
return `Changed "${before}" → "${after}", why?`
|
||||
case 'word_delete':
|
||||
return `Removed "${before}", why?`
|
||||
case 'word_add':
|
||||
return `Added "${after}", why?`
|
||||
default:
|
||||
return `Edit made, why?`
|
||||
}
|
||||
}
|
||||
|
||||
interface EditFeedbackBarProps {
|
||||
entry: EditLogEntry | null
|
||||
visible: boolean
|
||||
onFeedback: (entryId: string, reason: EditFeedbackReason) => void
|
||||
onDismiss: () => void
|
||||
}
|
||||
|
||||
export default function EditFeedbackBar({
|
||||
entry,
|
||||
visible,
|
||||
onFeedback,
|
||||
onDismiss,
|
||||
}: EditFeedbackBarProps) {
|
||||
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const entryIdRef = useRef<string | null>(null)
|
||||
const hoveredRef = useRef(false)
|
||||
const remainingRef = useRef(10_000)
|
||||
const startedAtRef = useRef<number | null>(null)
|
||||
|
||||
const clearTimer = useCallback(() => {
|
||||
if (timerRef.current) {
|
||||
clearTimeout(timerRef.current)
|
||||
timerRef.current = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
const startTimer = useCallback((ms: number) => {
|
||||
clearTimer()
|
||||
startedAtRef.current = Date.now()
|
||||
remainingRef.current = ms
|
||||
timerRef.current = setTimeout(() => {
|
||||
if (entry) {
|
||||
onFeedback(entry.id, 'no_response')
|
||||
onDismiss()
|
||||
}
|
||||
}, ms)
|
||||
}, [clearTimer, entry, onFeedback, onDismiss])
|
||||
|
||||
const handleMouseEnter = useCallback(() => {
|
||||
hoveredRef.current = true
|
||||
if (timerRef.current && startedAtRef.current !== null) {
|
||||
const elapsed = Date.now() - startedAtRef.current
|
||||
remainingRef.current = Math.max(0, remainingRef.current - elapsed)
|
||||
clearTimer()
|
||||
}
|
||||
}, [clearTimer])
|
||||
|
||||
const handleMouseLeave = useCallback(() => {
|
||||
hoveredRef.current = false
|
||||
if (visible && entry && remainingRef.current > 0) {
|
||||
startTimer(remainingRef.current)
|
||||
}
|
||||
}, [visible, entry, startTimer])
|
||||
|
||||
useEffect(() => {
|
||||
clearTimer()
|
||||
|
||||
if (!visible || !entry) return
|
||||
|
||||
// If this is a new entry, start the auto-dismiss timer
|
||||
if (entry.id !== entryIdRef.current) {
|
||||
entryIdRef.current = entry.id
|
||||
remainingRef.current = 10_000
|
||||
if (!hoveredRef.current) {
|
||||
startTimer(10_000)
|
||||
}
|
||||
}
|
||||
|
||||
return clearTimer
|
||||
}, [visible, entry, clearTimer, startTimer])
|
||||
|
||||
if (!visible || !entry) return null
|
||||
|
||||
const reasons = REASONS_BY_OP[entry.operation] ?? REASONS_BY_OP.word_change
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed bottom-[52px] left-0 right-0 z-40 flex justify-center animate-in slide-in-from-bottom-2 duration-200"
|
||||
onMouseEnter={handleMouseEnter}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
>
|
||||
<div className="bg-muted/95 backdrop-blur-sm border-t border-b px-4 py-2 flex items-center gap-3 w-full max-w-4xl">
|
||||
<span className="text-sm text-muted-foreground shrink-0 truncate max-w-[280px]">
|
||||
{getQuestionText(entry)}
|
||||
</span>
|
||||
<div className="flex items-center gap-1.5 flex-wrap">
|
||||
{reasons.map((r) => (
|
||||
<Button
|
||||
key={r.reason}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 text-xs px-2.5"
|
||||
onClick={() => {
|
||||
clearTimer()
|
||||
onFeedback(entry.id, r.reason)
|
||||
onDismiss()
|
||||
}}
|
||||
>
|
||||
{r.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 w-7 p-0 ml-auto shrink-0"
|
||||
onClick={() => {
|
||||
clearTimer()
|
||||
onFeedback(entry.id, 'no_response')
|
||||
onDismiss()
|
||||
}}
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
'use client'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from '@/components/ui/tooltip'
|
||||
import { ChevronLeft, ChevronRight } from 'lucide-react'
|
||||
|
||||
interface GapNavigatorProps {
|
||||
currentGapIndex: number | null
|
||||
totalGaps: number
|
||||
onPrevGap: () => void
|
||||
onNextGap: () => void
|
||||
}
|
||||
|
||||
export default function GapNavigator({
|
||||
currentGapIndex,
|
||||
totalGaps,
|
||||
onPrevGap,
|
||||
onNextGap,
|
||||
}: GapNavigatorProps) {
|
||||
if (totalGaps === 0) return null
|
||||
|
||||
const displayIndex = currentGapIndex !== null ? currentGapIndex + 1 : 0
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="h-7 w-7"
|
||||
onClick={onPrevGap}
|
||||
disabled={currentGapIndex === null || currentGapIndex <= 0}
|
||||
aria-label="Previous gap"
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Previous gap (P)</TooltipContent>
|
||||
</Tooltip>
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap">
|
||||
Gap {displayIndex} of {totalGaps}
|
||||
</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="h-7 w-7"
|
||||
onClick={onNextGap}
|
||||
disabled={currentGapIndex !== null && currentGapIndex >= totalGaps - 1}
|
||||
aria-label="Next gap"
|
||||
>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Next gap (N)</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { Card } from '@/components/ui/card'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from '@/components/ui/tooltip'
|
||||
import { Lightbulb, X } from 'lucide-react'
|
||||
import { CorrectionData } from '@/lib/lyrics-review/types'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface GuidancePanelProps {
|
||||
data: CorrectionData
|
||||
isReadOnly: boolean
|
||||
onMetricClick: {
|
||||
anchor: () => void
|
||||
corrected: () => void
|
||||
uncorrected: () => void
|
||||
}
|
||||
onHandlerToggle: (handler: string, enabled: boolean) => void
|
||||
isUpdatingHandlers: boolean
|
||||
onHandlerClick?: (handler: string) => void
|
||||
statsVisible: boolean
|
||||
onStatsToggle: () => void
|
||||
}
|
||||
|
||||
export default function GuidancePanel({
|
||||
data,
|
||||
isReadOnly,
|
||||
onMetricClick,
|
||||
onHandlerToggle,
|
||||
isUpdatingHandlers,
|
||||
onHandlerClick,
|
||||
statsVisible,
|
||||
onStatsToggle,
|
||||
}: GuidancePanelProps) {
|
||||
const [guidanceDismissed, setGuidanceDismissed] = useState(() => {
|
||||
if (typeof window === 'undefined') return false
|
||||
return localStorage.getItem('lyricsReviewGuidanceDismissed') === 'true'
|
||||
})
|
||||
|
||||
const isMobile = typeof window !== 'undefined' && window.innerWidth < 768
|
||||
|
||||
// Calculate metrics
|
||||
const gapCorrections = data.corrections.reduce(
|
||||
(map: Record<string, number>, correction) => {
|
||||
const gap = data.gap_sequences.find((g) =>
|
||||
g.transcribed_word_ids.includes(correction.word_id)
|
||||
)
|
||||
if (gap) {
|
||||
map[gap.id] = (map[gap.id] || 0) + 1
|
||||
}
|
||||
return map
|
||||
},
|
||||
{} as Record<string, number>
|
||||
)
|
||||
|
||||
const correctedGapCount = Object.keys(gapCorrections).length
|
||||
const uncorrectedGapCount = data.gap_sequences.length - correctedGapCount
|
||||
const totalGaps = data.gap_sequences.length
|
||||
|
||||
// Handler info
|
||||
const handlerCounts =
|
||||
data.corrections?.reduce(
|
||||
(counts: Record<string, number>, correction) => {
|
||||
counts[correction.handler] = (counts[correction.handler] || 0) + 1
|
||||
return counts
|
||||
},
|
||||
{} as Record<string, number>
|
||||
) || {}
|
||||
|
||||
const availableHandlers = data.metadata.available_handlers || []
|
||||
const enabledHandlers = new Set(data.metadata.enabled_handlers || [])
|
||||
|
||||
// Detailed metrics
|
||||
const totalWords = data.metadata.total_words || 0
|
||||
const anchorWordCount = data.anchor_sequences?.reduce(
|
||||
(sum, anchor) => sum + (anchor.transcribed_word_ids?.length || 0),
|
||||
0
|
||||
) ?? 0
|
||||
const multiSourceAnchors = data.anchor_sequences?.filter(
|
||||
(anchor) =>
|
||||
anchor?.reference_word_ids && Object.keys(anchor.reference_word_ids).length > 1
|
||||
).length ?? 0
|
||||
const replacedCount = data.corrections.filter(
|
||||
(c) => !c.is_deletion && !c.split_total
|
||||
).length
|
||||
const addedCount = data.corrections.filter((c) => c.split_total).length
|
||||
const deletedCount = data.corrections.filter((c) => c.is_deletion).length
|
||||
const uncorrectedGaps = data.gap_sequences.filter(
|
||||
(gap) => !gapCorrections[gap.id] && gap.transcribed_word_ids.length > 0
|
||||
)
|
||||
const uncorrectedWordCount = uncorrectedGaps.reduce(
|
||||
(sum, gap) => sum + gap.transcribed_word_ids.length,
|
||||
0
|
||||
)
|
||||
const anchorPercentage = totalWords > 0 ? Math.round((anchorWordCount / totalWords) * 100) : 0
|
||||
const correctedWordCount = replacedCount + addedCount
|
||||
const correctedPercentage = totalWords > 0 ? Math.round((correctedWordCount / totalWords) * 100) : 0
|
||||
const uncorrectedPercentage = totalWords > 0 ? Math.round((uncorrectedWordCount / totalWords) * 100) : 0
|
||||
|
||||
const handleDismiss = () => {
|
||||
setGuidanceDismissed(true)
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.setItem('lyricsReviewGuidanceDismissed', 'true')
|
||||
}
|
||||
}
|
||||
|
||||
const handleShowTips = () => {
|
||||
setGuidanceDismissed(false)
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.removeItem('lyricsReviewGuidanceDismissed')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2 mb-2">
|
||||
{/* Color legend row */}
|
||||
<div className="flex items-center gap-3 text-xs flex-wrap">
|
||||
<button
|
||||
className="flex items-center gap-1.5 hover:opacity-80 transition-opacity"
|
||||
onClick={onMetricClick.anchor}
|
||||
>
|
||||
<span className="w-2.5 h-2.5 rounded-full bg-blue-500/60 inline-block" />
|
||||
<span className="text-muted-foreground">Matched</span>
|
||||
</button>
|
||||
<button
|
||||
className="flex items-center gap-1.5 hover:opacity-80 transition-opacity"
|
||||
onClick={onMetricClick.uncorrected}
|
||||
>
|
||||
<span className="w-2.5 h-2.5 rounded-full bg-orange-500/60 inline-block" />
|
||||
<span className="text-muted-foreground">Gaps (needs review)</span>
|
||||
</button>
|
||||
<button
|
||||
className="flex items-center gap-1.5 hover:opacity-80 transition-opacity"
|
||||
onClick={onMetricClick.corrected}
|
||||
>
|
||||
<span className="w-2.5 h-2.5 rounded-full bg-green-500/60 inline-block" />
|
||||
<span className="text-muted-foreground">Corrected</span>
|
||||
</button>
|
||||
|
||||
<div className="flex items-center gap-2 ml-auto">
|
||||
{guidanceDismissed && !isReadOnly && (
|
||||
<button
|
||||
className="text-amber-500 hover:text-amber-400 transition-colors text-xs"
|
||||
onClick={handleShowTips}
|
||||
>
|
||||
Show tips
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
className={cn(
|
||||
'text-xs px-1.5 py-0.5 rounded border transition-colors',
|
||||
statsVisible
|
||||
? 'border-primary text-primary'
|
||||
: 'border-muted text-muted-foreground hover:text-foreground hover:border-foreground/50'
|
||||
)}
|
||||
onClick={onStatsToggle}
|
||||
>
|
||||
{statsVisible ? 'Hide Stats' : 'Stats'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Workflow tips (dismissible) */}
|
||||
{!guidanceDismissed && !isReadOnly && (
|
||||
<div className="flex items-start gap-2 p-2.5 rounded-md bg-amber-500/10 border border-amber-500/20">
|
||||
<Lightbulb className="h-4 w-4 text-amber-500 shrink-0 mt-0.5" />
|
||||
<div className="text-xs text-muted-foreground flex-1 leading-relaxed space-y-1.5">
|
||||
{totalGaps === 0 ? (
|
||||
<p>All lyrics matched the reference — no corrections needed. You can still click any word to edit.</p>
|
||||
) : (
|
||||
<>
|
||||
<p>The <strong>Synced Lyrics</strong> on the left are what will appear in the karaoke video.</p>
|
||||
<p>The orange highlighted words are <strong>gaps</strong> — sections that couldn't be matched to the reference lyrics and may contain errors (e.g. mis-heard words which sound similar).</p>
|
||||
<p>Use <kbd className="px-1 py-0.5 rounded bg-muted text-[0.65rem] font-mono">N</kbd> and <kbd className="px-1 py-0.5 rounded bg-muted text-[0.65rem] font-mono">P</kbd> to jump between gaps. For each one, click play beside the line and compare what you hear with the reference lyrics on the right, then click a word to edit or delete it.</p>
|
||||
<p>Watch out for phantom words like "and" at the start or end of lines — the transcription often adds these.</p>
|
||||
<p>Try the <strong>Timeline</strong> view to spot any unusually long words (10+ seconds), which usually indicate a timing problem.</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
className="text-muted-foreground hover:text-foreground transition-colors shrink-0"
|
||||
onClick={handleDismiss}
|
||||
aria-label="Dismiss tip"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Stats & Handlers (shown when toggled via header button) */}
|
||||
{statsVisible && (
|
||||
<div className={cn('flex gap-2 overflow-hidden', isMobile ? 'flex-col' : 'flex-row', isMobile ? 'h-auto' : 'h-[140px]')}>
|
||||
{/* Handler panel */}
|
||||
<Card className={cn('p-2', isMobile ? 'w-full' : 'w-[280px] min-w-[280px]')}>
|
||||
<h4 className="text-xs text-muted-foreground mb-1">Correction Handlers</h4>
|
||||
<div className="flex-1 overflow-auto flex flex-col">
|
||||
{availableHandlers.map((handler: { id: string; name: string; description: string }) => (
|
||||
<div key={handler.id} className="mb-1">
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
checked={enabledHandlers.has(handler.id)}
|
||||
onCheckedChange={(checked) => onHandlerToggle(handler.id, checked)}
|
||||
disabled={isUpdatingHandlers}
|
||||
className="scale-75"
|
||||
/>
|
||||
<Label
|
||||
className="text-xs cursor-pointer hover:text-foreground hover:underline transition-colors"
|
||||
onClick={() => onHandlerClick?.(handler.id)}
|
||||
>
|
||||
{handler.name} ({handlerCounts[handler.id] || 0})
|
||||
</Label>
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{handler.description}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Metrics panel */}
|
||||
<div className="flex-1 grid grid-cols-3 gap-2 h-full">
|
||||
<Card
|
||||
className="p-2 cursor-pointer hover:bg-muted/30 transition-colors flex flex-col overflow-hidden h-full"
|
||||
onClick={onMetricClick.anchor}
|
||||
>
|
||||
<div className="flex items-center gap-1 mb-0.5">
|
||||
<div className="w-3 h-3 rounded bg-blue-500/25 shrink-0" />
|
||||
<span className="text-xs text-muted-foreground truncate">Anchor Sequences</span>
|
||||
</div>
|
||||
<span className="text-lg font-semibold leading-tight">
|
||||
{data.metadata.anchor_sequences_count ?? '-'} ({anchorPercentage}%)
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground leading-tight">
|
||||
Matched sections between transcription and reference
|
||||
</span>
|
||||
<div className="mt-auto space-y-0 text-[10px]">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Words in Anchors</span>
|
||||
<span>{anchorWordCount}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Multi-source Matches</span>
|
||||
<span>{multiSourceAnchors}</span>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
className="p-2 cursor-pointer hover:bg-muted/30 transition-colors flex flex-col overflow-hidden h-full"
|
||||
onClick={onMetricClick.corrected}
|
||||
>
|
||||
<div className="flex items-center gap-1 mb-0.5">
|
||||
<div className="w-3 h-3 rounded bg-green-500/25 shrink-0" />
|
||||
<span className="text-xs text-muted-foreground truncate">Corrected Gaps</span>
|
||||
</div>
|
||||
<span className="text-lg font-semibold text-green-500 leading-tight">
|
||||
{correctedGapCount} ({correctedPercentage}%)
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground leading-tight">
|
||||
Successfully corrected sections
|
||||
</span>
|
||||
<div className="mt-auto space-y-0 text-[10px]">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Words Replaced</span>
|
||||
<span>{replacedCount}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Words Added / Deleted</span>
|
||||
<span>+{addedCount} / -{deletedCount}</span>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
className="p-2 cursor-pointer hover:bg-muted/30 transition-colors flex flex-col overflow-hidden h-full"
|
||||
onClick={onMetricClick.uncorrected}
|
||||
>
|
||||
<div className="flex items-center gap-1 mb-0.5">
|
||||
<div className="w-3 h-3 rounded bg-orange-500/25 shrink-0" />
|
||||
<span className="text-xs text-muted-foreground truncate">Uncorrected Gaps</span>
|
||||
</div>
|
||||
<span className="text-lg font-semibold text-amber-500 leading-tight">
|
||||
{uncorrectedGapCount} ({uncorrectedPercentage}%)
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground leading-tight">
|
||||
Sections that may need manual review
|
||||
</span>
|
||||
<div className="mt-auto space-y-0 text-[10px]">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Words Uncorrected</span>
|
||||
<span>{uncorrectedWordCount}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Number of Gaps</span>
|
||||
<span>{uncorrectedGaps.length}</span>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Card } from '@/components/ui/card'
|
||||
import {
|
||||
@@ -19,8 +17,6 @@ import {
|
||||
Undo2,
|
||||
Redo2,
|
||||
Timer,
|
||||
RotateCcw,
|
||||
MessageSquare,
|
||||
Eye,
|
||||
CheckCircle2,
|
||||
XCircle,
|
||||
@@ -28,7 +24,7 @@ import {
|
||||
import { CorrectionData, InteractionMode } from '@/lib/lyrics-review/types'
|
||||
import ModeSelector from './ModeSelector'
|
||||
import AudioPlayer from './AudioPlayer'
|
||||
import { findWordById } from '@/lib/lyrics-review/utils/wordUtils'
|
||||
import GuidancePanel from './GuidancePanel'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface ApiClient {
|
||||
@@ -54,7 +50,6 @@ interface HeaderProps {
|
||||
onHandlerClick?: (handler: string) => void
|
||||
onFindReplace?: () => void
|
||||
onEditAll?: () => void
|
||||
onUnCorrectAll?: () => void
|
||||
onResetCorrections?: () => void
|
||||
onTimingOffset?: () => void
|
||||
timingOffsetMs?: number
|
||||
@@ -62,8 +57,8 @@ interface HeaderProps {
|
||||
onRedo: () => void
|
||||
canUndo: boolean
|
||||
canRedo: boolean
|
||||
annotationsEnabled?: boolean
|
||||
onAnnotationsToggle?: (enabled: boolean) => void
|
||||
statsVisible: boolean
|
||||
onStatsToggle: () => void
|
||||
reviewMode?: boolean
|
||||
onReviewModeToggle?: (enabled: boolean) => void
|
||||
onAcceptAllCorrections?: () => void
|
||||
@@ -86,7 +81,6 @@ export default function Header({
|
||||
onHandlerClick,
|
||||
onFindReplace,
|
||||
onEditAll,
|
||||
onUnCorrectAll,
|
||||
onResetCorrections,
|
||||
onTimingOffset,
|
||||
timingOffsetMs = 0,
|
||||
@@ -94,8 +88,8 @@ export default function Header({
|
||||
onRedo,
|
||||
canUndo,
|
||||
canRedo,
|
||||
annotationsEnabled = true,
|
||||
onAnnotationsToggle,
|
||||
statsVisible,
|
||||
onStatsToggle,
|
||||
reviewMode = false,
|
||||
onReviewModeToggle,
|
||||
onAcceptAllCorrections,
|
||||
@@ -104,75 +98,12 @@ export default function Header({
|
||||
}: HeaderProps) {
|
||||
const isMobile = typeof window !== 'undefined' && window.innerWidth < 768
|
||||
|
||||
// Get handlers with their correction counts
|
||||
const handlerCounts =
|
||||
data.corrections?.reduce(
|
||||
(counts: Record<string, number>, correction) => {
|
||||
counts[correction.handler] = (counts[correction.handler] || 0) + 1
|
||||
return counts
|
||||
},
|
||||
{} as Record<string, number>
|
||||
) || {}
|
||||
|
||||
// Get available handlers from metadata
|
||||
const availableHandlers = data.metadata.available_handlers || []
|
||||
const enabledHandlers = new Set(data.metadata.enabled_handlers || [])
|
||||
|
||||
// Check if agentic mode is active
|
||||
const availableHandlers = data.metadata.available_handlers || []
|
||||
const isAgenticMode = availableHandlers.some(
|
||||
(h: { id: string }) => h.id === 'AgenticCorrector'
|
||||
)
|
||||
|
||||
// Create a map of gap IDs to their corrections
|
||||
const gapCorrections = data.corrections.reduce(
|
||||
(map: Record<string, number>, correction) => {
|
||||
const gap = data.gap_sequences.find((g) =>
|
||||
g.transcribed_word_ids.includes(correction.word_id)
|
||||
)
|
||||
if (gap) {
|
||||
map[gap.id] = (map[gap.id] || 0) + 1
|
||||
}
|
||||
return map
|
||||
},
|
||||
{} as Record<string, number>
|
||||
)
|
||||
|
||||
// Calculate metrics
|
||||
const correctedGapCount = Object.keys(gapCorrections).length
|
||||
const uncorrectedGapCount = data.gap_sequences.length - correctedGapCount
|
||||
|
||||
// Calculate correction type counts
|
||||
const replacedCount = data.corrections.filter(
|
||||
(c) => !c.is_deletion && !c.split_total
|
||||
).length
|
||||
const addedCount = data.corrections.filter((c) => c.split_total).length
|
||||
const deletedCount = data.corrections.filter((c) => c.is_deletion).length
|
||||
|
||||
// Calculate additional metrics for detailed display (matching old CorrectionMetrics)
|
||||
const totalWords = data.metadata.total_words || 0
|
||||
const anchorWordCount = data.anchor_sequences?.reduce(
|
||||
(sum, anchor) => sum + (anchor.transcribed_word_ids?.length || 0),
|
||||
0
|
||||
) ?? 0
|
||||
const multiSourceAnchors = data.anchor_sequences?.filter(
|
||||
(anchor) =>
|
||||
anchor?.reference_word_ids && Object.keys(anchor.reference_word_ids).length > 1
|
||||
).length ?? 0
|
||||
|
||||
// Calculate uncorrected gaps info
|
||||
const uncorrectedGaps = data.gap_sequences
|
||||
.filter((gap) => !gapCorrections[gap.id] && gap.transcribed_word_ids.length > 0)
|
||||
const uncorrectedWordCount = uncorrectedGaps.reduce(
|
||||
(sum, gap) => sum + gap.transcribed_word_ids.length,
|
||||
0
|
||||
)
|
||||
|
||||
// Calculate percentages
|
||||
const anchorPercentage = totalWords > 0 ? Math.round((anchorWordCount / totalWords) * 100) : 0
|
||||
const correctedWordCount = replacedCount + addedCount
|
||||
const correctedPercentage = totalWords > 0 ? Math.round((correctedWordCount / totalWords) * 100) : 0
|
||||
const uncorrectedPercentage = totalWords > 0 ? Math.round((uncorrectedWordCount / totalWords) * 100) : 0
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<div className="space-y-2">
|
||||
@@ -185,152 +116,47 @@ export default function Header({
|
||||
)}
|
||||
|
||||
{/* Review Mode toggle and Load File button */}
|
||||
<div className="flex gap-2 justify-end items-center mb-2">
|
||||
{!isReadOnly && isAgenticMode && onReviewModeToggle && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Badge
|
||||
variant={reviewMode ? 'default' : 'outline'}
|
||||
className="cursor-pointer hover:opacity-80 transition-opacity"
|
||||
onClick={() => onReviewModeToggle(!reviewMode)}
|
||||
>
|
||||
<Eye className="h-3 w-3 mr-1" />
|
||||
{reviewMode ? 'Review Mode' : 'Review Off'}
|
||||
</Badge>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
{reviewMode
|
||||
? 'Hide inline correction actions'
|
||||
: 'Show inline actions on all corrections for quick review'}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
{isReadOnly && (
|
||||
<Button variant="outline" size="sm" onClick={onFileLoad} className={cn(isMobile && 'w-full')}>
|
||||
<Upload className="h-4 w-4 mr-1" />
|
||||
Load File
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Handler panel and metrics */}
|
||||
<div className={cn('flex gap-2 mb-2 overflow-hidden', isMobile ? 'flex-col' : 'flex-row', isMobile ? 'h-auto' : 'h-[140px]')}>
|
||||
{/* Handler panel */}
|
||||
<Card className={cn('p-2', isMobile ? 'w-full' : 'w-[280px] min-w-[280px]')}>
|
||||
<h4 className="text-xs text-muted-foreground mb-1">Correction Handlers</h4>
|
||||
<div className="flex-1 overflow-auto flex flex-col">
|
||||
{availableHandlers.map((handler: { id: string; name: string; description: string }) => (
|
||||
<div key={handler.id} className="mb-1">
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
checked={enabledHandlers.has(handler.id)}
|
||||
onCheckedChange={(checked) => onHandlerToggle(handler.id, checked)}
|
||||
disabled={isUpdatingHandlers}
|
||||
className="scale-75"
|
||||
/>
|
||||
<Label
|
||||
className="text-xs cursor-pointer hover:text-foreground hover:underline transition-colors"
|
||||
onClick={() => onHandlerClick?.(handler.id)}
|
||||
>
|
||||
{handler.name} ({handlerCounts[handler.id] || 0})
|
||||
</Label>
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{handler.description}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Metrics panel - matches old CorrectionMetrics component */}
|
||||
<div className="flex-1 grid grid-cols-3 gap-2 h-full">
|
||||
{/* Anchor Sequences */}
|
||||
<Card
|
||||
className="p-2 cursor-pointer hover:bg-muted/30 transition-colors flex flex-col overflow-hidden h-full"
|
||||
onClick={onMetricClick.anchor}
|
||||
>
|
||||
<div className="flex items-center gap-1 mb-0.5">
|
||||
<div className="w-3 h-3 rounded bg-blue-500/25 shrink-0" />
|
||||
<span className="text-xs text-muted-foreground truncate">Anchor Sequences</span>
|
||||
</div>
|
||||
<span className="text-lg font-semibold leading-tight">
|
||||
{data.metadata.anchor_sequences_count ?? '-'} ({anchorPercentage}%)
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground leading-tight">
|
||||
Matched sections between transcription and reference
|
||||
</span>
|
||||
<div className="mt-auto space-y-0 text-[10px]">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Words in Anchors</span>
|
||||
<span>{anchorWordCount}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Multi-source Matches</span>
|
||||
<span>{multiSourceAnchors}</span>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Corrected Gaps */}
|
||||
<Card
|
||||
className="p-2 cursor-pointer hover:bg-muted/30 transition-colors flex flex-col overflow-hidden h-full"
|
||||
onClick={onMetricClick.corrected}
|
||||
>
|
||||
<div className="flex items-center gap-1 mb-0.5">
|
||||
<div className="w-3 h-3 rounded bg-green-500/25 shrink-0" />
|
||||
<span className="text-xs text-muted-foreground truncate">Corrected Gaps</span>
|
||||
</div>
|
||||
<span className="text-lg font-semibold text-green-500 leading-tight">
|
||||
{correctedGapCount} ({correctedPercentage}%)
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground leading-tight">
|
||||
Successfully corrected sections
|
||||
</span>
|
||||
<div className="mt-auto space-y-0 text-[10px]">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Words Replaced</span>
|
||||
<span>{replacedCount}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Words Added / Deleted</span>
|
||||
<span>+{addedCount} / -{deletedCount}</span>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Uncorrected Gaps */}
|
||||
<Card
|
||||
className="p-2 cursor-pointer hover:bg-muted/30 transition-colors flex flex-col overflow-hidden h-full"
|
||||
onClick={onMetricClick.uncorrected}
|
||||
>
|
||||
<div className="flex items-center gap-1 mb-0.5">
|
||||
<div className="w-3 h-3 rounded bg-orange-500/25 shrink-0" />
|
||||
<span className="text-xs text-muted-foreground truncate">Uncorrected Gaps</span>
|
||||
</div>
|
||||
<span className="text-lg font-semibold text-amber-500 leading-tight">
|
||||
{uncorrectedGapCount} ({uncorrectedPercentage}%)
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground leading-tight">
|
||||
Sections that may need manual review
|
||||
</span>
|
||||
<div className="mt-auto space-y-0 text-[10px]">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Words Uncorrected</span>
|
||||
<span>{uncorrectedWordCount}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Number of Gaps</span>
|
||||
<span>{uncorrectedGaps.length}</span>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
{(!isReadOnly && isAgenticMode && onReviewModeToggle) || isReadOnly ? (
|
||||
<div className="flex gap-2 justify-end items-center mb-2">
|
||||
{!isReadOnly && isAgenticMode && onReviewModeToggle && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Badge
|
||||
variant={reviewMode ? 'default' : 'outline'}
|
||||
className="cursor-pointer hover:opacity-80 transition-opacity"
|
||||
onClick={() => onReviewModeToggle(!reviewMode)}
|
||||
>
|
||||
<Eye className="h-3 w-3 mr-1" />
|
||||
{reviewMode ? 'Review Mode' : 'Review Off'}
|
||||
</Badge>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
{reviewMode
|
||||
? 'Hide inline correction actions'
|
||||
: 'Show inline actions on all corrections for quick review'}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
{isReadOnly && (
|
||||
<Button variant="outline" size="sm" onClick={onFileLoad} className={cn(isMobile && 'w-full')}>
|
||||
<Upload className="h-4 w-4 mr-1" />
|
||||
Load File
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Guidance panel with color legend, tips, and conditionally visible stats */}
|
||||
<GuidancePanel
|
||||
data={data}
|
||||
isReadOnly={isReadOnly}
|
||||
onMetricClick={onMetricClick}
|
||||
onHandlerToggle={onHandlerToggle}
|
||||
isUpdatingHandlers={isUpdatingHandlers}
|
||||
onHandlerClick={onHandlerClick}
|
||||
statsVisible={statsVisible}
|
||||
onStatsToggle={onStatsToggle}
|
||||
/>
|
||||
|
||||
{/* Batch Actions Panel */}
|
||||
{!isReadOnly && reviewMode && isAgenticMode && data.corrections?.length > 0 && (
|
||||
@@ -396,7 +222,7 @@ export default function Header({
|
||||
Undo All
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Undo all your changes</TooltipContent>
|
||||
<TooltipContent className="max-w-xs">Reset all changes back to the original AI-corrected lyrics</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
@@ -434,71 +260,54 @@ export default function Header({
|
||||
)}
|
||||
|
||||
{!isReadOnly && (
|
||||
<Button variant="outline" size="sm" onClick={onFindReplace} className="h-8 text-xs">
|
||||
<Search className="h-3.5 w-3.5 mr-1" />
|
||||
Find/Replace
|
||||
</Button>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button variant="outline" size="sm" onClick={onFindReplace} className="h-8 text-xs">
|
||||
<Search className="h-3.5 w-3.5 mr-1" />
|
||||
Find/Replace
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent className="max-w-xs">Search for text across all lyrics and replace it. Useful for a word that appears multiple times.</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
{!isReadOnly && onEditAll && (
|
||||
<Button variant="outline" size="sm" onClick={onEditAll} className="h-8 text-xs">
|
||||
<Edit className="h-3.5 w-3.5 mr-1" />
|
||||
Edit All
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{!isReadOnly && onUnCorrectAll && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button variant="outline" size="sm" onClick={onUnCorrectAll} className="h-8 text-xs">
|
||||
<RotateCcw className="h-3.5 w-3.5 mr-1" />
|
||||
Undo Auto Corrections
|
||||
<Button variant="outline" size="sm" onClick={onEditAll} className="h-8 text-xs">
|
||||
<Edit className="h-3.5 w-3.5 mr-1" />
|
||||
Edit All
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Revert only automatic AI corrections (keeps your manual edits)</TooltipContent>
|
||||
<TooltipContent className="max-w-xs">View and edit all lyrics as plain text. Useful when many lines need changing.</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
{!isReadOnly && onTimingOffset && (
|
||||
<div className="flex items-center">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onTimingOffset}
|
||||
className={cn('h-8 text-xs', timingOffsetMs !== 0 && 'border-purple-500 text-purple-500')}
|
||||
>
|
||||
<Timer className="h-3.5 w-3.5 mr-1" />
|
||||
Timing Offset
|
||||
</Button>
|
||||
{timingOffsetMs !== 0 && (
|
||||
<span className="ml-1 text-xs font-bold text-purple-500">
|
||||
{timingOffsetMs > 0 ? '+' : ''}
|
||||
{timingOffsetMs}ms
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isReadOnly && onAnnotationsToggle && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onAnnotationsToggle(!annotationsEnabled)}
|
||||
className={cn('h-8 text-xs', annotationsEnabled && 'border-primary')}
|
||||
>
|
||||
<MessageSquare className="h-3.5 w-3.5 mr-1" />
|
||||
{annotationsEnabled ? 'Feedback On' : 'Feedback Off'}
|
||||
</Button>
|
||||
<div className="flex items-center">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onTimingOffset}
|
||||
className={cn('h-8 text-xs', timingOffsetMs !== 0 && 'border-purple-500 text-purple-500')}
|
||||
>
|
||||
<Timer className="h-3.5 w-3.5 mr-1" />
|
||||
Timing Offset
|
||||
</Button>
|
||||
{timingOffsetMs !== 0 && (
|
||||
<span className="ml-1 text-xs font-bold text-purple-500">
|
||||
{timingOffsetMs > 0 ? '+' : ''}
|
||||
{timingOffsetMs}ms
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
{annotationsEnabled
|
||||
? 'Click to disable annotation prompts when editing'
|
||||
: 'Click to enable annotation prompts when editing'}
|
||||
</TooltipContent>
|
||||
<TooltipContent className="max-w-xs">Shift all word timings forward or backward. Use if lyrics appear slightly early or late in the preview.</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
</div>
|
||||
|
||||
<AudioPlayer
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useState, useEffect, useCallback, useMemo, memo } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Video, Check } from 'lucide-react'
|
||||
import { Video, Check, CheckCircle2 } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import {
|
||||
AnchorSequence,
|
||||
@@ -14,11 +14,12 @@ import {
|
||||
LyricsSegment,
|
||||
ReferenceSource,
|
||||
WordCorrection,
|
||||
CorrectionAnnotation,
|
||||
FlashType,
|
||||
Word,
|
||||
WordClickInfo,
|
||||
ModalContent,
|
||||
} from '@/lib/lyrics-review/types'
|
||||
import type { EditLog, EditLogEntry, EditFeedbackReason } from '@/lib/lyrics-review/types'
|
||||
import type { InstrumentalSelectionType } from '@/lib/api'
|
||||
import { cn } from '@/lib/utils'
|
||||
import ReferenceView from './ReferenceView'
|
||||
@@ -26,11 +27,11 @@ import TranscriptionView from './TranscriptionView'
|
||||
import { EditModal } from './modals'
|
||||
import { ReviewChangesModal } from './modals'
|
||||
import { ReplaceAllLyricsModal } from './modals'
|
||||
import { CorrectionAnnotationModal } from './modals'
|
||||
import { AddLyricsModal } from './modals'
|
||||
import { FindReplaceModal } from './modals'
|
||||
import { TimingOffsetModal } from './modals'
|
||||
import CorrectionDetailCard from './CorrectionDetailCard'
|
||||
import EditFeedbackBar from './EditFeedbackBar'
|
||||
import {
|
||||
addSegmentBefore,
|
||||
splitSegment,
|
||||
@@ -45,7 +46,9 @@ import {
|
||||
setModalHandler,
|
||||
getModalState,
|
||||
} from '@/lib/lyrics-review/utils/keyboardHandlers'
|
||||
import { createEditLog, addEditEntry, attachFeedback } from '@/lib/lyrics-review/utils/editLog'
|
||||
import Header from './Header'
|
||||
import GapNavigator from './GapNavigator'
|
||||
import { getWordsFromIds } from '@/lib/lyrics-review/utils/wordUtils'
|
||||
import { applyOffsetToCorrectionData, applyOffsetToSegment } from '@/lib/lyrics-review/utils/timingUtils'
|
||||
|
||||
@@ -61,7 +64,8 @@ declare global {
|
||||
|
||||
interface ApiClient {
|
||||
submitCorrections: (data: CorrectionData) => Promise<void>
|
||||
submitAnnotations: (annotations: Omit<CorrectionAnnotation, 'annotation_id' | 'timestamp'>[]) => Promise<void>
|
||||
submitAnnotations: (annotations: never[]) => Promise<void>
|
||||
submitEditLog: (editLog: EditLog) => Promise<void>
|
||||
updateHandlers: (handlers: string[]) => Promise<CorrectionData>
|
||||
addLyrics: (source: string, lyrics: string) => Promise<CorrectionData>
|
||||
getAudioUrl: (hash: string) => string
|
||||
@@ -135,21 +139,23 @@ export default function LyricsAnalyzer({
|
||||
const [countdown, setCountdown] = useState(2)
|
||||
const [showInstrumentalReview, setShowInstrumentalReview] = useState(false)
|
||||
|
||||
// Annotation state
|
||||
const [annotations, setAnnotations] = useState<Omit<CorrectionAnnotation, 'annotation_id' | 'timestamp'>[]>([])
|
||||
const [isAnnotationModalOpen, setIsAnnotationModalOpen] = useState(false)
|
||||
const [pendingAnnotation, setPendingAnnotation] = useState<{
|
||||
originalText: string
|
||||
correctedText: string
|
||||
wordIdsAffected: string[]
|
||||
gapId?: string
|
||||
} | null>(null)
|
||||
const [annotationsEnabled, setAnnotationsEnabled] = useState(() => {
|
||||
if (typeof window === 'undefined') return true
|
||||
const saved = localStorage.getItem('annotationsEnabled')
|
||||
return saved !== null ? saved === 'true' : true
|
||||
// Edit log state
|
||||
const [editLog] = useState<EditLog>(() => createEditLog(jobId ?? 'unknown', audioHash))
|
||||
const [lastEditEntry, setLastEditEntry] = useState<EditLogEntry | null>(null)
|
||||
const [showFeedbackBar, setShowFeedbackBar] = useState(false)
|
||||
|
||||
// Stats panel visibility
|
||||
const [statsVisible, setStatsVisible] = useState(false)
|
||||
|
||||
// Advanced mode for transcription view (Simple/Advanced toggle)
|
||||
const [advancedMode, setAdvancedMode] = useState(() => {
|
||||
if (typeof window === 'undefined') return false
|
||||
return localStorage.getItem('lyricsReviewAdvancedMode') === 'true'
|
||||
})
|
||||
|
||||
// Gap navigation state
|
||||
const [currentGapIndex, setCurrentGapIndex] = useState<number | null>(null)
|
||||
|
||||
// Correction detail card state
|
||||
const [correctionDetailOpen, setCorrectionDetailOpen] = useState(false)
|
||||
const [selectedCorrection, setSelectedCorrection] = useState<{
|
||||
@@ -204,11 +210,97 @@ export default function LyricsAnalyzer({
|
||||
}
|
||||
}, [data, isReadOnly, initialData])
|
||||
|
||||
// Flash handler (defined early so gap navigation can use it)
|
||||
const handleFlash = useCallback((type: FlashType, info?: HighlightInfo) => {
|
||||
setFlashingType(null)
|
||||
setHighlightInfo(null)
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(() => {
|
||||
setFlashingType(type)
|
||||
if (info) {
|
||||
setHighlightInfo(info)
|
||||
}
|
||||
setTimeout(() => {
|
||||
setFlashingType(null)
|
||||
setHighlightInfo(null)
|
||||
}, 1200)
|
||||
})
|
||||
})
|
||||
}, [])
|
||||
|
||||
// Compute uncorrected gaps for navigation
|
||||
const uncorrectedGaps = useMemo(() => {
|
||||
const gapCorrections = data.corrections.reduce(
|
||||
(map: Record<string, boolean>, correction) => {
|
||||
const gap = data.gap_sequences.find((g) =>
|
||||
g.transcribed_word_ids.includes(correction.word_id)
|
||||
)
|
||||
if (gap) map[gap.id] = true
|
||||
return map
|
||||
},
|
||||
{} as Record<string, boolean>
|
||||
)
|
||||
return data.gap_sequences.filter(
|
||||
(gap) => !gapCorrections[gap.id] && gap.transcribed_word_ids.length > 0
|
||||
)
|
||||
}, [data.gap_sequences, data.corrections])
|
||||
|
||||
// Navigate to a specific gap
|
||||
const navigateToGap = useCallback(
|
||||
(index: number) => {
|
||||
if (index < 0 || index >= uncorrectedGaps.length) return
|
||||
setCurrentGapIndex(index)
|
||||
const gap = uncorrectedGaps[index]
|
||||
const firstWordId = gap.transcribed_word_ids[0]
|
||||
if (firstWordId) {
|
||||
const el = document.getElementById(`word-${firstWordId}`)
|
||||
if (el) {
|
||||
el.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||||
}
|
||||
}
|
||||
// Flash only the specific gap's words (not all uncorrected gaps)
|
||||
const gapWords = gap.transcribed_word_ids
|
||||
.map((id) => {
|
||||
for (const seg of data.corrected_segments) {
|
||||
const w = seg.words.find((w) => w.id === id)
|
||||
if (w) return w
|
||||
}
|
||||
return null
|
||||
})
|
||||
.filter((w): w is Word => w !== null)
|
||||
handleFlash('uncorrected', {
|
||||
type: 'gap',
|
||||
sequence: gap,
|
||||
transcribed_words: gapWords,
|
||||
})
|
||||
},
|
||||
[uncorrectedGaps, handleFlash, data.corrected_segments]
|
||||
)
|
||||
|
||||
const handlePrevGap = useCallback(() => {
|
||||
const newIndex = currentGapIndex !== null ? currentGapIndex - 1 : 0
|
||||
navigateToGap(Math.max(0, newIndex))
|
||||
}, [currentGapIndex, navigateToGap])
|
||||
|
||||
const handleNextGap = useCallback(() => {
|
||||
const newIndex = currentGapIndex !== null ? currentGapIndex + 1 : 0
|
||||
navigateToGap(Math.min(uncorrectedGaps.length - 1, newIndex))
|
||||
}, [currentGapIndex, uncorrectedGaps.length, navigateToGap])
|
||||
|
||||
// Word IDs for the currently active gap (persistent ring indicator)
|
||||
const activeGapWordIds = useMemo(() => {
|
||||
if (currentGapIndex === null || currentGapIndex >= uncorrectedGaps.length) return undefined
|
||||
return new Set(uncorrectedGaps[currentGapIndex].transcribed_word_ids)
|
||||
}, [currentGapIndex, uncorrectedGaps])
|
||||
|
||||
// Keyboard handlers
|
||||
useEffect(() => {
|
||||
const { handleKeyDown, handleKeyUp, cleanup } = setupKeyboardHandlers({
|
||||
setIsShiftPressed,
|
||||
setIsCtrlPressed,
|
||||
onNextGap: handleNextGap,
|
||||
onPrevGap: handlePrevGap,
|
||||
})
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown)
|
||||
@@ -225,7 +317,7 @@ export default function LyricsAnalyzer({
|
||||
document.body.style.userSelect = ''
|
||||
cleanup()
|
||||
}
|
||||
}, [isAnyModalOpen])
|
||||
}, [isAnyModalOpen, handleNextGap, handlePrevGap])
|
||||
|
||||
// Update modal state tracking
|
||||
useEffect(() => {
|
||||
@@ -284,51 +376,33 @@ export default function LyricsAnalyzer({
|
||||
// Calculate effective mode based on modifier key states
|
||||
const effectiveMode = isCtrlPressed ? 'delete_word' : isShiftPressed ? 'highlight' : interactionMode
|
||||
|
||||
// Flash handler
|
||||
const handleFlash = useCallback((type: FlashType, info?: HighlightInfo) => {
|
||||
setFlashingType(null)
|
||||
setHighlightInfo(null)
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(() => {
|
||||
setFlashingType(type)
|
||||
if (info) {
|
||||
setHighlightInfo(info)
|
||||
}
|
||||
setTimeout(() => {
|
||||
setFlashingType(null)
|
||||
setHighlightInfo(null)
|
||||
}, 1200)
|
||||
})
|
||||
})
|
||||
}, [])
|
||||
|
||||
// Annotation handlers
|
||||
const handleSaveAnnotation = useCallback(
|
||||
(annotation: Omit<CorrectionAnnotation, 'annotation_id' | 'timestamp'>) => {
|
||||
setAnnotations((prev) => [...prev, annotation])
|
||||
// Edit feedback handler
|
||||
const handleEditFeedback = useCallback(
|
||||
(entryId: string, reason: EditFeedbackReason) => {
|
||||
attachFeedback(editLog, entryId, reason)
|
||||
},
|
||||
[]
|
||||
[editLog]
|
||||
)
|
||||
|
||||
const handleSkipAnnotation = useCallback(() => {
|
||||
// No-op for now
|
||||
}, [])
|
||||
|
||||
const handleAnnotationsToggle = useCallback((enabled: boolean) => {
|
||||
setAnnotationsEnabled(enabled)
|
||||
const handleAdvancedModeToggle = useCallback((enabled: boolean) => {
|
||||
setAdvancedMode(enabled)
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.setItem('annotationsEnabled', String(enabled))
|
||||
localStorage.setItem('lyricsReviewAdvancedMode', String(enabled))
|
||||
}
|
||||
}, [])
|
||||
|
||||
const triggerAnnotationModal = useCallback(
|
||||
(originalText: string, correctedText: string, wordIdsAffected: string[], gapId?: string) => {
|
||||
if (!annotationsEnabled || isReadOnly) return
|
||||
setPendingAnnotation({ originalText, correctedText, wordIdsAffected, gapId })
|
||||
setIsAnnotationModalOpen(true)
|
||||
const showFeedbackForEntry = useCallback(
|
||||
(entry: EditLogEntry) => {
|
||||
// Only show for single-word edits
|
||||
if (!['word_change', 'word_delete', 'word_add'].includes(entry.operation)) return
|
||||
// Dismiss previous entry with no_response if still showing
|
||||
if (lastEditEntry && lastEditEntry.id !== entry.id) {
|
||||
attachFeedback(editLog, lastEditEntry.id, 'no_response')
|
||||
}
|
||||
setLastEditEntry(entry)
|
||||
setShowFeedbackBar(true)
|
||||
},
|
||||
[annotationsEnabled, isReadOnly]
|
||||
[editLog, lastEditEntry]
|
||||
)
|
||||
|
||||
// Show correction detail
|
||||
@@ -364,9 +438,18 @@ export default function LyricsAnalyzer({
|
||||
const handleWordClick = useCallback(
|
||||
(info: WordClickInfo) => {
|
||||
if (effectiveMode === 'delete_word') {
|
||||
const deletedWord = data.corrected_segments.flatMap((s) => s.words).find((w) => w.id === info.word_id)
|
||||
const segment = data.corrected_segments.find((s) => s.words.some((w) => w.id === info.word_id))
|
||||
const entry = addEditEntry(editLog, 'word_delete', {
|
||||
segment_id: segment?.id,
|
||||
segment_index: segment ? data.corrected_segments.indexOf(segment) : null,
|
||||
word_ids_before: [info.word_id],
|
||||
text_before: deletedWord?.text ?? '',
|
||||
})
|
||||
const newData = deleteWord(data, info.word_id)
|
||||
updateDataWithHistory(newData, 'delete word')
|
||||
handleFlash('word')
|
||||
showFeedbackForEntry(entry)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -463,26 +546,75 @@ export default function LyricsAnalyzer({
|
||||
corrected_segments: newSegments,
|
||||
}
|
||||
|
||||
updateDataWithHistory(newData, 'update segment')
|
||||
|
||||
// Diff original vs updated words to create edit log entries
|
||||
const originalSegment = editModalSegment.originalSegment || editModalSegment.segment
|
||||
const entries: EditLogEntry[] = []
|
||||
if (originalSegment && originalSegment.text !== updatedSegment.text) {
|
||||
const wordIds = updatedSegment.words.map((w) => w.id)
|
||||
triggerAnnotationModal(originalSegment.text, updatedSegment.text, wordIds)
|
||||
const origWordMap = new Map(originalSegment.words.map((w) => [w.id, w]))
|
||||
const updatedWordMap = new Map(updatedSegment.words.map((w) => [w.id, w]))
|
||||
|
||||
// Changed or deleted words
|
||||
for (const origWord of originalSegment.words) {
|
||||
const updatedWord = updatedWordMap.get(origWord.id)
|
||||
if (!updatedWord) {
|
||||
entries.push(addEditEntry(editLog, 'word_delete', {
|
||||
segment_id: originalSegment.id,
|
||||
segment_index: editModalSegment.index,
|
||||
word_ids_before: [origWord.id],
|
||||
text_before: origWord.text,
|
||||
}))
|
||||
} else if (updatedWord.text !== origWord.text) {
|
||||
entries.push(addEditEntry(editLog, 'word_change', {
|
||||
segment_id: originalSegment.id,
|
||||
segment_index: editModalSegment.index,
|
||||
word_ids_before: [origWord.id],
|
||||
word_ids_after: [updatedWord.id],
|
||||
text_before: origWord.text,
|
||||
text_after: updatedWord.text,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
// Added words
|
||||
for (const updatedWord of updatedSegment.words) {
|
||||
if (!origWordMap.has(updatedWord.id)) {
|
||||
entries.push(addEditEntry(editLog, 'word_add', {
|
||||
segment_id: originalSegment.id,
|
||||
segment_index: editModalSegment.index,
|
||||
word_ids_after: [updatedWord.id],
|
||||
text_after: updatedWord.text,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
// Show feedback bar only for single-word edits
|
||||
if (entries.length === 1) {
|
||||
showFeedbackForEntry(entries[0])
|
||||
}
|
||||
}
|
||||
|
||||
updateDataWithHistory(newData, 'update segment')
|
||||
setEditModalSegment(null)
|
||||
},
|
||||
[history, historyIndex, editModalSegment, updateDataWithHistory, triggerAnnotationModal]
|
||||
[history, historyIndex, editModalSegment, updateDataWithHistory, editLog, showFeedbackForEntry]
|
||||
)
|
||||
|
||||
// Delete segment handler
|
||||
const handleDeleteSegment = useCallback(
|
||||
(segmentIndex: number) => {
|
||||
const segment = data.corrected_segments[segmentIndex]
|
||||
if (segment) {
|
||||
addEditEntry(editLog, 'segment_delete', {
|
||||
segment_id: segment.id,
|
||||
segment_index: segmentIndex,
|
||||
word_ids_before: segment.words.map((w) => w.id),
|
||||
text_before: segment.text,
|
||||
})
|
||||
}
|
||||
const newData = deleteSegment(data, segmentIndex)
|
||||
updateDataWithHistory(newData, 'delete segment')
|
||||
},
|
||||
[data, updateDataWithHistory]
|
||||
[data, updateDataWithHistory, editLog]
|
||||
)
|
||||
|
||||
// Correction action handlers
|
||||
@@ -525,9 +657,18 @@ export default function LyricsAnalyzer({
|
||||
corrections: newCorrections,
|
||||
}
|
||||
|
||||
addEditEntry(editLog, 'revert_correction', {
|
||||
segment_id: segment.id,
|
||||
segment_index: segmentIndex,
|
||||
word_ids_before: [wordId],
|
||||
word_ids_after: [correction.word_id],
|
||||
text_before: correction.corrected_word,
|
||||
text_after: correction.original_word,
|
||||
})
|
||||
|
||||
updateDataWithHistory(newData, 'revert correction')
|
||||
},
|
||||
[data, updateDataWithHistory]
|
||||
[data, updateDataWithHistory, editLog]
|
||||
)
|
||||
|
||||
const handleEditCorrection = useCallback(
|
||||
@@ -575,6 +716,10 @@ export default function LyricsAnalyzer({
|
||||
return
|
||||
}
|
||||
|
||||
addEditEntry(editLog, 'revert_all', {
|
||||
details: { count: data.corrections?.length ?? 0 },
|
||||
})
|
||||
|
||||
const corrections = [...(data.corrections || [])].reverse()
|
||||
let newData = data
|
||||
|
||||
@@ -610,7 +755,7 @@ export default function LyricsAnalyzer({
|
||||
}
|
||||
|
||||
updateDataWithHistory(newData, 'revert all corrections')
|
||||
}, [data, updateDataWithHistory])
|
||||
}, [data, updateDataWithHistory, editLog])
|
||||
|
||||
// Finish review - opens preview modal
|
||||
const handleFinishReview = useCallback(() => {
|
||||
@@ -633,12 +778,12 @@ export default function LyricsAnalyzer({
|
||||
// 1. Save corrections (not final submission yet)
|
||||
await apiClient.submitCorrections(dataToSubmit)
|
||||
|
||||
// 2. Save annotations
|
||||
if (annotations.length > 0) {
|
||||
// 2. Save edit log (non-blocking)
|
||||
if (editLog.entries.length > 0) {
|
||||
try {
|
||||
await apiClient.submitAnnotations(annotations)
|
||||
await apiClient.submitEditLog(editLog)
|
||||
} catch (error) {
|
||||
console.error('Failed to submit annotations:', error)
|
||||
console.error('Failed to submit edit log:', error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -666,7 +811,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, annotations, isLocalMode, jobId])
|
||||
}, [apiClient, data, timingOffsetMs, editLog, isLocalMode, jobId])
|
||||
|
||||
// Play segment handler
|
||||
const handlePlaySegment = useCallback(
|
||||
@@ -798,9 +943,23 @@ export default function LyricsAnalyzer({
|
||||
options: { caseSensitive: boolean; useRegex: boolean; fullTextMode: boolean }
|
||||
) => {
|
||||
const newData = findAndReplace(data, findText, replaceText, options)
|
||||
// Count how many segments changed
|
||||
const changedSegments = newData.corrected_segments.filter(
|
||||
(seg, i) => seg.text !== data.corrected_segments[i]?.text
|
||||
)
|
||||
addEditEntry(editLog, 'find_replace', {
|
||||
text_before: findText,
|
||||
text_after: replaceText,
|
||||
details: {
|
||||
pattern: findText,
|
||||
replacement: replaceText,
|
||||
segments_affected: changedSegments.length,
|
||||
...options,
|
||||
},
|
||||
})
|
||||
updateDataWithHistory(newData, 'find/replace')
|
||||
},
|
||||
[data, updateDataWithHistory]
|
||||
[data, updateDataWithHistory, editLog]
|
||||
)
|
||||
|
||||
// Un-correct all
|
||||
@@ -826,11 +985,17 @@ export default function LyricsAnalyzer({
|
||||
|
||||
const handleSaveReplaceAllLyrics = useCallback(
|
||||
(newSegments: LyricsSegment[]) => {
|
||||
addEditEntry(editLog, 'replace_all_lyrics', {
|
||||
details: {
|
||||
segments_before: data.corrected_segments.length,
|
||||
segments_after: newSegments.length,
|
||||
},
|
||||
})
|
||||
const newData = { ...data, corrected_segments: newSegments }
|
||||
updateDataWithHistory(newData, 'replace all lyrics')
|
||||
setIsReplaceAllLyricsModalOpen(false)
|
||||
},
|
||||
[data, updateDataWithHistory]
|
||||
[data, updateDataWithHistory, editLog]
|
||||
)
|
||||
|
||||
// Undo/Redo
|
||||
@@ -925,10 +1090,9 @@ export default function LyricsAnalyzer({
|
||||
onRedo={handleRedo}
|
||||
canUndo={canUndo}
|
||||
canRedo={canRedo}
|
||||
onUnCorrectAll={handleUnCorrectAll}
|
||||
onResetCorrections={handleResetCorrections}
|
||||
annotationsEnabled={annotationsEnabled}
|
||||
onAnnotationsToggle={handleAnnotationsToggle}
|
||||
statsVisible={statsVisible}
|
||||
onStatsToggle={() => setStatsVisible((v) => !v)}
|
||||
reviewMode={reviewMode}
|
||||
onReviewModeToggle={setReviewMode}
|
||||
onAcceptAllCorrections={handleAcceptAllCorrections}
|
||||
@@ -956,6 +1120,9 @@ export default function LyricsAnalyzer({
|
||||
onEditCorrection={handleEditCorrection}
|
||||
onAcceptCorrection={handleAcceptCorrection}
|
||||
onShowCorrectionDetail={handleShowCorrectionDetail}
|
||||
activeGapWordIds={activeGapWordIds}
|
||||
advancedMode={advancedMode}
|
||||
onAdvancedModeToggle={handleAdvancedModeToggle}
|
||||
/>
|
||||
<ReferenceView
|
||||
referenceSources={data.reference_lyrics}
|
||||
@@ -979,7 +1146,35 @@ export default function LyricsAnalyzer({
|
||||
|
||||
{/* Sticky footer bar */}
|
||||
{!isReadOnly && apiClient && (
|
||||
<div className="fixed bottom-0 left-0 right-0 bg-background border-t shadow-lg py-3 px-4 z-50 flex justify-center items-center gap-4">
|
||||
<div className="fixed bottom-0 left-0 right-0 bg-background border-t shadow-lg py-3 px-4 z-50 flex justify-center items-center gap-4 flex-wrap">
|
||||
<GapNavigator
|
||||
currentGapIndex={currentGapIndex}
|
||||
totalGaps={uncorrectedGaps.length}
|
||||
onPrevGap={handlePrevGap}
|
||||
onNextGap={handleNextGap}
|
||||
/>
|
||||
{data.gap_sequences.length > 0 && (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<div className="w-16 h-1.5 bg-muted rounded-full overflow-hidden">
|
||||
<div
|
||||
className="h-full bg-green-500 rounded-full transition-all"
|
||||
style={{
|
||||
width: `${data.gap_sequences.length > 0 ? ((data.gap_sequences.length - uncorrectedGaps.length) / data.gap_sequences.length) * 100 : 0}%`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{uncorrectedGaps.length === 0 ? (
|
||||
<span className="text-xs text-green-500 flex items-center gap-0.5">
|
||||
<CheckCircle2 className="h-3.5 w-3.5" />
|
||||
All gaps reviewed
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap">
|
||||
{data.gap_sequences.length - uncorrectedGaps.length}/{data.gap_sequences.length} gaps reviewed
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<span className="text-sm text-muted-foreground">Lyrics look good?</span>
|
||||
<Button onClick={handleFinishReview} disabled={isReviewComplete}>
|
||||
{isReviewComplete ? 'Review Complete' : 'Preview Video'}
|
||||
@@ -1074,26 +1269,12 @@ export default function LyricsAnalyzer({
|
||||
existingSegments={data.corrected_segments}
|
||||
/>
|
||||
|
||||
{pendingAnnotation && (
|
||||
<CorrectionAnnotationModal
|
||||
open={isAnnotationModalOpen}
|
||||
onClose={() => {
|
||||
setIsAnnotationModalOpen(false)
|
||||
setPendingAnnotation(null)
|
||||
}}
|
||||
onSave={handleSaveAnnotation}
|
||||
onSkip={handleSkipAnnotation}
|
||||
originalText={pendingAnnotation.originalText}
|
||||
correctedText={pendingAnnotation.correctedText}
|
||||
wordIdsAffected={pendingAnnotation.wordIdsAffected}
|
||||
referenceSources={Object.keys(data.reference_lyrics || {})}
|
||||
audioHash={audioHash}
|
||||
artist={data.metadata?.audio_filepath?.split('/').pop()?.split('.')[0] || 'Unknown'}
|
||||
title={data.metadata?.audio_filepath?.split('/').pop()?.split('.')[0] || 'Unknown'}
|
||||
sessionId={audioHash}
|
||||
gapId={pendingAnnotation.gapId}
|
||||
/>
|
||||
)}
|
||||
<EditFeedbackBar
|
||||
entry={lastEditEntry}
|
||||
visible={showFeedbackBar}
|
||||
onFeedback={handleEditFeedback}
|
||||
onDismiss={() => setShowFeedbackBar(false)}
|
||||
/>
|
||||
|
||||
{selectedCorrection && (
|
||||
<CorrectionDetailCard
|
||||
|
||||
@@ -36,8 +36,8 @@ export default function ModeSelector({ effectiveMode, onChange }: ModeSelectorPr
|
||||
Edit
|
||||
</ToggleGroupItem>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>Default mode; click words to edit that lyrics segment</p>
|
||||
<TooltipContent className="max-w-xs">
|
||||
<p>Click any word to edit that lyrics line. Default mode for correcting misheard words.</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
@@ -51,8 +51,8 @@ export default function ModeSelector({ effectiveMode, onChange }: ModeSelectorPr
|
||||
Highlight
|
||||
</ToggleGroupItem>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>Hold SHIFT and click words to highlight the matching anchor sequence</p>
|
||||
<TooltipContent className="max-w-xs">
|
||||
<p>Click any word to see where it matches in the reference lyrics. Shortcut: hold SHIFT.</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
@@ -66,8 +66,8 @@ export default function ModeSelector({ effectiveMode, onChange }: ModeSelectorPr
|
||||
Delete
|
||||
</ToggleGroupItem>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>Hold CTRL and click words to delete them</p>
|
||||
<TooltipContent className="max-w-xs">
|
||||
<p>Click any word to instantly delete it. Great for removing phantom words like "And" during instrumental sections. Shortcut: hold CTRL.</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</ToggleGroup>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useState } from 'react'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Play, Trash2, Type, Clock } from 'lucide-react'
|
||||
import { HighlightedText } from './shared/HighlightedText'
|
||||
import { TranscriptionViewProps, TranscriptionWordPosition } from '@/lib/lyrics-review/types'
|
||||
@@ -28,6 +29,9 @@ export default function TranscriptionView({
|
||||
onEditCorrection,
|
||||
onAcceptCorrection,
|
||||
onShowCorrectionDetail,
|
||||
activeGapWordIds,
|
||||
advancedMode = false,
|
||||
onAdvancedModeToggle,
|
||||
}: TranscriptionViewProps) {
|
||||
const [selectedSegmentIndex, setSelectedSegmentIndex] = useState<number | null>(null)
|
||||
const [viewMode, setViewMode] = useState<'text' | 'duration'>('text')
|
||||
@@ -43,7 +47,16 @@ export default function TranscriptionView({
|
||||
<Card className="p-2">
|
||||
<CardContent className="p-0">
|
||||
<div className="flex justify-between items-center mb-1">
|
||||
<h3 className="text-sm font-semibold">Corrected Transcription</h3>
|
||||
<div className="flex items-center gap-2">
|
||||
<h3 className="text-sm font-semibold">Synced Lyrics</h3>
|
||||
<Badge
|
||||
variant={advancedMode ? 'default' : 'outline'}
|
||||
className="cursor-pointer hover:opacity-80 transition-opacity text-[0.65rem] h-5 px-1.5"
|
||||
onClick={() => onAdvancedModeToggle?.(!advancedMode)}
|
||||
>
|
||||
{advancedMode ? 'Advanced' : 'Simple'}
|
||||
</Badge>
|
||||
</div>
|
||||
<ToggleGroup
|
||||
type="single"
|
||||
value={viewMode}
|
||||
@@ -132,22 +145,26 @@ export default function TranscriptionView({
|
||||
className="flex items-start w-full hover:bg-muted/50 transition-colors"
|
||||
>
|
||||
{/* Segment controls */}
|
||||
<div className="flex items-center gap-0.5 min-w-[2.5em] pr-1">
|
||||
<span
|
||||
className="text-muted-foreground w-[1.8em] text-right mr-1 select-none font-mono text-[0.8rem] leading-tight cursor-pointer hover:underline"
|
||||
onClick={() => setSelectedSegmentIndex(segmentIndex)}
|
||||
>
|
||||
{segmentIndex}
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-[18px] w-[18px] min-h-0 min-w-0 p-[1px] text-destructive hover:text-destructive"
|
||||
onClick={() => handleDeleteSegment(segmentIndex)}
|
||||
title="Delete segment"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<div className="flex items-center gap-0.5 pr-1" style={{ minWidth: advancedMode ? '2.5em' : undefined }}>
|
||||
{advancedMode && (
|
||||
<span
|
||||
className="text-muted-foreground w-[1.8em] text-right mr-1 select-none font-mono text-[0.8rem] leading-tight cursor-pointer hover:underline"
|
||||
onClick={() => setSelectedSegmentIndex(segmentIndex)}
|
||||
>
|
||||
{segmentIndex}
|
||||
</span>
|
||||
)}
|
||||
{advancedMode && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-[18px] w-[18px] min-h-0 min-w-0 p-[1px] text-destructive hover:text-destructive"
|
||||
onClick={() => handleDeleteSegment(segmentIndex)}
|
||||
title="Delete segment"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
)}
|
||||
{segment.start_time !== null && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
@@ -176,6 +193,7 @@ export default function TranscriptionView({
|
||||
currentTime={currentTime}
|
||||
gaps={data.gap_sequences}
|
||||
corrections={data.corrections}
|
||||
activeGapWordIds={activeGapWordIds}
|
||||
reviewMode={reviewMode}
|
||||
onRevertCorrection={onRevertCorrection}
|
||||
onEditCorrection={onEditCorrection}
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
import { render, screen, act } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import EditFeedbackBar from '../EditFeedbackBar'
|
||||
import type { EditLogEntry } from '@/lib/lyrics-review/types'
|
||||
|
||||
function makeEntry(overrides: Partial<EditLogEntry> = {}): EditLogEntry {
|
||||
return {
|
||||
id: 'entry-1',
|
||||
timestamp: new Date().toISOString(),
|
||||
operation: 'word_change',
|
||||
segment_id: 's1',
|
||||
segment_index: 0,
|
||||
word_ids_before: ['w1'],
|
||||
word_ids_after: ['w1'],
|
||||
text_before: 'helo',
|
||||
text_after: 'hello',
|
||||
feedback: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('EditFeedbackBar', () => {
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
it('renders nothing when not visible', () => {
|
||||
const { container } = render(
|
||||
<EditFeedbackBar entry={makeEntry()} visible={false} onFeedback={jest.fn()} onDismiss={jest.fn()} />
|
||||
)
|
||||
expect(container.firstChild).toBeNull()
|
||||
})
|
||||
|
||||
it('renders nothing when entry is null', () => {
|
||||
const { container } = render(
|
||||
<EditFeedbackBar entry={null} visible={true} onFeedback={jest.fn()} onDismiss={jest.fn()} />
|
||||
)
|
||||
expect(container.firstChild).toBeNull()
|
||||
})
|
||||
|
||||
it('shows question text for word_change', () => {
|
||||
render(
|
||||
<EditFeedbackBar entry={makeEntry()} visible={true} onFeedback={jest.fn()} onDismiss={jest.fn()} />
|
||||
)
|
||||
expect(screen.getByText(/Changed "helo" → "hello", why\?/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows question text for word_delete', () => {
|
||||
render(
|
||||
<EditFeedbackBar
|
||||
entry={makeEntry({ operation: 'word_delete', text_before: 'ghost', text_after: '' })}
|
||||
visible={true}
|
||||
onFeedback={jest.fn()}
|
||||
onDismiss={jest.fn()}
|
||||
/>
|
||||
)
|
||||
expect(screen.getByText(/Removed "ghost", why\?/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows question text for word_add', () => {
|
||||
render(
|
||||
<EditFeedbackBar
|
||||
entry={makeEntry({ operation: 'word_add', text_before: '', text_after: 'world' })}
|
||||
visible={true}
|
||||
onFeedback={jest.fn()}
|
||||
onDismiss={jest.fn()}
|
||||
/>
|
||||
)
|
||||
expect(screen.getByText(/Added "world", why\?/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows correct reason buttons for word_change', () => {
|
||||
render(
|
||||
<EditFeedbackBar entry={makeEntry()} visible={true} onFeedback={jest.fn()} onDismiss={jest.fn()} />
|
||||
)
|
||||
expect(screen.getByText('Mis-heard word')).toBeInTheDocument()
|
||||
expect(screen.getByText('Wrong lyrics')).toBeInTheDocument()
|
||||
expect(screen.getByText('Spelling/punctuation')).toBeInTheDocument()
|
||||
expect(screen.getByText('Other')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows correct reason buttons for word_delete', () => {
|
||||
render(
|
||||
<EditFeedbackBar
|
||||
entry={makeEntry({ operation: 'word_delete' })}
|
||||
visible={true}
|
||||
onFeedback={jest.fn()}
|
||||
onDismiss={jest.fn()}
|
||||
/>
|
||||
)
|
||||
expect(screen.getByText('Phantom word')).toBeInTheDocument()
|
||||
expect(screen.getByText('Duplicate')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows correct reason buttons for word_add', () => {
|
||||
render(
|
||||
<EditFeedbackBar
|
||||
entry={makeEntry({ operation: 'word_add' })}
|
||||
visible={true}
|
||||
onFeedback={jest.fn()}
|
||||
onDismiss={jest.fn()}
|
||||
/>
|
||||
)
|
||||
expect(screen.getByText('Missing word')).toBeInTheDocument()
|
||||
expect(screen.getByText('Split word')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('calls onFeedback with correct reason when button clicked', async () => {
|
||||
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime })
|
||||
const onFeedback = jest.fn()
|
||||
const onDismiss = jest.fn()
|
||||
|
||||
render(
|
||||
<EditFeedbackBar entry={makeEntry()} visible={true} onFeedback={onFeedback} onDismiss={onDismiss} />
|
||||
)
|
||||
|
||||
await user.click(screen.getByText('Mis-heard word'))
|
||||
expect(onFeedback).toHaveBeenCalledWith('entry-1', 'misheard_word')
|
||||
expect(onDismiss).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('calls onFeedback with no_response and onDismiss when X clicked', async () => {
|
||||
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime })
|
||||
const onFeedback = jest.fn()
|
||||
const onDismiss = jest.fn()
|
||||
|
||||
render(
|
||||
<EditFeedbackBar entry={makeEntry()} visible={true} onFeedback={onFeedback} onDismiss={onDismiss} />
|
||||
)
|
||||
|
||||
// Click the X button (last button)
|
||||
const buttons = screen.getAllByRole('button')
|
||||
const closeButton = buttons[buttons.length - 1]
|
||||
await user.click(closeButton)
|
||||
|
||||
expect(onFeedback).toHaveBeenCalledWith('entry-1', 'no_response')
|
||||
expect(onDismiss).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('auto-dismisses after 10 seconds with no_response', () => {
|
||||
const onFeedback = jest.fn()
|
||||
const onDismiss = jest.fn()
|
||||
|
||||
render(
|
||||
<EditFeedbackBar entry={makeEntry()} visible={true} onFeedback={onFeedback} onDismiss={onDismiss} />
|
||||
)
|
||||
|
||||
expect(onFeedback).not.toHaveBeenCalled()
|
||||
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(10_000)
|
||||
})
|
||||
|
||||
expect(onFeedback).toHaveBeenCalledWith('entry-1', 'no_response')
|
||||
expect(onDismiss).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('pauses auto-dismiss while hovered', async () => {
|
||||
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime })
|
||||
const onFeedback = jest.fn()
|
||||
const onDismiss = jest.fn()
|
||||
|
||||
const { container } = render(
|
||||
<EditFeedbackBar entry={makeEntry()} visible={true} onFeedback={onFeedback} onDismiss={onDismiss} />
|
||||
)
|
||||
|
||||
const bar = container.firstChild as HTMLElement
|
||||
|
||||
// Advance 6 seconds, then hover
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(6_000)
|
||||
})
|
||||
expect(onFeedback).not.toHaveBeenCalled()
|
||||
|
||||
await user.hover(bar)
|
||||
|
||||
// Advance well past 10s total — should NOT dismiss while hovered
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(10_000)
|
||||
})
|
||||
expect(onFeedback).not.toHaveBeenCalled()
|
||||
|
||||
// Unhover — timer resumes with remaining ~4s
|
||||
await user.unhover(bar)
|
||||
|
||||
// 3s after unhover — still not dismissed
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(3_000)
|
||||
})
|
||||
expect(onFeedback).not.toHaveBeenCalled()
|
||||
|
||||
// 2 more seconds (past the remaining ~4s) — should dismiss
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(2_000)
|
||||
})
|
||||
expect(onFeedback).toHaveBeenCalledWith('entry-1', 'no_response')
|
||||
expect(onDismiss).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not auto-dismiss if user clicks a reason while hovered', async () => {
|
||||
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime })
|
||||
const onFeedback = jest.fn()
|
||||
const onDismiss = jest.fn()
|
||||
|
||||
const { container } = render(
|
||||
<EditFeedbackBar entry={makeEntry()} visible={true} onFeedback={onFeedback} onDismiss={onDismiss} />
|
||||
)
|
||||
|
||||
const bar = container.firstChild as HTMLElement
|
||||
|
||||
await user.hover(bar)
|
||||
await user.click(screen.getByText('Mis-heard word'))
|
||||
|
||||
expect(onFeedback).toHaveBeenCalledWith('entry-1', 'misheard_word')
|
||||
expect(onDismiss).toHaveBeenCalled()
|
||||
|
||||
// Advancing time should not trigger a second no_response call
|
||||
onFeedback.mockClear()
|
||||
onDismiss.mockClear()
|
||||
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(15_000)
|
||||
})
|
||||
expect(onFeedback).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,79 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import GapNavigator from '../GapNavigator'
|
||||
|
||||
describe('GapNavigator', () => {
|
||||
const defaultProps = {
|
||||
currentGapIndex: null as number | null,
|
||||
totalGaps: 5,
|
||||
onPrevGap: jest.fn(),
|
||||
onNextGap: jest.fn(),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
it('renders gap counter', () => {
|
||||
render(<GapNavigator {...defaultProps} currentGapIndex={2} />)
|
||||
|
||||
expect(screen.getByText('Gap 3 of 5')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows "Gap 0 of N" when no gap selected', () => {
|
||||
render(<GapNavigator {...defaultProps} currentGapIndex={null} />)
|
||||
|
||||
expect(screen.getByText('Gap 0 of 5')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders nothing when totalGaps is 0', () => {
|
||||
const { container } = render(<GapNavigator {...defaultProps} totalGaps={0} />)
|
||||
|
||||
expect(container.firstChild).toBeNull()
|
||||
})
|
||||
|
||||
it('disables prev button at first gap', () => {
|
||||
render(<GapNavigator {...defaultProps} currentGapIndex={0} />)
|
||||
|
||||
expect(screen.getByLabelText('Previous gap')).toBeDisabled()
|
||||
expect(screen.getByLabelText('Next gap')).not.toBeDisabled()
|
||||
})
|
||||
|
||||
it('disables next button at last gap', () => {
|
||||
render(<GapNavigator {...defaultProps} currentGapIndex={4} />)
|
||||
|
||||
expect(screen.getByLabelText('Previous gap')).not.toBeDisabled()
|
||||
expect(screen.getByLabelText('Next gap')).toBeDisabled()
|
||||
})
|
||||
|
||||
it('disables prev button when no gap selected', () => {
|
||||
render(<GapNavigator {...defaultProps} currentGapIndex={null} />)
|
||||
|
||||
expect(screen.getByLabelText('Previous gap')).toBeDisabled()
|
||||
})
|
||||
|
||||
it('calls onNextGap when next button clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<GapNavigator {...defaultProps} currentGapIndex={1} />)
|
||||
|
||||
await user.click(screen.getByLabelText('Next gap'))
|
||||
|
||||
expect(defaultProps.onNextGap).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('calls onPrevGap when prev button clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<GapNavigator {...defaultProps} currentGapIndex={2} />)
|
||||
|
||||
await user.click(screen.getByLabelText('Previous gap'))
|
||||
|
||||
expect(defaultProps.onPrevGap).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows keyboard shortcut hints in tooltips', () => {
|
||||
render(<GapNavigator {...defaultProps} currentGapIndex={0} />)
|
||||
|
||||
expect(screen.getByLabelText('Previous gap')).toBeInTheDocument()
|
||||
expect(screen.getByLabelText('Next gap')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,176 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import GuidancePanel from '../GuidancePanel'
|
||||
import { CorrectionData } from '@/lib/lyrics-review/types'
|
||||
|
||||
// Mock localStorage
|
||||
const localStorageMock = (() => {
|
||||
let store: Record<string, string> = {}
|
||||
return {
|
||||
getItem: jest.fn((key: string) => store[key] || null),
|
||||
setItem: jest.fn((key: string, value: string) => { store[key] = value }),
|
||||
removeItem: jest.fn((key: string) => { delete store[key] }),
|
||||
clear: jest.fn(() => { store = {} }),
|
||||
}
|
||||
})()
|
||||
Object.defineProperty(window, 'localStorage', { value: localStorageMock })
|
||||
|
||||
const makeMockData = (overrides: Partial<CorrectionData> = {}): CorrectionData => ({
|
||||
corrected_segments: [],
|
||||
original_segments: [],
|
||||
anchor_sequences: [
|
||||
{
|
||||
id: 'a1',
|
||||
transcribed_word_ids: ['w1', 'w2'],
|
||||
reference_word_ids: { source1: ['r1', 'r2'] },
|
||||
confidence: 0.9,
|
||||
},
|
||||
],
|
||||
gap_sequences: [
|
||||
{
|
||||
id: 'g1',
|
||||
transcribed_word_ids: ['w3'],
|
||||
reference_word_ids: { source1: ['r3'] },
|
||||
},
|
||||
{
|
||||
id: 'g2',
|
||||
transcribed_word_ids: ['w4', 'w5'],
|
||||
reference_word_ids: { source1: ['r4'] },
|
||||
},
|
||||
],
|
||||
corrections: [
|
||||
{
|
||||
word_id: 'w3',
|
||||
corrected_word_id: 'w3c',
|
||||
original_word: 'orig',
|
||||
corrected_word: 'fixed',
|
||||
handler: 'TestHandler',
|
||||
confidence: 0.8,
|
||||
source: 'source1',
|
||||
reason: 'test',
|
||||
is_deletion: false,
|
||||
},
|
||||
],
|
||||
reference_lyrics: {},
|
||||
metadata: {
|
||||
total_words: 10,
|
||||
anchor_sequences_count: 1,
|
||||
available_handlers: [],
|
||||
enabled_handlers: [],
|
||||
},
|
||||
...overrides,
|
||||
} as unknown as CorrectionData)
|
||||
|
||||
describe('GuidancePanel', () => {
|
||||
const defaultProps = {
|
||||
isReadOnly: false,
|
||||
onMetricClick: { anchor: jest.fn(), corrected: jest.fn(), uncorrected: jest.fn() },
|
||||
onHandlerToggle: jest.fn(),
|
||||
isUpdatingHandlers: false,
|
||||
onHandlerClick: jest.fn(),
|
||||
statsVisible: false,
|
||||
onStatsToggle: jest.fn(),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
localStorageMock.clear()
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
it('renders color legend with all three dot labels', () => {
|
||||
render(<GuidancePanel data={makeMockData()} {...defaultProps} />)
|
||||
|
||||
expect(screen.getByText('Matched')).toBeInTheDocument()
|
||||
expect(screen.getByText('Gaps (needs review)')).toBeInTheDocument()
|
||||
expect(screen.getByText('Corrected')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders workflow tip by default', () => {
|
||||
render(<GuidancePanel data={makeMockData()} {...defaultProps} />)
|
||||
|
||||
expect(screen.getByText(/Synced Lyrics/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows zero-gap message when no gaps exist', () => {
|
||||
const data = makeMockData({ gap_sequences: [], corrections: [] })
|
||||
render(<GuidancePanel data={data} {...defaultProps} />)
|
||||
|
||||
expect(screen.getByText(/All lyrics matched the reference/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('dismisses tip and stores in localStorage', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<GuidancePanel data={makeMockData()} {...defaultProps} />)
|
||||
|
||||
const dismissButton = screen.getByLabelText('Dismiss tip')
|
||||
await user.click(dismissButton)
|
||||
|
||||
expect(localStorageMock.setItem).toHaveBeenCalledWith('lyricsReviewGuidanceDismissed', 'true')
|
||||
expect(screen.queryByText(/Synced Lyrics/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows "Show tips" link after dismissal', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<GuidancePanel data={makeMockData()} {...defaultProps} />)
|
||||
|
||||
await user.click(screen.getByLabelText('Dismiss tip'))
|
||||
|
||||
expect(screen.getByText('Show tips')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('restores tip when "Show tips" is clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<GuidancePanel data={makeMockData()} {...defaultProps} />)
|
||||
|
||||
await user.click(screen.getByLabelText('Dismiss tip'))
|
||||
await user.click(screen.getByText('Show tips'))
|
||||
|
||||
expect(screen.getByText(/Synced Lyrics/)).toBeInTheDocument()
|
||||
expect(localStorageMock.removeItem).toHaveBeenCalledWith('lyricsReviewGuidanceDismissed')
|
||||
})
|
||||
|
||||
it('hides workflow tip in read-only mode', () => {
|
||||
render(<GuidancePanel data={makeMockData()} {...defaultProps} isReadOnly={true} />)
|
||||
|
||||
expect(screen.queryByText(/Synced Lyrics/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('stats are collapsed by default', () => {
|
||||
render(<GuidancePanel data={makeMockData()} {...defaultProps} />)
|
||||
|
||||
expect(screen.getByText('Stats')).toBeInTheDocument()
|
||||
// Stats content should not be visible
|
||||
expect(screen.queryByText('Anchor Sequences')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('calls onStatsToggle when Stats button clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<GuidancePanel data={makeMockData()} {...defaultProps} />)
|
||||
|
||||
await user.click(screen.getByText('Stats'))
|
||||
|
||||
expect(defaultProps.onStatsToggle).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows stats content when statsVisible is true', () => {
|
||||
render(<GuidancePanel data={makeMockData()} {...defaultProps} statsVisible={true} />)
|
||||
|
||||
expect(screen.getByText('Anchor Sequences')).toBeInTheDocument()
|
||||
expect(screen.getByText('Corrected Gaps')).toBeInTheDocument()
|
||||
expect(screen.getByText('Uncorrected Gaps')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('calls metric click handler when color legend dot clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<GuidancePanel data={makeMockData()} {...defaultProps} />)
|
||||
|
||||
await user.click(screen.getByText('Matched'))
|
||||
expect(defaultProps.onMetricClick.anchor).toHaveBeenCalled()
|
||||
|
||||
await user.click(screen.getByText('Gaps (needs review)'))
|
||||
expect(defaultProps.onMetricClick.uncorrected).toHaveBeenCalled()
|
||||
|
||||
await user.click(screen.getByText('Corrected'))
|
||||
expect(defaultProps.onMetricClick.corrected).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -41,6 +41,8 @@ export interface HighlightedTextProps {
|
||||
gaps?: GapSequence[]
|
||||
flashingHandler?: string | null
|
||||
corrections?: WordCorrection[]
|
||||
// Gap navigation
|
||||
activeGapWordIds?: Set<string>
|
||||
// Review mode props for agentic corrections
|
||||
reviewMode?: boolean
|
||||
onRevertCorrection?: (wordId: string) => void
|
||||
@@ -68,6 +70,7 @@ export function HighlightedText({
|
||||
gaps = [],
|
||||
flashingHandler,
|
||||
corrections = [],
|
||||
activeGapWordIds,
|
||||
reviewMode = false,
|
||||
onRevertCorrection,
|
||||
onEditCorrection,
|
||||
@@ -116,7 +119,14 @@ export function HighlightedText({
|
||||
return Boolean(
|
||||
(flashingType === 'anchor' && wordPos.type === 'anchor') ||
|
||||
(flashingType === 'corrected' && isCorrected) ||
|
||||
(flashingType === 'uncorrected' && wordPos.type === 'gap' && !isCorrected) ||
|
||||
(flashingType === 'uncorrected' &&
|
||||
wordPos.type === 'gap' &&
|
||||
!isCorrected &&
|
||||
// If highlightInfo specifies a gap, only flash that gap's words
|
||||
(!highlightInfo?.sequence ||
|
||||
(highlightInfo.sequence as GapSequence).transcribed_word_ids?.includes(
|
||||
wordPos.word.id
|
||||
))) ||
|
||||
(flashingType === 'word' &&
|
||||
((highlightInfo?.type === 'anchor' &&
|
||||
wordPos.type === 'anchor' &&
|
||||
@@ -202,6 +212,7 @@ export function HighlightedText({
|
||||
onRevert={() => onRevertCorrection?.(wordPos.word.id)}
|
||||
onEdit={() => onEditCorrection?.(wordPos.word.id)}
|
||||
onAccept={() => onAcceptCorrection?.(wordPos.word.id)}
|
||||
id={`word-${wordPos.word.id}`}
|
||||
onClick={() => {
|
||||
if (isMobile) {
|
||||
onShowCorrectionDetail?.(wordPos.word.id)
|
||||
@@ -230,6 +241,8 @@ export function HighlightedText({
|
||||
isCorrectedGap={wordPos.isCorrected}
|
||||
isUncorrectedGap={wordPos.type === 'gap' && !wordPos.isCorrected}
|
||||
isCurrentlyPlaying={shouldHighlightWord(wordPos)}
|
||||
isActiveGap={activeGapWordIds?.has(wordPos.word.id)}
|
||||
id={`word-${wordPos.word.id}`}
|
||||
onClick={() =>
|
||||
handleWordClick(
|
||||
wordPos.word.text,
|
||||
@@ -299,6 +312,7 @@ export function HighlightedText({
|
||||
onRevert={() => onRevertCorrection?.(word.id)}
|
||||
onEdit={() => onEditCorrection?.(word.id)}
|
||||
onAccept={() => onAcceptCorrection?.(word.id)}
|
||||
id={`word-${word.id}`}
|
||||
onClick={() => {
|
||||
if (isMobile) {
|
||||
onShowCorrectionDetail?.(word.id)
|
||||
@@ -333,6 +347,8 @@ export function HighlightedText({
|
||||
isCurrentlyPlaying={shouldHighlightWord(
|
||||
wordPos || { word: word.text, id: word.id }
|
||||
)}
|
||||
isActiveGap={activeGapWordIds?.has(word.id)}
|
||||
id={`word-${word.id}`}
|
||||
onClick={() => handleWordClick(word.text, word.id, anchor, sequence)}
|
||||
correction={correctionInfo}
|
||||
/>
|
||||
|
||||
@@ -13,8 +13,10 @@ export const WordComponent = React.memo(function Word({
|
||||
isCorrectedGap,
|
||||
isUncorrectedGap,
|
||||
isCurrentlyPlaying,
|
||||
isActiveGap,
|
||||
padding = 'px-[3px] py-[1px]',
|
||||
onClick,
|
||||
id,
|
||||
correction,
|
||||
}: WordProps) {
|
||||
if (/^\s+$/.test(word)) {
|
||||
@@ -34,11 +36,13 @@ export const WordComponent = React.memo(function Word({
|
||||
|
||||
const wordElement = (
|
||||
<span
|
||||
id={id}
|
||||
className={cn(
|
||||
'inline-block mr-[0.25em] transition-colors duration-200 cursor-pointer rounded-sm text-[0.85rem] leading-[1.2]',
|
||||
padding,
|
||||
bgColorClass,
|
||||
shouldFlash && 'animate-lyrics-flash',
|
||||
isActiveGap && 'ring-1 ring-yellow-400 dark:ring-yellow-300',
|
||||
correction && 'underline decoration-dotted underline-offset-2 decoration-muted-foreground',
|
||||
'hover:bg-foreground/[0.08]'
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
[
|
||||
{
|
||||
"slug": "maximo-park-by-the-monument",
|
||||
"artist": "Maximo Park",
|
||||
"title": "By the Monument",
|
||||
"resultCount": 19,
|
||||
"status": "awaiting_selection",
|
||||
"file": "maximo-park-by-the-monument.json"
|
||||
},
|
||||
{
|
||||
"slug": "hot-mulligan-pop-shuvit-hall-of-meat-duh-acoustic",
|
||||
"artist": "Hot Mulligan",
|
||||
"title": "Pop Shuvit (Hall of Meat, Duh) (Acoustic)",
|
||||
"resultCount": 9,
|
||||
"status": "awaiting_selection",
|
||||
"file": "hot-mulligan-pop-shuvit-hall-of-meat-duh-acoustic.json"
|
||||
},
|
||||
{
|
||||
"slug": "bon-jovi-it-s-my-life",
|
||||
"artist": "Bon Jovi",
|
||||
"title": "It's My Life",
|
||||
"resultCount": 47,
|
||||
"status": "awaiting_selection",
|
||||
"file": "bon-jovi-it-s-my-life.json"
|
||||
},
|
||||
{
|
||||
"slug": "pony-bradshaw-10x10",
|
||||
"artist": "Pony Bradshaw",
|
||||
"title": "10x10",
|
||||
"resultCount": 8,
|
||||
"status": "awaiting_selection",
|
||||
"file": "pony-bradshaw-10x10.json"
|
||||
},
|
||||
{
|
||||
"slug": "sawyer-hill-masochistic-lover",
|
||||
"artist": "Sawyer Hill",
|
||||
"title": "Masochistic Lover",
|
||||
"resultCount": 9,
|
||||
"status": "awaiting_selection",
|
||||
"file": "sawyer-hill-masochistic-lover.json"
|
||||
},
|
||||
{
|
||||
"slug": "astn-happier-than-ever",
|
||||
"artist": "ASTN",
|
||||
"title": "Happier Than Ever",
|
||||
"resultCount": 5,
|
||||
"status": "awaiting_selection",
|
||||
"file": "astn-happier-than-ever.json"
|
||||
},
|
||||
{
|
||||
"slug": "quail-what-you-got",
|
||||
"artist": "Quail",
|
||||
"title": "What You Got",
|
||||
"resultCount": 5,
|
||||
"status": "awaiting_selection",
|
||||
"file": "quail-what-you-got.json"
|
||||
},
|
||||
{
|
||||
"slug": "hot-mulligan-pop-shuvit-hall-of-meat-duh",
|
||||
"artist": "Hot Mulligan",
|
||||
"title": "Pop Shuvit (Hall of Meat, Duh)",
|
||||
"resultCount": 7,
|
||||
"status": "awaiting_selection",
|
||||
"file": "hot-mulligan-pop-shuvit-hall-of-meat-duh.json"
|
||||
},
|
||||
{
|
||||
"slug": "the-mountain-goats-source-decay",
|
||||
"artist": "The Mountain Goats",
|
||||
"title": "Source Decay",
|
||||
"resultCount": 14,
|
||||
"status": "awaiting_selection",
|
||||
"file": "the-mountain-goats-source-decay.json"
|
||||
},
|
||||
{
|
||||
"slug": "linkin-park-final-masquerade",
|
||||
"artist": "Linkin Park",
|
||||
"title": "Final Masquerade",
|
||||
"resultCount": 32,
|
||||
"status": "awaiting_selection",
|
||||
"file": "linkin-park-final-masquerade.json"
|
||||
},
|
||||
{
|
||||
"slug": "purim-shpiel-i-love-you-koreh",
|
||||
"artist": "Purim Shpiel",
|
||||
"title": "I Love You, KoREH",
|
||||
"resultCount": 10,
|
||||
"status": "awaiting_selection",
|
||||
"file": "purim-shpiel-i-love-you-koreh.json"
|
||||
},
|
||||
{
|
||||
"slug": "purim-shpiel-keep-on-achieving",
|
||||
"artist": "Purim Shpiel",
|
||||
"title": "Keep On Achieving",
|
||||
"resultCount": 15,
|
||||
"status": "awaiting_selection",
|
||||
"file": "purim-shpiel-keep-on-achieving.json"
|
||||
},
|
||||
{
|
||||
"slug": "purim-shpiel-525-060-b-nai-mitzvah",
|
||||
"artist": "Purim Shpiel",
|
||||
"title": "525,060 B'nai Mitzvah",
|
||||
"resultCount": 10,
|
||||
"status": "awaiting_selection",
|
||||
"file": "purim-shpiel-525-060-b-nai-mitzvah.json"
|
||||
},
|
||||
{
|
||||
"slug": "purim-shpiel-i-ve-been-changed-at-koreh",
|
||||
"artist": "Purim Shpiel",
|
||||
"title": "I've Been Changed at KoREH",
|
||||
"resultCount": 10,
|
||||
"status": "awaiting_selection",
|
||||
"file": "purim-shpiel-i-ve-been-changed-at-koreh.json"
|
||||
},
|
||||
{
|
||||
"slug": "hollow-coves-blessings",
|
||||
"artist": "Hollow Coves",
|
||||
"title": "Blessings",
|
||||
"resultCount": 17,
|
||||
"status": "awaiting_selection",
|
||||
"file": "hollow-coves-blessings.json"
|
||||
},
|
||||
{
|
||||
"slug": "eyehategod-jack-ass-in-the-will-of-god",
|
||||
"artist": "Eyehategod",
|
||||
"title": "Jack ass in the will of god",
|
||||
"resultCount": 22,
|
||||
"status": "awaiting_selection",
|
||||
"file": "eyehategod-jack-ass-in-the-will-of-god.json"
|
||||
},
|
||||
{
|
||||
"slug": "jack-kays-the-rug",
|
||||
"artist": "Jack Kays",
|
||||
"title": "The Rug",
|
||||
"resultCount": 9,
|
||||
"status": "awaiting_selection",
|
||||
"file": "jack-kays-the-rug.json"
|
||||
},
|
||||
{
|
||||
"slug": "pitchshifter-genius",
|
||||
"artist": "Pitchshifter",
|
||||
"title": "Genius",
|
||||
"resultCount": 29,
|
||||
"status": "awaiting_selection",
|
||||
"file": "pitchshifter-genius.json"
|
||||
},
|
||||
{
|
||||
"slug": "japanese-breakfast-till-death",
|
||||
"artist": "Japanese Breakfast",
|
||||
"title": "Till Death",
|
||||
"resultCount": 21,
|
||||
"status": "awaiting_selection",
|
||||
"file": "japanese-breakfast-till-death.json"
|
||||
},
|
||||
{
|
||||
"slug": "pierce-the-veil-she-makes-dirty-words-sound-pretty",
|
||||
"artist": "Pierce The Veil",
|
||||
"title": "She Makes Dirty Words Sound Pretty",
|
||||
"resultCount": 17,
|
||||
"status": "awaiting_selection",
|
||||
"file": "pierce-the-veil-she-makes-dirty-words-sound-pretty.json"
|
||||
},
|
||||
{
|
||||
"slug": "cage-the-elephant-ain-t-no-rest-for-the-wicked",
|
||||
"artist": "Cage The elephant",
|
||||
"title": "Ain't no rest for the wicked",
|
||||
"resultCount": 37,
|
||||
"status": "awaiting_selection",
|
||||
"file": "cage-the-elephant-ain-t-no-rest-for-the-wicked.json"
|
||||
},
|
||||
{
|
||||
"slug": "steve-taylor-jim-morrison-s-grave",
|
||||
"artist": "Steve Taylor",
|
||||
"title": "Jim Morrison's Grave",
|
||||
"resultCount": 11,
|
||||
"status": "awaiting_selection",
|
||||
"file": "steve-taylor-jim-morrison-s-grave.json"
|
||||
},
|
||||
{
|
||||
"slug": "eyehategod-shoplift",
|
||||
"artist": "Eyehategod",
|
||||
"title": "Shoplift",
|
||||
"resultCount": 21,
|
||||
"status": "awaiting_selection",
|
||||
"file": "eyehategod-shoplift.json"
|
||||
},
|
||||
{
|
||||
"slug": "eyehategod-blank",
|
||||
"artist": "Eyehategod",
|
||||
"title": "Blank",
|
||||
"resultCount": 21,
|
||||
"status": "awaiting_selection",
|
||||
"file": "eyehategod-blank.json"
|
||||
},
|
||||
{
|
||||
"slug": "eyehategod-agitation-propaganda",
|
||||
"artist": "Eyehategod",
|
||||
"title": "Agitation! Propaganda!",
|
||||
"resultCount": 18,
|
||||
"status": "awaiting_selection",
|
||||
"file": "eyehategod-agitation-propaganda.json"
|
||||
},
|
||||
{
|
||||
"slug": "eyehategod-medicine-noose",
|
||||
"artist": "Eyehategod",
|
||||
"title": "Medicine noose",
|
||||
"resultCount": 9,
|
||||
"status": "awaiting_selection",
|
||||
"file": "eyehategod-medicine-noose.json"
|
||||
},
|
||||
{
|
||||
"slug": "the-swirling-eddies-pyro-sets-a-wildfire",
|
||||
"artist": "The Swirling Eddies",
|
||||
"title": "Pyro Sets a Wildfire",
|
||||
"resultCount": 17,
|
||||
"status": "awaiting_selection",
|
||||
"file": "the-swirling-eddies-pyro-sets-a-wildfire.json"
|
||||
},
|
||||
{
|
||||
"slug": "novo-amor-vantablack",
|
||||
"artist": "novo amor",
|
||||
"title": "Vantablack",
|
||||
"resultCount": 21,
|
||||
"status": "awaiting_selection",
|
||||
"file": "novo-amor-vantablack.json"
|
||||
},
|
||||
{
|
||||
"slug": "super-cassette-invincibility-star",
|
||||
"artist": "Super Cassette",
|
||||
"title": "Invincibility Star",
|
||||
"resultCount": 6,
|
||||
"status": "awaiting_selection",
|
||||
"file": "super-cassette-invincibility-star.json"
|
||||
},
|
||||
{
|
||||
"slug": "pigeon-pit-josephine-county-blues",
|
||||
"artist": "Pigeon Pit",
|
||||
"title": "Josephine County Blues",
|
||||
"resultCount": 3,
|
||||
"status": "awaiting_selection",
|
||||
"file": "pigeon-pit-josephine-county-blues.json"
|
||||
},
|
||||
{
|
||||
"slug": "set-it-off-wolf-in-sheep-s-clothing",
|
||||
"artist": "Set it off",
|
||||
"title": "Wolf in sheep's clothing",
|
||||
"resultCount": 27,
|
||||
"status": "awaiting_selection",
|
||||
"file": "set-it-off-wolf-in-sheep-s-clothing.json"
|
||||
},
|
||||
{
|
||||
"slug": "joe-nichols-sunny-and-75",
|
||||
"artist": "Joe Nichols",
|
||||
"title": "Sunny and 75",
|
||||
"resultCount": 17,
|
||||
"status": "awaiting_selection",
|
||||
"file": "joe-nichols-sunny-and-75.json"
|
||||
},
|
||||
{
|
||||
"slug": "the-something-specials-aces",
|
||||
"artist": "The Something Specials",
|
||||
"title": "Aces",
|
||||
"resultCount": 15,
|
||||
"status": "awaiting_selection",
|
||||
"file": "the-something-specials-aces.json"
|
||||
},
|
||||
{
|
||||
"slug": "over-the-garden-wall-the-blasting-company-patient-is-the-night",
|
||||
"artist": "Over The Garden Wall (The Blasting Company)",
|
||||
"title": "Patient Is The Night",
|
||||
"resultCount": 15,
|
||||
"status": "awaiting_selection",
|
||||
"file": "over-the-garden-wall-the-blasting-company-patient-is-the-night.json"
|
||||
},
|
||||
{
|
||||
"slug": "dawid-podsiad-o-p-t-adamczyk-phantom-liberty",
|
||||
"artist": "Dawid Podsiadło, P.T. Adamczyk",
|
||||
"title": "Phantom Liberty",
|
||||
"resultCount": 15,
|
||||
"status": "awaiting_selection",
|
||||
"file": "dawid-podsiad-o-p-t-adamczyk-phantom-liberty.json"
|
||||
},
|
||||
{
|
||||
"slug": "social-distortion-1945-13th-floor-version",
|
||||
"artist": "Social Distortion",
|
||||
"title": "1945 (13th Floor Version)",
|
||||
"resultCount": 17,
|
||||
"status": "awaiting_selection",
|
||||
"file": "social-distortion-1945-13th-floor-version.json"
|
||||
},
|
||||
{
|
||||
"slug": "yarbrough-and-peoples-guilty",
|
||||
"artist": "Yarbrough And Peoples",
|
||||
"title": "Guilty",
|
||||
"resultCount": 17,
|
||||
"status": "awaiting_selection",
|
||||
"file": "yarbrough-and-peoples-guilty.json"
|
||||
},
|
||||
{
|
||||
"slug": "phil-collins-amy-keys-separate-lives-live-in-paris-2004",
|
||||
"artist": "Phil Collins & Amy Keys",
|
||||
"title": "Separate Lives (Live In Paris 2004)",
|
||||
"resultCount": 15,
|
||||
"status": "awaiting_selection",
|
||||
"file": "phil-collins-amy-keys-separate-lives-live-in-paris-2004.json"
|
||||
},
|
||||
{
|
||||
"slug": "kenny-wayne-shepherd-everything-is-broken",
|
||||
"artist": "Kenny Wayne Shepherd",
|
||||
"title": "Everything Is Broken",
|
||||
"resultCount": 18,
|
||||
"status": "awaiting_selection",
|
||||
"file": "kenny-wayne-shepherd-everything-is-broken.json"
|
||||
},
|
||||
{
|
||||
"slug": "nick-lowe-true-love-travels-on-a-gravel-road",
|
||||
"artist": "Nick Lowe",
|
||||
"title": "True Love Travels on a Gravel Road",
|
||||
"resultCount": 15,
|
||||
"status": "awaiting_selection",
|
||||
"file": "nick-lowe-true-love-travels-on-a-gravel-road.json"
|
||||
},
|
||||
{
|
||||
"slug": "jasmine-thompson-you-are-my-sunshine",
|
||||
"artist": "Jasmine Thompson",
|
||||
"title": "You Are My Sunshine",
|
||||
"resultCount": 15,
|
||||
"status": "awaiting_selection",
|
||||
"file": "jasmine-thompson-you-are-my-sunshine.json"
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,300 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Fetch Audio Search Fixtures from Production
|
||||
*
|
||||
* Queries the production API for the most recently completed karaoke jobs,
|
||||
* then re-runs the audio search for each (artist, title) pair and stores
|
||||
* the raw search results as JSON fixtures.
|
||||
*
|
||||
* These fixtures let us iterate on confidence tier logic and UI without
|
||||
* needing to hit the backend again after the initial fetch.
|
||||
*
|
||||
* Usage:
|
||||
* cd frontend
|
||||
*
|
||||
* # Fetch 50 fixtures (default)
|
||||
* node e2e/fixtures/fetch-search-fixtures.mjs
|
||||
*
|
||||
* # Fetch a specific number
|
||||
* node e2e/fixtures/fetch-search-fixtures.mjs --count 20
|
||||
*
|
||||
* # Skip jobs already fetched (resume mode)
|
||||
* node e2e/fixtures/fetch-search-fixtures.mjs --resume
|
||||
*
|
||||
* Prerequisites:
|
||||
* - Admin token via: gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke
|
||||
* - Or set KARAOKE_ADMIN_TOKEN env var
|
||||
*
|
||||
* Output: e2e/fixtures/data/search-results/
|
||||
* - index.json (manifest of all fixtures with metadata)
|
||||
* - {artist}--{title}.json (individual search result files)
|
||||
*/
|
||||
|
||||
import { execSync } from 'child_process';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const OUTPUT_DIR = path.join(__dirname, 'data', 'search-results');
|
||||
const INDEX_PATH = path.join(OUTPUT_DIR, 'index.json');
|
||||
const API_URL = 'https://api.nomadkaraoke.com';
|
||||
|
||||
// Parse CLI args
|
||||
const args = process.argv.slice(2);
|
||||
const countIdx = args.indexOf('--count');
|
||||
const FETCH_COUNT = countIdx !== -1 ? parseInt(args[countIdx + 1]) : 50;
|
||||
const RESUME = args.includes('--resume');
|
||||
|
||||
function getAdminToken() {
|
||||
if (process.env.KARAOKE_ADMIN_TOKEN) {
|
||||
return process.env.KARAOKE_ADMIN_TOKEN;
|
||||
}
|
||||
try {
|
||||
const token = execSync(
|
||||
'gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke',
|
||||
{ encoding: 'utf-8' }
|
||||
).trim().split(',')[0];
|
||||
return token;
|
||||
} catch {
|
||||
console.error('Could not get admin token. Set KARAOKE_ADMIN_TOKEN or configure gcloud.');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function slugify(artist, title) {
|
||||
const slug = `${artist}--${title}`
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-|-$/g, '')
|
||||
.slice(0, 100);
|
||||
return slug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch recently completed jobs from the admin API.
|
||||
* Uses the /api/admin/jobs endpoint with status filter.
|
||||
*/
|
||||
async function fetchRecentJobs(token, count) {
|
||||
console.log(`Fetching ${count} most recently completed jobs from API...`);
|
||||
|
||||
const res = await fetch(
|
||||
`${API_URL}/api/admin/jobs?status=complete&limit=${count + 20}&sort=created_at:desc`,
|
||||
{
|
||||
headers: { 'X-Admin-Token': token },
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
// Fallback: try the regular jobs list endpoint
|
||||
console.log(`Admin jobs endpoint returned ${res.status}, trying regular endpoint...`);
|
||||
const fallbackRes = await fetch(`${API_URL}/api/jobs?limit=${count + 20}`, {
|
||||
headers: { 'X-Admin-Token': token },
|
||||
});
|
||||
|
||||
if (!fallbackRes.ok) {
|
||||
throw new Error(`Failed to fetch jobs: ${fallbackRes.status} ${await fallbackRes.text()}`);
|
||||
}
|
||||
|
||||
const jobs = await fallbackRes.json();
|
||||
return processJobs(Array.isArray(jobs) ? jobs : jobs.jobs || [], count);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
const jobs = Array.isArray(data) ? data : data.jobs || [];
|
||||
return processJobs(jobs, count);
|
||||
}
|
||||
|
||||
function processJobs(jobs, count) {
|
||||
const seen = new Set();
|
||||
const results = [];
|
||||
|
||||
// Filter to completed jobs and deduplicate by artist+title
|
||||
for (const job of jobs) {
|
||||
if (job.status && job.status !== 'complete') continue;
|
||||
|
||||
const artist = job.artist?.trim();
|
||||
const title = job.title?.trim();
|
||||
if (!artist || !title) continue;
|
||||
|
||||
const key = `${artist.toLowerCase()}|${title.toLowerCase()}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
|
||||
results.push({
|
||||
jobId: job.job_id,
|
||||
artist,
|
||||
title,
|
||||
createdAt: job.created_at,
|
||||
});
|
||||
|
||||
if (results.length >= count) break;
|
||||
}
|
||||
|
||||
console.log(`Found ${results.length} unique (artist, title) pairs`);
|
||||
return results;
|
||||
}
|
||||
|
||||
async function searchAudio(token, artist, title) {
|
||||
// Step 1: Initiate search
|
||||
const searchRes = await fetch(`${API_URL}/api/audio-search/search`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Admin-Token': token,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
artist,
|
||||
title,
|
||||
auto_download: false,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!searchRes.ok) {
|
||||
const text = await searchRes.text();
|
||||
throw new Error(`Search failed (${searchRes.status}): ${text}`);
|
||||
}
|
||||
|
||||
const searchData = await searchRes.json();
|
||||
const jobId = searchData.job_id;
|
||||
|
||||
// If results are already in the response
|
||||
if (searchData.results && searchData.results.length > 0) {
|
||||
return { jobId, results: searchData.results, status: searchData.status };
|
||||
}
|
||||
|
||||
// Step 2: Poll for results
|
||||
const maxAttempts = 30;
|
||||
const interval = 2000;
|
||||
|
||||
for (let i = 0; i < maxAttempts; i++) {
|
||||
await new Promise(resolve => setTimeout(resolve, interval));
|
||||
|
||||
const resultsRes = await fetch(`${API_URL}/api/audio-search/${jobId}/results`, {
|
||||
headers: { 'X-Admin-Token': token },
|
||||
});
|
||||
|
||||
if (!resultsRes.ok) continue;
|
||||
|
||||
const resultsData = await resultsRes.json();
|
||||
if (resultsData.results && resultsData.results.length > 0) {
|
||||
return { jobId, results: resultsData.results, status: resultsData.status };
|
||||
}
|
||||
|
||||
if (resultsData.status === 'search_complete' || resultsData.status === 'audio_search_complete') {
|
||||
return { jobId, results: [], status: resultsData.status };
|
||||
}
|
||||
}
|
||||
|
||||
return { jobId, results: [], status: 'timeout' };
|
||||
}
|
||||
|
||||
async function cleanupJob(token, jobId) {
|
||||
try {
|
||||
await fetch(`${API_URL}/api/jobs/${jobId}`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'X-Admin-Token': token },
|
||||
});
|
||||
} catch {
|
||||
// Best-effort cleanup
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const token = getAdminToken();
|
||||
console.log(`Token: ${token.substring(0, 8)}...`);
|
||||
|
||||
// Ensure output directory exists
|
||||
fs.mkdirSync(OUTPUT_DIR, { recursive: true });
|
||||
|
||||
// Load existing index if resuming
|
||||
let existingIndex = [];
|
||||
if (RESUME && fs.existsSync(INDEX_PATH)) {
|
||||
existingIndex = JSON.parse(fs.readFileSync(INDEX_PATH, 'utf-8'));
|
||||
console.log(`Resume mode: ${existingIndex.length} fixtures already exist`);
|
||||
}
|
||||
const existingSlugs = new Set(existingIndex.map(f => f.slug));
|
||||
|
||||
// Fetch recent completed jobs
|
||||
const jobs = await fetchRecentJobs(token, FETCH_COUNT + existingSlugs.size);
|
||||
const toFetch = jobs.filter(j => !existingSlugs.has(slugify(j.artist, j.title)));
|
||||
|
||||
if (toFetch.length === 0) {
|
||||
console.log('All fixtures already exist. Nothing to fetch.');
|
||||
return;
|
||||
}
|
||||
|
||||
const limit = Math.min(toFetch.length, FETCH_COUNT - existingIndex.length);
|
||||
console.log(`\nWill fetch search results for ${limit} jobs...\n`);
|
||||
console.log(`Estimated time: ~${Math.ceil(limit * 0.7)} minutes (10s between each + search time)\n`);
|
||||
|
||||
const results = [...existingIndex];
|
||||
let successCount = 0;
|
||||
let failCount = 0;
|
||||
|
||||
for (let i = 0; i < limit; i++) {
|
||||
const job = toFetch[i];
|
||||
const slug = slugify(job.artist, job.title);
|
||||
const outPath = path.join(OUTPUT_DIR, `${slug}.json`);
|
||||
|
||||
process.stdout.write(`[${i + 1}/${limit}] ${job.artist} - ${job.title}... `);
|
||||
|
||||
try {
|
||||
const searchResult = await searchAudio(token, job.artist, job.title);
|
||||
|
||||
const fixture = {
|
||||
artist: job.artist,
|
||||
title: job.title,
|
||||
originalJobId: job.jobId,
|
||||
createdAt: job.createdAt,
|
||||
fetchedAt: new Date().toISOString(),
|
||||
searchJobId: searchResult.jobId,
|
||||
status: searchResult.status,
|
||||
resultCount: searchResult.results.length,
|
||||
results: searchResult.results,
|
||||
};
|
||||
|
||||
fs.writeFileSync(outPath, JSON.stringify(fixture, null, 2));
|
||||
|
||||
results.push({
|
||||
slug,
|
||||
artist: job.artist,
|
||||
title: job.title,
|
||||
resultCount: searchResult.results.length,
|
||||
status: searchResult.status,
|
||||
file: `${slug}.json`,
|
||||
});
|
||||
|
||||
console.log(`${searchResult.results.length} results`);
|
||||
successCount++;
|
||||
|
||||
// Clean up the search job (don't leave stale jobs)
|
||||
await cleanupJob(token, searchResult.jobId);
|
||||
} catch (err) {
|
||||
console.log(`FAILED: ${err.message}`);
|
||||
failCount++;
|
||||
}
|
||||
|
||||
// Write index after each successful fetch (so --resume works if interrupted)
|
||||
fs.writeFileSync(INDEX_PATH, JSON.stringify(results, null, 2));
|
||||
|
||||
// 10s delay between searches to avoid rate limits
|
||||
if (i < limit - 1) {
|
||||
process.stdout.write(' Waiting 10s before next search...');
|
||||
await new Promise(resolve => setTimeout(resolve, 10000));
|
||||
console.log(' done');
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\n=== Done ===`);
|
||||
console.log(`Success: ${successCount}`);
|
||||
console.log(`Failed: ${failCount}`);
|
||||
console.log(`Total fixtures: ${results.length}`);
|
||||
console.log(`Output: ${OUTPUT_DIR}`);
|
||||
console.log(`Index: ${INDEX_PATH}`);
|
||||
}
|
||||
|
||||
main().catch(err => {
|
||||
console.error('Fatal error:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Fixture Review Driver
|
||||
*
|
||||
* Loads one fixture at a time into the guided flow, takes a screenshot,
|
||||
* and writes it to a predictable path for review.
|
||||
*
|
||||
* Usage:
|
||||
* node e2e/fixtures/review-driver.mjs <fixture-index> [screenshot-path]
|
||||
*
|
||||
* fixture-index: 0-based index into the fixture index.json
|
||||
* screenshot-path: optional, defaults to /tmp/fixture-review.png
|
||||
*/
|
||||
|
||||
import { chromium } from '@playwright/test';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const FIXTURES_DIR = path.join(__dirname, 'data', 'search-results');
|
||||
const INDEX_PATH = path.join(FIXTURES_DIR, 'index.json');
|
||||
|
||||
const fixtureIdx = parseInt(process.argv[2] || '0', 10);
|
||||
const screenshotPath = process.argv[3] || '/tmp/fixture-review.png';
|
||||
|
||||
// Load fixture
|
||||
const index = JSON.parse(fs.readFileSync(INDEX_PATH, 'utf-8'));
|
||||
if (fixtureIdx < 0 || fixtureIdx >= index.length) {
|
||||
console.error(`Invalid fixture index ${fixtureIdx}. Range: 0-${index.length - 1}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const entry = index[fixtureIdx];
|
||||
const fixture = JSON.parse(fs.readFileSync(path.join(FIXTURES_DIR, entry.file), 'utf-8'));
|
||||
|
||||
console.log(`Loading fixture ${fixtureIdx + 1}/${index.length}: ${entry.artist} - ${entry.title} (${entry.resultCount} results)`);
|
||||
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
|
||||
// Set up API mocks
|
||||
await page.route('**/api/**', async (route) => {
|
||||
const req = route.request();
|
||||
const method = req.method();
|
||||
const url = new URL(req.url());
|
||||
const apiPath = url.pathname;
|
||||
|
||||
if (method === 'POST' && apiPath === '/api/audio-search/search') {
|
||||
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ job_id: 'fixture-review', status: 'audio_search' }) });
|
||||
}
|
||||
if (method === 'GET' && apiPath.includes('/api/audio-search/') && apiPath.includes('/results')) {
|
||||
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ results: fixture.results, status: 'search_complete' }) });
|
||||
}
|
||||
if (method === 'POST' && apiPath.includes('/api/audio-search/') && apiPath.includes('/select')) {
|
||||
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ job_id: 'fixture-review', status: 'downloading' }) });
|
||||
}
|
||||
if (method === 'GET' && apiPath === '/api/jobs') {
|
||||
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify([]) });
|
||||
}
|
||||
if (method === 'GET' && apiPath === '/api/users/me') {
|
||||
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ user: { email: 'reviewer@test.com', credits: 99, role: 'admin' }, has_session: true }) });
|
||||
}
|
||||
if (method === 'GET' && apiPath === '/api/themes') {
|
||||
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ themes: [] }) });
|
||||
}
|
||||
if (method === 'GET' && apiPath === '/api/users/credits/packages') {
|
||||
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ packages: [] }) });
|
||||
}
|
||||
return route.continue();
|
||||
});
|
||||
|
||||
// Set auth token
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem('karaoke_access_token', 'fixture-review-token');
|
||||
});
|
||||
|
||||
// Navigate to app
|
||||
await page.goto('http://127.0.0.1:3000/app');
|
||||
await page.getByLabel(/artist/i).waitFor({ timeout: 15000 });
|
||||
|
||||
// Fill in artist and title
|
||||
await page.getByLabel(/artist/i).fill(entry.artist);
|
||||
await page.getByLabel(/title/i).fill(entry.title);
|
||||
|
||||
// Click Choose Audio
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
// Wait for results
|
||||
try {
|
||||
await page.getByText('Perfect match found')
|
||||
.or(page.getByText('Recommended'))
|
||||
.or(page.getByText('Limited sources found'))
|
||||
.or(page.getByText(/no audio sources/i))
|
||||
.waitFor({ timeout: 15000 });
|
||||
} catch {
|
||||
console.log('Warning: tier text not found within timeout, taking screenshot anyway');
|
||||
}
|
||||
|
||||
// Small delay for any animations
|
||||
await page.waitForTimeout(500);
|
||||
|
||||
// Take full-page screenshot
|
||||
await page.screenshot({ path: screenshotPath, fullPage: true });
|
||||
console.log(`Screenshot saved: ${screenshotPath}`);
|
||||
|
||||
await browser.close();
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Fixture Review Tool — Quick Reference
|
||||
*
|
||||
* Opens each search result fixture in the guided flow UI so you can
|
||||
* manually verify how each tier looks and behaves.
|
||||
*
|
||||
* Usage:
|
||||
* cd frontend
|
||||
* npm run fixtures:review-ui
|
||||
*
|
||||
* Filters (env vars):
|
||||
* FIXTURE_START=10 Start from fixture 10
|
||||
* FIXTURE_SLUG=bon-jovi-it-s-my-life Review only this fixture
|
||||
* FIXTURE_TIER=3 Only review tier 3 fixtures
|
||||
*
|
||||
* Example:
|
||||
* FIXTURE_TIER=1 npm run fixtures:review-ui # Review only Tier 1
|
||||
* FIXTURE_START=20 npm run fixtures:review-ui # Start from fixture 20
|
||||
*
|
||||
* In the Playwright Inspector, click ▶ Resume to advance to the next fixture.
|
||||
*/
|
||||
|
||||
console.log('Fixture Review — Interactive Tier Verification');
|
||||
console.log('');
|
||||
console.log('Usage:');
|
||||
console.log(' cd frontend');
|
||||
console.log(' npm run fixtures:review-ui');
|
||||
console.log('');
|
||||
console.log('Filters (pass as env vars):');
|
||||
console.log(' FIXTURE_START=N Start from fixture N (1-indexed)');
|
||||
console.log(' FIXTURE_SLUG=x Review only the fixture with this slug');
|
||||
console.log(' FIXTURE_TIER=N Only review fixtures classified as tier N (1, 2, or 3)');
|
||||
console.log('');
|
||||
console.log('Examples:');
|
||||
console.log(' FIXTURE_TIER=1 npm run fixtures:review-ui');
|
||||
console.log(' FIXTURE_SLUG=bon-jovi-it-s-my-life npm run fixtures:review-ui');
|
||||
@@ -0,0 +1,294 @@
|
||||
/**
|
||||
* Fixture Review — Interactive Tier Verification
|
||||
*
|
||||
* Steps through each search result fixture in the guided flow UI,
|
||||
* mocking the API to return that fixture's data. Pauses after each
|
||||
* fixture so you can visually verify the tier rendering.
|
||||
*
|
||||
* Usage:
|
||||
* cd frontend
|
||||
* npm run fixtures:review-ui
|
||||
*
|
||||
* How to advance:
|
||||
* Open the browser's DevTools console (Cmd+Option+J) and type: next()
|
||||
* This advances to the next fixture.
|
||||
*
|
||||
* Environment variables:
|
||||
* FIXTURE_START=N Start from fixture N (1-indexed, default: 1)
|
||||
* FIXTURE_SLUG=slug Review only the fixture matching this slug
|
||||
* FIXTURE_TIER=1|2|3 Only review fixtures classified as that tier
|
||||
*/
|
||||
|
||||
import { test as base, expect, chromium, type Page, type BrowserContext } from '@playwright/test';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
|
||||
// --- Persistent Chrome profile (bookmarks bar enabled) ---
|
||||
|
||||
const REVIEW_PROFILE = path.resolve(__dirname, '../../.review-profile');
|
||||
const PREFS_DIR = path.join(REVIEW_PROFILE, 'Default');
|
||||
const PREFS_FILE = path.join(PREFS_DIR, 'Preferences');
|
||||
if (!fs.existsSync(PREFS_FILE)) {
|
||||
fs.mkdirSync(PREFS_DIR, { recursive: true });
|
||||
fs.writeFileSync(PREFS_FILE, JSON.stringify({
|
||||
bookmark_bar: { show_on_all_tabs: true },
|
||||
}, null, 2));
|
||||
}
|
||||
|
||||
const PORT = process.env.E2E_PORT || '3000';
|
||||
|
||||
const test = base.extend<object, { reviewContext: BrowserContext }>({
|
||||
reviewContext: [async ({}, use) => {
|
||||
const context = await chromium.launchPersistentContext(REVIEW_PROFILE, {
|
||||
headless: false,
|
||||
baseURL: `http://127.0.0.1:${PORT}`,
|
||||
viewport: { width: 1280, height: 720 },
|
||||
});
|
||||
await use(context);
|
||||
await context.close();
|
||||
}, { scope: 'worker' }],
|
||||
/* eslint-disable react-hooks/rules-of-hooks */
|
||||
page: async ({ reviewContext }, use) => {
|
||||
const page = await reviewContext.newPage();
|
||||
await use(page);
|
||||
await page.close();
|
||||
},
|
||||
/* eslint-enable react-hooks/rules-of-hooks */
|
||||
});
|
||||
|
||||
// --- Load fixtures ---
|
||||
|
||||
const FIXTURES_DIR = path.resolve(__dirname, 'data', 'search-results');
|
||||
const INDEX_PATH = path.join(FIXTURES_DIR, 'index.json');
|
||||
|
||||
interface FixtureEntry {
|
||||
slug: string;
|
||||
artist: string;
|
||||
title: string;
|
||||
resultCount: number;
|
||||
status: string;
|
||||
file: string;
|
||||
}
|
||||
|
||||
interface Fixture {
|
||||
artist: string;
|
||||
title: string;
|
||||
resultCount: number;
|
||||
results: any[];
|
||||
}
|
||||
|
||||
function loadIndex(): FixtureEntry[] {
|
||||
if (!fs.existsSync(INDEX_PATH)) {
|
||||
throw new Error(`No fixture index found at ${INDEX_PATH}. Run: node e2e/fixtures/fetch-search-fixtures.mjs`);
|
||||
}
|
||||
return JSON.parse(fs.readFileSync(INDEX_PATH, 'utf-8'));
|
||||
}
|
||||
|
||||
function loadFixture(entry: FixtureEntry): Fixture {
|
||||
const filePath = path.join(FIXTURES_DIR, entry.file);
|
||||
if (!fs.existsSync(filePath)) {
|
||||
throw new Error(`Fixture file not found: ${filePath}`);
|
||||
}
|
||||
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
||||
}
|
||||
|
||||
// Compute tier for filtering (same logic as audio-search-utils.ts but simplified)
|
||||
function computeTier(fixture: Fixture): 1 | 2 | 3 {
|
||||
if (fixture.results.length === 0) return 3;
|
||||
|
||||
let best: any = null;
|
||||
for (const r of fixture.results) {
|
||||
if (r.is_lossless && r.quality_data?.media?.toLowerCase() === 'vinyl') continue;
|
||||
if (!best) { best = r; continue; }
|
||||
const isBestChoice = r.is_lossless && (r.seeders ?? 0) >= 50 && r.quality_data?.media?.toLowerCase() !== 'vinyl';
|
||||
const currentIsBest = best.is_lossless && (best.seeders ?? 0) >= 50 && best.quality_data?.media?.toLowerCase() !== 'vinyl';
|
||||
if (isBestChoice && !currentIsBest) best = r;
|
||||
else if (isBestChoice && currentIsBest && (r.seeders ?? 0) > (best.seeders ?? 0)) best = r;
|
||||
}
|
||||
if (!best) best = fixture.results[0];
|
||||
|
||||
const isBestChoice = best.is_lossless && (best.seeders ?? 0) >= 50 && best.quality_data?.media?.toLowerCase() !== 'vinyl';
|
||||
const hasLossless = fixture.results.some(
|
||||
(r: any) => r.is_lossless && r.provider?.toLowerCase() !== 'youtube' && r.quality_data?.media?.toLowerCase() !== 'vinyl'
|
||||
);
|
||||
|
||||
if (isBestChoice) return 1;
|
||||
if (!hasLossless) return 3;
|
||||
return 2;
|
||||
}
|
||||
|
||||
// --- Mocking helpers ---
|
||||
|
||||
const APP_PAGE_MOCKS = [
|
||||
{ method: 'GET', path: '/api/jobs', body: [] },
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/api/users/me',
|
||||
body: { user: { email: 'reviewer@test.com', credits: 99, role: 'admin' }, has_session: true },
|
||||
},
|
||||
{ method: 'GET', path: '/api/themes', body: { themes: [] } },
|
||||
{ method: 'GET', path: '/api/users/credits/packages', body: { packages: [] } },
|
||||
];
|
||||
|
||||
async function setupMocks(page: Page, fixture: Fixture) {
|
||||
const fixtureJobId = `fixture-review-${Date.now()}`;
|
||||
|
||||
await page.route('**/api/**', async (route) => {
|
||||
const request = route.request();
|
||||
const method = request.method();
|
||||
const url = new URL(request.url());
|
||||
const apiPath = url.pathname;
|
||||
|
||||
if (method === 'POST' && apiPath === '/api/audio-search/search') {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ job_id: fixtureJobId, status: 'audio_search' }),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === 'GET' && apiPath.includes('/api/audio-search/') && apiPath.includes('/results')) {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ results: fixture.results, status: 'search_complete' }),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === 'POST' && apiPath.includes('/api/audio-search/') && apiPath.includes('/select')) {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ job_id: fixtureJobId, status: 'downloading' }),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
for (const mock of APP_PAGE_MOCKS) {
|
||||
if (method === mock.method && apiPath === mock.path) {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mock.body),
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await route.continue();
|
||||
});
|
||||
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem('karaoke_access_token', 'fixture-review-token');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for the reviewer to type next() in the browser console.
|
||||
* Injects a global next() function that resolves a promise,
|
||||
* then waits for the 'NEXT' console message.
|
||||
*/
|
||||
async function waitForNext(page: Page, info: string) {
|
||||
// Inject the next() helper and display info
|
||||
await page.evaluate((msg) => {
|
||||
// Show banner in the page
|
||||
const banner = document.createElement('div');
|
||||
banner.id = 'fixture-review-banner';
|
||||
banner.style.cssText = 'position:fixed;bottom:0;left:0;right:0;background:#1a1a2e;color:#e0e0e0;padding:8px 16px;font-family:monospace;font-size:13px;z-index:99999;border-top:2px solid #7c3aed;display:flex;justify-content:space-between;align-items:center;';
|
||||
banner.innerHTML = `<span>${msg}</span><span style="color:#a78bfa;">Type <b>next()</b> in DevTools console to continue</span>`;
|
||||
document.body.appendChild(banner);
|
||||
|
||||
// Expose next() function
|
||||
(window as any).__nextResolve = null;
|
||||
(window as any).next = () => {
|
||||
console.log('NEXT');
|
||||
banner.remove();
|
||||
};
|
||||
}, info);
|
||||
|
||||
// Wait for the 'NEXT' console message
|
||||
await page.waitForEvent('console', {
|
||||
predicate: (msg) => msg.text() === 'NEXT',
|
||||
timeout: 600_000, // 10 minutes
|
||||
});
|
||||
}
|
||||
|
||||
// --- Build fixture list ---
|
||||
|
||||
const allEntries = loadIndex();
|
||||
const startIdx = parseInt(process.env.FIXTURE_START || '1', 10) - 1;
|
||||
const slugFilter = process.env.FIXTURE_SLUG || '';
|
||||
const tierFilter = process.env.FIXTURE_TIER ? parseInt(process.env.FIXTURE_TIER, 10) : 0;
|
||||
|
||||
let entriesToReview = allEntries;
|
||||
|
||||
if (slugFilter) {
|
||||
entriesToReview = allEntries.filter((e) => e.slug === slugFilter);
|
||||
if (entriesToReview.length === 0) {
|
||||
console.error(`No fixture found with slug: ${slugFilter}`);
|
||||
console.error('Available slugs:', allEntries.map((e) => e.slug).join(', '));
|
||||
}
|
||||
}
|
||||
|
||||
if (tierFilter) {
|
||||
entriesToReview = entriesToReview.filter((e) => {
|
||||
const fixture = loadFixture(e);
|
||||
return computeTier(fixture) === tierFilter;
|
||||
});
|
||||
}
|
||||
|
||||
if (startIdx > 0) {
|
||||
entriesToReview = entriesToReview.slice(startIdx);
|
||||
}
|
||||
|
||||
// --- Generate tests ---
|
||||
|
||||
test.describe('Fixture Review', () => {
|
||||
test.describe.configure({ mode: 'serial' });
|
||||
test.setTimeout(600_000);
|
||||
|
||||
for (let i = 0; i < entriesToReview.length; i++) {
|
||||
const entry = entriesToReview[i];
|
||||
const globalIdx = allEntries.indexOf(entry) + 1;
|
||||
const fixture = loadFixture(entry);
|
||||
const tier = computeTier(fixture);
|
||||
|
||||
test(`[${globalIdx}/${allEntries.length}] T${tier} | ${entry.artist} - ${entry.title} (${entry.resultCount} results)`, async ({
|
||||
page,
|
||||
}) => {
|
||||
await setupMocks(page, fixture);
|
||||
|
||||
await page.goto('/app');
|
||||
await expect(page.getByLabel(/artist/i)).toBeVisible({ timeout: 15_000 });
|
||||
|
||||
await page.getByLabel(/artist/i).fill(entry.artist);
|
||||
await page.getByLabel(/title/i).fill(entry.title);
|
||||
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
await expect(
|
||||
page
|
||||
.getByText('Perfect match found')
|
||||
.or(page.getByText('Recommended'))
|
||||
.or(page.getByText('Limited sources found'))
|
||||
.or(page.getByText(/no audio sources/i))
|
||||
).toBeVisible({ timeout: 15_000 });
|
||||
|
||||
console.log(`\n${'='.repeat(60)}`);
|
||||
console.log(` [${globalIdx}/${allEntries.length}] ${entry.artist} - ${entry.title}`);
|
||||
console.log(` Tier: ${tier} | Results: ${entry.resultCount}`);
|
||||
console.log(`${'='.repeat(60)}`);
|
||||
|
||||
// Wait for reviewer to type next() in browser console
|
||||
await waitForNext(page, `[${globalIdx}/${allEntries.length}] T${tier} — ${entry.artist} - ${entry.title} (${entry.resultCount} results)`);
|
||||
});
|
||||
}
|
||||
|
||||
if (entriesToReview.length === 0) {
|
||||
test('no fixtures to review', async () => {
|
||||
console.log('No fixtures matched the filter criteria.');
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,589 @@
|
||||
import { test, expect, Page } from '@playwright/test';
|
||||
import * as path from 'path';
|
||||
import { setAuthToken, getEnvAuthToken } from '../helpers/auth';
|
||||
import { createCleanupTracker } from '../helpers/test-cleanup';
|
||||
import { TEST_SONG, URLS, TIMEOUTS } from '../helpers/constants';
|
||||
|
||||
/**
|
||||
* Production E2E Tests: Guided Job Creation Flow
|
||||
*
|
||||
* Tests the 3-step guided job creation flow (Song Info → Choose Audio → Customize & Create)
|
||||
* against the real production backend. Uses route interception to capture outgoing
|
||||
* request bodies while still letting them hit the real API.
|
||||
*
|
||||
* The audio search step uses a confidence tier system:
|
||||
* - Tier 1 ("Perfect match found"): High-confidence lossless result
|
||||
* - Tier 2 ("Recommended"): Good result with caveats
|
||||
* - Tier 3 ("Limited sources found"): Guidance-first, no prominent pick
|
||||
*
|
||||
* Supports two modes:
|
||||
* - Production frontend (default): tests against gen.nomadkaraoke.com
|
||||
* - Local frontend: set E2E_LOCAL=1 to test against localhost:3000 (still uses prod backend)
|
||||
*
|
||||
* Prerequisites:
|
||||
* - KARAOKE_ACCESS_TOKEN: User token with credits
|
||||
* - E2E_ADMIN_TOKEN: Admin token for cleanup (optional, uses KARAOKE_ACCESS_TOKEN as fallback)
|
||||
*
|
||||
* Run against production:
|
||||
* npx playwright test e2e/production/guided-flow.spec.ts --config=playwright.production.config.ts
|
||||
*
|
||||
* Run against local frontend (with prod backend):
|
||||
* E2E_LOCAL=1 npx playwright test e2e/production/guided-flow.spec.ts --config=playwright.production.config.ts
|
||||
*/
|
||||
|
||||
const API_URL = URLS.production.api;
|
||||
const FRONTEND_URL = process.env.E2E_LOCAL
|
||||
? URLS.local.frontend
|
||||
: URLS.production.frontend;
|
||||
|
||||
// Path to the real FLAC fixture (relative to repo root, resolved from frontend/)
|
||||
const UPLOAD_FIXTURE_PATH = path.resolve(__dirname, '..', '..', '..', 'tests', 'data', 'waterloo10sec.flac');
|
||||
|
||||
function getAdminToken(): string | null {
|
||||
return process.env.E2E_ADMIN_TOKEN || getEnvAuthToken() || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper: Intercept a route, capture the response body as JSON, and pass through.
|
||||
* Returns the raw body buffer to route.fulfill() to avoid double-read issues.
|
||||
*/
|
||||
async function fetchAndCapture(
|
||||
route: any,
|
||||
): Promise<{ body: Buffer; json: any; status: number; headers: Record<string, string> }> {
|
||||
const response = await route.fetch();
|
||||
const body = await response.body();
|
||||
let json: any = null;
|
||||
try {
|
||||
json = JSON.parse(body.toString());
|
||||
} catch {
|
||||
// Response wasn't JSON — still pass through
|
||||
}
|
||||
return { body, json, status: response.status(), headers: response.headers() };
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for search results to appear. Matches any confidence tier indicator
|
||||
* or no-results message, since we don't know what tier a real search will produce.
|
||||
*/
|
||||
function waitForSearchComplete(page: Page) {
|
||||
return expect(
|
||||
page.getByText('Perfect match found')
|
||||
.or(page.getByText('Recommended'))
|
||||
.or(page.getByText('Limited sources found'))
|
||||
.or(page.getByText(/no audio sources/i))
|
||||
.or(page.getByText(/taking longer than expected/i))
|
||||
).toBeVisible({ timeout: TIMEOUTS.apiCall });
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for a pick card (Tier 1 or Tier 2) to appear. If Tier 3 (no pick card),
|
||||
* returns false so tests can adapt.
|
||||
*/
|
||||
async function waitForPickCard(page: Page): Promise<boolean> {
|
||||
try {
|
||||
await expect(
|
||||
page.getByText('Perfect match found')
|
||||
.or(page.getByText('Recommended'))
|
||||
).toBeVisible({ timeout: TIMEOUTS.apiCall });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
test.describe('Guided Job Creation Flow', () => {
|
||||
let cleanup: ReturnType<typeof createCleanupTracker>;
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
const token = getEnvAuthToken();
|
||||
test.skip(!token, 'KARAOKE_ACCESS_TOKEN not set — skipping guided flow tests');
|
||||
|
||||
cleanup = createCleanupTracker(getAdminToken()!, API_URL);
|
||||
|
||||
// Authenticate
|
||||
await setAuthToken(page, token!);
|
||||
|
||||
if (process.env.E2E_LOCAL) {
|
||||
console.log(` Mode: LOCAL frontend (${FRONTEND_URL}) → prod backend (${API_URL})`);
|
||||
}
|
||||
});
|
||||
|
||||
test.afterEach(async () => {
|
||||
if (cleanup) {
|
||||
console.log(' Cleaning up test jobs...');
|
||||
const result = await cleanup.cleanupAll();
|
||||
console.log(` Cleanup: ${result.deleted} deleted, ${result.failed} failed`);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test 1: Search → Pick card → Create with defaults
|
||||
// ---------------------------------------------------------------------------
|
||||
test('search → select pick card → create with defaults', async ({ page, request }) => {
|
||||
test.setTimeout(TIMEOUTS.apiCall * 2);
|
||||
|
||||
// Intercept API calls to capture params
|
||||
let searchBody: any = null;
|
||||
let searchJobId: string | null = null;
|
||||
let selectBody: any = null;
|
||||
|
||||
await page.route('**/api/audio-search/search', async (route) => {
|
||||
const req = route.request();
|
||||
if (req.method() === 'POST') {
|
||||
searchBody = req.postDataJSON();
|
||||
const { body, json, status, headers } = await fetchAndCapture(route);
|
||||
searchJobId = json?.job_id;
|
||||
if (searchJobId) cleanup.trackJob(searchJobId);
|
||||
await route.fulfill({ status, headers, body });
|
||||
} else {
|
||||
await route.continue();
|
||||
}
|
||||
});
|
||||
|
||||
await page.route('**/api/audio-search/*/select', async (route) => {
|
||||
const req = route.request();
|
||||
if (req.method() === 'POST') {
|
||||
selectBody = req.postDataJSON();
|
||||
}
|
||||
const { body, status, headers } = await fetchAndCapture(route);
|
||||
await route.fulfill({ status, headers, body });
|
||||
});
|
||||
|
||||
// Step 1: Fill artist/title
|
||||
await page.goto(`${FRONTEND_URL}/app`);
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill(TEST_SONG.artist);
|
||||
await page.getByTestId('guided-title-input').fill(TEST_SONG.title);
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
console.log(' Step 1 complete: submitted search');
|
||||
|
||||
// Step 2: Wait for pick card (Tier 1 or 2) and click "Use This Audio"
|
||||
const hasPickCard = await waitForPickCard(page);
|
||||
test.skip(!hasPickCard, 'Search returned Tier 3 (no pick card) — skipping pick card test');
|
||||
console.log(' Step 2: Pick card visible');
|
||||
|
||||
await page.getByRole('button', { name: /use this audio/i }).click();
|
||||
console.log(' Step 2 complete: selected pick card');
|
||||
|
||||
// Step 3: Click "Create Karaoke Video" with defaults (no overrides, not private)
|
||||
await expect(page.getByRole('heading', { name: 'Customize & Create' })).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
await page.getByRole('button', { name: /create karaoke video/i }).click();
|
||||
|
||||
// Wait for success
|
||||
await expect(page.getByText('Job Created')).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
console.log(' Step 3 complete: job created');
|
||||
|
||||
// Assert: search body has correct params
|
||||
expect(searchBody).toBeTruthy();
|
||||
expect(searchBody.artist).toBe(TEST_SONG.artist);
|
||||
expect(searchBody.title).toBe(TEST_SONG.title);
|
||||
expect(searchBody.is_private).toBeFalsy();
|
||||
console.log(' Verified search request params');
|
||||
|
||||
// Assert: select was called with a numeric index
|
||||
expect(selectBody).toBeTruthy();
|
||||
expect(typeof selectBody.selection_index).toBe('number');
|
||||
console.log(` Verified select request: index=${selectBody.selection_index}`);
|
||||
|
||||
// Assert: backend state via API
|
||||
expect(searchJobId).toBeTruthy();
|
||||
const token = getAdminToken()!;
|
||||
const jobResponse = await request.get(`${API_URL}/api/jobs/${searchJobId}`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
timeout: TIMEOUTS.apiCall,
|
||||
});
|
||||
expect(jobResponse.ok()).toBe(true);
|
||||
const job = await jobResponse.json();
|
||||
expect(job.artist.toLowerCase()).toBe(TEST_SONG.artist.toLowerCase());
|
||||
expect(job.title.toLowerCase()).toBe(TEST_SONG.title.toLowerCase());
|
||||
console.log(` Verified backend job: ${job.artist} - ${job.title} (status: ${job.status})`);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test 2: Search → Select → Custom display names + private
|
||||
// ---------------------------------------------------------------------------
|
||||
test('search → select → custom display names + private', async ({ page, request }) => {
|
||||
test.setTimeout(TIMEOUTS.apiCall * 2);
|
||||
|
||||
let searchJobId: string | null = null;
|
||||
let selectCalled = false;
|
||||
|
||||
await page.route('**/api/audio-search/search', async (route) => {
|
||||
const req = route.request();
|
||||
if (req.method() === 'POST') {
|
||||
const { body, json, status, headers } = await fetchAndCapture(route);
|
||||
searchJobId = json?.job_id;
|
||||
if (searchJobId) cleanup.trackJob(searchJobId);
|
||||
await route.fulfill({ status, headers, body });
|
||||
} else {
|
||||
await route.continue();
|
||||
}
|
||||
});
|
||||
|
||||
await page.route('**/api/audio-search/*/select', async (route) => {
|
||||
selectCalled = true;
|
||||
const { body, status, headers } = await fetchAndCapture(route);
|
||||
await route.fulfill({ status, headers, body });
|
||||
});
|
||||
|
||||
// Step 1: Fill and proceed
|
||||
await page.goto(`${FRONTEND_URL}/app`);
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill(TEST_SONG.artist);
|
||||
await page.getByTestId('guided-title-input').fill(TEST_SONG.title);
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
// Step 2: Wait for pick card and select it
|
||||
const hasPickCard = await waitForPickCard(page);
|
||||
test.skip(!hasPickCard, 'Search returned Tier 3 — skipping pick card test');
|
||||
await page.getByRole('button', { name: /use this audio/i }).click();
|
||||
|
||||
// Step 3: Fill display overrides, check private, and confirm
|
||||
await expect(page.getByRole('heading', { name: 'Customize & Create' })).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
|
||||
await page.locator('#guided-display-artist').fill('PIRI (Display)');
|
||||
await page.locator('#guided-display-title').fill('DOG (Display)');
|
||||
await page.locator('#guided-private').check();
|
||||
console.log(' Filled display overrides and checked Private');
|
||||
|
||||
await page.getByRole('button', { name: /create karaoke video/i }).click();
|
||||
|
||||
// Wait for success
|
||||
await expect(page.getByText('Job Created')).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
console.log(' Job created with custom display names + private');
|
||||
|
||||
// Assert: selectAudioResult was called (confirms job created via search path)
|
||||
expect(selectCalled).toBe(true);
|
||||
console.log(' Verified selectAudioResult was called');
|
||||
|
||||
// Assert: backend state — verify the job exists and has correct base fields
|
||||
// Note: is_private and display overrides are sent during the initial search request,
|
||||
// before the user reaches Step 3. The current flow sends is_private from the parent
|
||||
// state at search time (defaulting to false). Display overrides follow the same pattern.
|
||||
// A future improvement should update these fields when the user confirms on Step 3.
|
||||
expect(searchJobId).toBeTruthy();
|
||||
const token = getAdminToken()!;
|
||||
const jobResponse = await request.get(`${API_URL}/api/jobs/${searchJobId}`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
timeout: TIMEOUTS.apiCall,
|
||||
});
|
||||
expect(jobResponse.ok()).toBe(true);
|
||||
const job = await jobResponse.json();
|
||||
// Verify core fields
|
||||
expect(job.artist.toLowerCase()).toBe(TEST_SONG.artist.toLowerCase());
|
||||
expect(job.title.toLowerCase()).toBe(TEST_SONG.title.toLowerCase());
|
||||
console.log(` Verified backend job: ${job.artist} - ${job.title} (is_private=${job.is_private})`);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test 3: YouTube URL fallback
|
||||
// ---------------------------------------------------------------------------
|
||||
test('YouTube URL fallback', async ({ page }) => {
|
||||
test.setTimeout(TIMEOUTS.apiCall * 2);
|
||||
|
||||
let urlBody: any = null;
|
||||
let urlJobId: string | null = null;
|
||||
|
||||
// Intercept search (to track the search job)
|
||||
let searchJobId: string | null = null;
|
||||
await page.route('**/api/audio-search/search', async (route) => {
|
||||
const req = route.request();
|
||||
if (req.method() === 'POST') {
|
||||
const { body, json, status, headers } = await fetchAndCapture(route);
|
||||
searchJobId = json?.job_id;
|
||||
if (searchJobId) cleanup.trackJob(searchJobId);
|
||||
await route.fulfill({ status, headers, body });
|
||||
} else {
|
||||
await route.continue();
|
||||
}
|
||||
});
|
||||
|
||||
// Intercept URL creation
|
||||
await page.route('**/api/jobs/create-from-url', async (route) => {
|
||||
const req = route.request();
|
||||
if (req.method() === 'POST') {
|
||||
urlBody = req.postDataJSON();
|
||||
const { body, json, status, headers } = await fetchAndCapture(route);
|
||||
urlJobId = json?.job_id;
|
||||
if (urlJobId) cleanup.trackJob(urlJobId);
|
||||
await route.fulfill({ status, headers, body });
|
||||
} else {
|
||||
await route.continue();
|
||||
}
|
||||
});
|
||||
|
||||
// Step 1: Fill and proceed
|
||||
await page.goto(`${FRONTEND_URL}/app`);
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill(TEST_SONG.artist);
|
||||
await page.getByTestId('guided-title-input').fill(TEST_SONG.title);
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
// Wait for search to complete (any tier indicator or no results)
|
||||
await waitForSearchComplete(page);
|
||||
console.log(' Search complete, clicking YouTube URL fallback');
|
||||
|
||||
await page.getByRole('button', { name: 'YouTube URL', exact: true }).click();
|
||||
|
||||
// Fill URL and submit
|
||||
await page.locator('input[type="url"]').fill('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
|
||||
await page.getByRole('button', { name: /use this url/i }).click();
|
||||
|
||||
// Wait for success
|
||||
await expect(page.getByText('Job Created')).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
console.log(' Job created via YouTube URL');
|
||||
|
||||
// Assert: intercepted request body
|
||||
expect(urlBody).toBeTruthy();
|
||||
expect(urlBody.url).toContain('youtube.com');
|
||||
expect(urlBody.artist).toBe(TEST_SONG.artist);
|
||||
expect(urlBody.title).toBe(TEST_SONG.title);
|
||||
console.log(` Verified URL request: url=${urlBody.url}, artist=${urlBody.artist}`);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test 4: File upload fallback
|
||||
// ---------------------------------------------------------------------------
|
||||
test('file upload fallback', async ({ page }) => {
|
||||
test.setTimeout(TIMEOUTS.apiCall * 2);
|
||||
|
||||
let uploadIntercepted = false;
|
||||
let uploadJobId: string | null = null;
|
||||
|
||||
// Intercept search (to track the search job)
|
||||
let searchJobId: string | null = null;
|
||||
await page.route('**/api/audio-search/search', async (route) => {
|
||||
const req = route.request();
|
||||
if (req.method() === 'POST') {
|
||||
const { body, json, status, headers } = await fetchAndCapture(route);
|
||||
searchJobId = json?.job_id;
|
||||
if (searchJobId) cleanup.trackJob(searchJobId);
|
||||
await route.fulfill({ status, headers, body });
|
||||
} else {
|
||||
await route.continue();
|
||||
}
|
||||
});
|
||||
|
||||
// Intercept upload
|
||||
await page.route('**/api/jobs/upload', async (route) => {
|
||||
uploadIntercepted = true;
|
||||
const { body, json, status, headers } = await fetchAndCapture(route);
|
||||
uploadJobId = json?.job_id;
|
||||
if (uploadJobId) cleanup.trackJob(uploadJobId);
|
||||
await route.fulfill({ status, headers, body });
|
||||
});
|
||||
|
||||
// Step 1: Fill and proceed
|
||||
await page.goto(`${FRONTEND_URL}/app`);
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill(TEST_SONG.artist);
|
||||
await page.getByTestId('guided-title-input').fill(TEST_SONG.title);
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
// Wait for search to complete
|
||||
await waitForSearchComplete(page);
|
||||
console.log(' Search complete, clicking Upload fallback');
|
||||
|
||||
await page.getByRole('button', { name: 'Upload file', exact: true }).click();
|
||||
|
||||
// Upload the real FLAC fixture file (tests/data/waterloo10sec.flac)
|
||||
console.log(` Uploading fixture: ${UPLOAD_FIXTURE_PATH}`);
|
||||
const fileInput = page.locator('input[type="file"]');
|
||||
await fileInput.setInputFiles(UPLOAD_FIXTURE_PATH);
|
||||
|
||||
// Click upload submit button
|
||||
await page.getByRole('button', { name: /upload.*create/i }).click();
|
||||
|
||||
// Wait for success
|
||||
await expect(page.getByText('Job Created')).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
console.log(' Job created via file upload');
|
||||
|
||||
// Assert: upload was intercepted
|
||||
expect(uploadIntercepted).toBe(true);
|
||||
console.log(' Verified upload request was sent');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test 5: Back navigation cleans up stale job
|
||||
// ---------------------------------------------------------------------------
|
||||
test('back navigation cleans up stale job', async ({ page }) => {
|
||||
test.setTimeout(TIMEOUTS.apiCall * 2);
|
||||
|
||||
let searchJobId: string | null = null;
|
||||
let deleteIntercepted = false;
|
||||
let deletedJobId: string | null = null;
|
||||
|
||||
await page.route('**/api/audio-search/search', async (route) => {
|
||||
const req = route.request();
|
||||
if (req.method() === 'POST') {
|
||||
const { body, json, status, headers } = await fetchAndCapture(route);
|
||||
searchJobId = json?.job_id;
|
||||
if (searchJobId) cleanup.trackJob(searchJobId);
|
||||
await route.fulfill({ status, headers, body });
|
||||
} else {
|
||||
await route.continue();
|
||||
}
|
||||
});
|
||||
|
||||
// Intercept DELETE calls for job cleanup
|
||||
await page.route('**/api/jobs/*', async (route) => {
|
||||
const req = route.request();
|
||||
if (req.method() === 'DELETE') {
|
||||
deleteIntercepted = true;
|
||||
// Extract job ID from URL path
|
||||
const urlParts = req.url().split('/api/jobs/');
|
||||
if (urlParts[1]) {
|
||||
deletedJobId = urlParts[1].split('?')[0];
|
||||
}
|
||||
}
|
||||
const { body, status, headers } = await fetchAndCapture(route);
|
||||
await route.fulfill({ status, headers, body });
|
||||
});
|
||||
|
||||
// Step 1: Fill and proceed
|
||||
await page.goto(`${FRONTEND_URL}/app`);
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill(TEST_SONG.artist);
|
||||
await page.getByTestId('guided-title-input').fill(TEST_SONG.title);
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
// Step 2: Wait for results to appear
|
||||
await waitForSearchComplete(page);
|
||||
console.log(` Search complete, job ID: ${searchJobId}`);
|
||||
|
||||
// Click "Back"
|
||||
await page.getByRole('button', { name: /back/i }).click();
|
||||
|
||||
// Wait a moment for the cleanup request to fire (it's fire-and-forget)
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
// Assert: DELETE was intercepted
|
||||
expect(deleteIntercepted).toBe(true);
|
||||
console.log(` Verified DELETE intercepted for job: ${deletedJobId}`);
|
||||
|
||||
// Assert: returned to Step 1 (artist/title inputs visible)
|
||||
await expect(page.getByTestId('guided-artist-input')).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
await expect(page.getByTestId('guided-title-input')).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
console.log(' Returned to Step 1 — artist/title inputs visible');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test 6: Fallback options (YouTube URL, Upload file) visible after search
|
||||
// ---------------------------------------------------------------------------
|
||||
test('fallback options visible after search completes', async ({ page }) => {
|
||||
test.setTimeout(TIMEOUTS.apiCall * 2);
|
||||
|
||||
let searchJobId: string | null = null;
|
||||
|
||||
await page.route('**/api/audio-search/search', async (route) => {
|
||||
const req = route.request();
|
||||
if (req.method() === 'POST') {
|
||||
const { body, json, status, headers } = await fetchAndCapture(route);
|
||||
searchJobId = json?.job_id;
|
||||
if (searchJobId) cleanup.trackJob(searchJobId);
|
||||
await route.fulfill({ status, headers, body });
|
||||
} else {
|
||||
await route.continue();
|
||||
}
|
||||
});
|
||||
|
||||
// Step 1: Search for test song (will find results, but fallback options should still appear)
|
||||
await page.goto(`${FRONTEND_URL}/app`);
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill(TEST_SONG.artist);
|
||||
await page.getByTestId('guided-title-input').fill(TEST_SONG.title);
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
console.log(' Submitted search');
|
||||
|
||||
// Wait for search to complete (any tier)
|
||||
await waitForSearchComplete(page);
|
||||
console.log(' Search complete');
|
||||
|
||||
// Assert: fallback options are visible
|
||||
await expect(page.getByRole('button', { name: 'YouTube URL', exact: true })).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
await expect(page.getByRole('button', { name: 'Upload file', exact: true })).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
console.log(' Fallback options (YouTube URL, Upload file) visible');
|
||||
|
||||
// Verify fallback section text (varies by tier)
|
||||
await expect(
|
||||
page.getByText(/not finding what you need/i)
|
||||
.or(page.getByText(/can't find the right version/i))
|
||||
).toBeVisible();
|
||||
console.log(' Fallback helper text visible');
|
||||
|
||||
console.log(` Search job tracked for cleanup: ${searchJobId}`);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test 7: Confidence tier indicator present after search
|
||||
// ---------------------------------------------------------------------------
|
||||
test('shows confidence tier indicator after search', async ({ page }) => {
|
||||
test.setTimeout(TIMEOUTS.apiCall * 2);
|
||||
|
||||
let searchJobId: string | null = null;
|
||||
|
||||
await page.route('**/api/audio-search/search', async (route) => {
|
||||
const req = route.request();
|
||||
if (req.method() === 'POST') {
|
||||
const { body, json, status, headers } = await fetchAndCapture(route);
|
||||
searchJobId = json?.job_id;
|
||||
if (searchJobId) cleanup.trackJob(searchJobId);
|
||||
await route.fulfill({ status, headers, body });
|
||||
} else {
|
||||
await route.continue();
|
||||
}
|
||||
});
|
||||
|
||||
await page.goto(`${FRONTEND_URL}/app`);
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill(TEST_SONG.artist);
|
||||
await page.getByTestId('guided-title-input').fill(TEST_SONG.title);
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
// Wait for any tier indicator
|
||||
await waitForSearchComplete(page);
|
||||
|
||||
// Verify one of the tier-specific elements is present
|
||||
const pickCard = page.getByTestId('pick-card');
|
||||
const guidanceBanner = page.getByTestId('guidance-banner');
|
||||
|
||||
const hasPickCard = await pickCard.isVisible().catch(() => false);
|
||||
const hasGuidanceBanner = await guidanceBanner.isVisible().catch(() => false);
|
||||
|
||||
// At least one must be present (unless no results at all)
|
||||
const noResults = await page.getByText(/no audio sources/i).isVisible().catch(() => false);
|
||||
if (!noResults) {
|
||||
expect(hasPickCard || hasGuidanceBanner).toBe(true);
|
||||
console.log(` Tier indicator: pick-card=${hasPickCard}, guidance-banner=${hasGuidanceBanner}`);
|
||||
} else {
|
||||
console.log(' No results returned — no tier indicator expected');
|
||||
}
|
||||
|
||||
// If pick card is visible, verify "Use This Audio" button exists
|
||||
if (hasPickCard) {
|
||||
await expect(page.getByRole('button', { name: /use this audio/i })).toBeVisible();
|
||||
console.log(' "Use This Audio" button visible in pick card');
|
||||
|
||||
// Check for tier-specific text
|
||||
const isPerfect = await page.getByText('Perfect match found').isVisible().catch(() => false);
|
||||
const isRecommended = await page.getByText('Recommended').isVisible().catch(() => false);
|
||||
console.log(` Tier: ${isPerfect ? 'Tier 1 (Perfect)' : isRecommended ? 'Tier 2 (Recommended)' : 'Unknown'}`);
|
||||
}
|
||||
|
||||
// If guidance banner, verify tips are shown
|
||||
if (hasGuidanceBanner) {
|
||||
await expect(page.getByText(/check the filename/i)).toBeVisible();
|
||||
console.log(' Guidance tips visible in Tier 3 banner');
|
||||
}
|
||||
|
||||
console.log(` Search job tracked for cleanup: ${searchJobId}`);
|
||||
});
|
||||
});
|
||||
@@ -13,8 +13,8 @@ import { createEmailHelper, isEmailTestingAvailable } from '../helpers/email-tes
|
||||
* 1. Landing Page - Navigate and verify
|
||||
* 2. New User Signup - Create testmail.app inbox, submit beta form, verify email
|
||||
* 3. Magic Link Auth - Click magic link to authenticate
|
||||
* 4. Create Job - Search for test song via UI
|
||||
* 5. Audio Selection - Select audio source via UI dialog
|
||||
* 4. Create Job - Guided flow Step 1 (Song Info) + Step 2 (Choose Audio)
|
||||
* 5. Audio Selection & Create - Guided flow Step 3 (Customize & Create) → "Job Created"
|
||||
* 6. Wait for Processing - Monitor via UI status updates
|
||||
* 7. Combined Review - Open review UI, preview video, proceed to instrumental
|
||||
* 8. Instrumental Selection - Select instrumental and submit (same page via hash nav)
|
||||
@@ -358,117 +358,119 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// STEP 4: Create Karaoke Job (via UI)
|
||||
// STEP 4: Create Karaoke Job via Guided Flow
|
||||
// The new guided flow has 3 inline steps:
|
||||
// Step 1 (Song Info): Fill artist/title → "Choose Audio"
|
||||
// Step 2 (Choose Audio): Auto-search → select result
|
||||
// Step 3 (Customize & Create): Confirm settings → "Create Karaoke Video"
|
||||
// =========================================================================
|
||||
console.log('\n========================================');
|
||||
console.log('STEP 4: Create Karaoke Job');
|
||||
console.log('STEP 4: Create Karaoke Job (Guided Flow)');
|
||||
console.log('========================================');
|
||||
|
||||
// Navigate to Search tab
|
||||
await page.getByRole('tab', { name: /search/i }).click();
|
||||
await page.waitForTimeout(1000);
|
||||
// --- Guided Step 1: Song Info ---
|
||||
await page.getByTestId('guided-artist-input').fill(TEST_SONG.artist);
|
||||
await page.getByTestId('guided-title-input').fill(TEST_SONG.title);
|
||||
console.log(` Filled song info: ${TEST_SONG.artist} - ${TEST_SONG.title}`);
|
||||
|
||||
// Fill artist and title (using data-testid for robust test selectors)
|
||||
await page.getByTestId('search-artist-input').fill(TEST_SONG.artist);
|
||||
await page.getByTestId('search-title-input').fill(TEST_SONG.title);
|
||||
console.log(` Searching for: ${TEST_SONG.artist} - ${TEST_SONG.title}`);
|
||||
await page.screenshot({ path: 'test-results/04a-song-info.png' });
|
||||
|
||||
await page.screenshot({ path: 'test-results/04a-search-form.png' });
|
||||
|
||||
// Submit search
|
||||
await page.getByRole('button', { name: /search.*create/i }).click();
|
||||
|
||||
// Wait for job card to appear
|
||||
console.log(' Waiting for job card...');
|
||||
const jobCard = page.locator('[class*="rounded-lg"][class*="border"]').filter({
|
||||
hasText: `${TEST_SONG.artist} - ${TEST_SONG.title}`
|
||||
}).first();
|
||||
|
||||
await expect(jobCard).toBeVisible({ timeout: TIMEOUTS.audioSearch });
|
||||
console.log(' Job card visible');
|
||||
|
||||
// Extract job ID from the card's full text content
|
||||
// The ID appears as "ID: xxxxxxxx" in the card text (e.g., "piri - dogID: af10c81f")
|
||||
const cardFullText = await jobCard.textContent() || '';
|
||||
const idMatch = cardFullText.match(/ID:\s*([a-f0-9]{8,})/i);
|
||||
if (idMatch) {
|
||||
jobId = idMatch[1];
|
||||
console.log(` Job ID: ${jobId}`);
|
||||
} else {
|
||||
console.log(` WARNING: Could not extract job ID from card text`);
|
||||
console.log(` Card text sample: ${cardFullText.substring(0, 100)}...`);
|
||||
}
|
||||
|
||||
await page.screenshot({ path: 'test-results/04b-job-created.png' });
|
||||
console.log('STEP 4 COMPLETE: Job created');
|
||||
// Click "Choose Audio" to advance to Step 2 and trigger search
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
console.log(' Clicked "Choose Audio" — searching for audio sources...');
|
||||
|
||||
// =========================================================================
|
||||
// STEP 5: Audio Selection (via UI)
|
||||
// STEP 5: Audio Selection (Guided Step 2)
|
||||
// =========================================================================
|
||||
console.log('\n========================================');
|
||||
console.log('STEP 5: Audio Selection');
|
||||
console.log('STEP 5: Audio Selection (Guided Step 2)');
|
||||
console.log('========================================');
|
||||
|
||||
// Wait for job to need audio selection or skip if not needed
|
||||
await page.waitForTimeout(5000);
|
||||
// Wait for search results to appear (Tier 1/2/3 or no results)
|
||||
await expect(
|
||||
page.getByText('Perfect match found')
|
||||
.or(page.getByText('Recommended'))
|
||||
.or(page.getByText('Limited sources found'))
|
||||
.or(page.getByText(/no audio sources/i))
|
||||
).toBeVisible({ timeout: TIMEOUTS.audioSearch });
|
||||
|
||||
// Check if Select Audio button appears
|
||||
const selectAudioBtn = jobCard.getByRole('button', { name: /select audio/i });
|
||||
if (await selectAudioBtn.isVisible({ timeout: 30000 }).catch(() => false)) {
|
||||
console.log(' Opening audio selection dialog...');
|
||||
await selectAudioBtn.click();
|
||||
await page.waitForTimeout(2000);
|
||||
await page.screenshot({ path: 'test-results/05a-search-results.png' });
|
||||
|
||||
const dialog = page.locator('[role="dialog"]');
|
||||
if (await dialog.isVisible({ timeout: 5000 })) {
|
||||
await page.screenshot({ path: 'test-results/05a-audio-dialog-loading.png' });
|
||||
|
||||
// Wait for the loading spinner to disappear
|
||||
// The AudioSearchDialog shows "Loading..." while fetching results
|
||||
const loadingIndicator = dialog.getByText(/loading/i);
|
||||
try {
|
||||
await expect(loadingIndicator).not.toBeVisible({ timeout: 60000 });
|
||||
console.log(' Audio results loaded');
|
||||
} catch {
|
||||
console.log(' WARNING: Loading indicator timeout');
|
||||
}
|
||||
|
||||
await page.screenshot({ path: 'test-results/05b-audio-dialog-loaded.png' });
|
||||
|
||||
// Check for "No audio sources found" message
|
||||
const noResultsMsg = dialog.getByText(/no audio sources found/i);
|
||||
if (await noResultsMsg.isVisible({ timeout: 2000 }).catch(() => false)) {
|
||||
console.log(' WARNING: No audio sources found - this may cause the test to fail');
|
||||
await page.screenshot({ path: 'test-results/05b-no-audio-sources.png' });
|
||||
}
|
||||
|
||||
// Find and click first Select button
|
||||
const selectButtons = dialog.getByRole('button', { name: /^select$/i });
|
||||
const count = await selectButtons.count();
|
||||
console.log(` Found ${count} audio options`);
|
||||
|
||||
if (count > 0) {
|
||||
await selectButtons.first().click();
|
||||
console.log(' Audio selected via UI');
|
||||
|
||||
// Wait for dialog to close
|
||||
await dialog.waitFor({ state: 'hidden', timeout: TIMEOUTS.audioSearch }).catch(() => {
|
||||
console.log(' Dialog still open - pressing Escape');
|
||||
return page.keyboard.press('Escape');
|
||||
});
|
||||
} else {
|
||||
console.log(' ERROR: No Select buttons found - closing dialog');
|
||||
await page.keyboard.press('Escape');
|
||||
// This is a critical error - the job won't progress without audio selection
|
||||
throw new Error('No audio sources available for selection. The job cannot proceed.');
|
||||
}
|
||||
// Determine tier and select audio
|
||||
const hasPickCard = await page.getByTestId('pick-card').isVisible().catch(() => false);
|
||||
if (hasPickCard) {
|
||||
// Tier 1 or 2: click "Use This Audio" on the pick card
|
||||
const tierText = await page.getByText('Perfect match found').isVisible().catch(() => false)
|
||||
? 'Tier 1 (Perfect match)' : 'Tier 2 (Recommended)';
|
||||
console.log(` ${tierText} — clicking "Use This Audio"`);
|
||||
await page.getByRole('button', { name: /use this audio/i }).click();
|
||||
} else if (await page.getByText('Limited sources found').isVisible().catch(() => false)) {
|
||||
// Tier 3: find and click the first Select button in results
|
||||
console.log(' Tier 3 (Limited sources) — selecting first available result');
|
||||
const selectBtns = page.getByRole('button', { name: /^select$/i });
|
||||
const count = await selectBtns.count();
|
||||
console.log(` Found ${count} selectable results`);
|
||||
if (count > 0) {
|
||||
await selectBtns.first().click();
|
||||
} else {
|
||||
throw new Error('No audio sources available for selection');
|
||||
}
|
||||
} else {
|
||||
console.log(' No audio selection needed - job auto-selected or cached');
|
||||
throw new Error('No audio sources found — cannot proceed');
|
||||
}
|
||||
|
||||
await page.screenshot({ path: 'test-results/05c-after-audio.png' });
|
||||
console.log('STEP 5 COMPLETE: Audio selection handled');
|
||||
await page.screenshot({ path: 'test-results/05b-audio-selected.png' });
|
||||
console.log(' Audio source selected');
|
||||
|
||||
// --- Guided Step 3: Customize & Create ---
|
||||
console.log(' Waiting for Customize & Create step...');
|
||||
await expect(page.getByRole('heading', { name: 'Customize & Create' })).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
|
||||
await page.screenshot({ path: 'test-results/05c-customize-step.png' });
|
||||
|
||||
// Accept defaults and create
|
||||
await page.getByRole('button', { name: /create karaoke video/i }).click();
|
||||
console.log(' Clicked "Create Karaoke Video"');
|
||||
|
||||
// Wait for success state
|
||||
await expect(page.getByText('Job Created')).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
console.log(' Job created successfully!');
|
||||
|
||||
// Read the job ID from the success card (shown as "ID: xxxxxxxx")
|
||||
const createdJobIdEl = page.getByTestId('created-job-id');
|
||||
if (await createdJobIdEl.isVisible({ timeout: 5000 }).catch(() => false)) {
|
||||
const idText = await createdJobIdEl.textContent() || '';
|
||||
const idMatch = idText.match(/ID:\s*([a-f0-9]{8,})/i);
|
||||
if (idMatch) {
|
||||
jobId = idMatch[1];
|
||||
console.log(` Job ID: ${jobId}`);
|
||||
}
|
||||
}
|
||||
|
||||
await page.screenshot({ path: 'test-results/05d-job-created.png' });
|
||||
|
||||
// Find the job card in the Recent Jobs panel
|
||||
console.log(' Looking for job card in Recent Jobs...');
|
||||
|
||||
// Wait a moment for the jobs list to refresh after creation
|
||||
await page.waitForTimeout(3000);
|
||||
|
||||
// Click Refresh to ensure job list is up to date
|
||||
const refreshBtn = page.getByRole('button', { name: /refresh/i });
|
||||
if (await refreshBtn.isVisible({ timeout: 5000 }).catch(() => false)) {
|
||||
await refreshBtn.click();
|
||||
await page.waitForTimeout(3000);
|
||||
}
|
||||
|
||||
// Find the specific job card using the job ID from the success screen
|
||||
const jobCard = page.locator('[class*="rounded-lg"][class*="border"][class*="p-3"]').filter({
|
||||
hasText: new RegExp(`ID:\\s*${jobId ? jobId.slice(0, 8) : TEST_SONG.artist}`, 'i')
|
||||
}).first();
|
||||
|
||||
await expect(jobCard).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
console.log(' Job card visible in Recent Jobs');
|
||||
|
||||
console.log('STEP 5 COMPLETE: Job created via guided flow');
|
||||
|
||||
// =========================================================================
|
||||
// STEP 6: Wait for Lyrics Processing
|
||||
@@ -724,9 +726,9 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
|
||||
|
||||
// Refresh main app
|
||||
await page.bringToFront();
|
||||
const refreshBtn = page.getByRole('button', { name: /refresh/i });
|
||||
if (await refreshBtn.isVisible().catch(() => false)) {
|
||||
await refreshBtn.click();
|
||||
const refreshBtnAfterInstrumental = page.getByRole('button', { name: /refresh/i });
|
||||
if (await refreshBtnAfterInstrumental.isVisible().catch(() => false)) {
|
||||
await refreshBtnAfterInstrumental.click();
|
||||
await page.waitForTimeout(3000);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,52 +2,56 @@ import { test, expect } from '@playwright/test';
|
||||
import { setupApiFixtures, setAuthToken } from '../fixtures/test-helper';
|
||||
|
||||
/**
|
||||
* Regression Tests - Karaoke Generation Flow
|
||||
* Regression Tests - Karaoke Generation Flow (3-Step Guided Flow)
|
||||
*
|
||||
* Tests the karaoke generation UI elements using mocked API responses.
|
||||
* These tests run offline in CI without hitting production.
|
||||
* Tests the 3-step guided job creation:
|
||||
* Step 1: Song Info (artist/title inputs)
|
||||
* Step 2: Choose Audio (search results with confidence tier UI + fallback options)
|
||||
* Step 3: Customize & Create (title card, display overrides, privacy, submit)
|
||||
*
|
||||
* Uses mocked API responses — runs offline in CI.
|
||||
*/
|
||||
|
||||
// Mock data
|
||||
const MOCK_USER = {
|
||||
email: 'test@example.com',
|
||||
credits: 5,
|
||||
is_beta: true,
|
||||
};
|
||||
|
||||
const MOCK_AUDIO_RESULTS = [
|
||||
const MOCK_SEARCH_RESULTS = [
|
||||
{
|
||||
id: 'audio-1',
|
||||
title: 'Test Song - High Quality',
|
||||
format: 'FLAC',
|
||||
bitrate: '1411',
|
||||
size: '45MB',
|
||||
source: 'Deezer',
|
||||
index: 0,
|
||||
title: 'Bohemian Rhapsody',
|
||||
artist: 'Queen',
|
||||
is_lossless: true,
|
||||
seeders: 85,
|
||||
provider: 'other',
|
||||
quality: 'FLAC 16bit 44.1kHz',
|
||||
quality_data: { format: 'FLAC', bit_depth: 16, sample_rate: 44100, media: 'CD' },
|
||||
release_type: 'Album',
|
||||
label: 'EMI',
|
||||
year: 1975,
|
||||
},
|
||||
{
|
||||
id: 'audio-2',
|
||||
title: 'Test Song - Standard',
|
||||
format: 'MP3',
|
||||
bitrate: '320',
|
||||
size: '12MB',
|
||||
source: 'Tidal',
|
||||
index: 1,
|
||||
title: 'Bohemian Rhapsody',
|
||||
artist: 'Queen',
|
||||
is_lossless: true,
|
||||
seeders: 12,
|
||||
provider: 'other',
|
||||
quality: 'FLAC 16bit 44.1kHz',
|
||||
quality_data: { format: 'FLAC', bit_depth: 16, sample_rate: 44100, media: 'CD' },
|
||||
release_type: 'Album',
|
||||
label: 'Hollywood Records',
|
||||
year: 1991,
|
||||
},
|
||||
{
|
||||
index: 2,
|
||||
title: 'Bohemian Rhapsody',
|
||||
artist: 'Queen',
|
||||
is_lossless: false,
|
||||
provider: 'YouTube',
|
||||
channel: 'Queen Official',
|
||||
view_count: 1500000000,
|
||||
},
|
||||
];
|
||||
|
||||
const MOCK_INSTRUMENTALS = [
|
||||
{
|
||||
id: 'instrumental-clean',
|
||||
name: 'Clean (no backing vocals)',
|
||||
description: 'Pure instrumental with all vocals removed',
|
||||
},
|
||||
{
|
||||
id: 'instrumental-backing',
|
||||
name: 'With backing vocals',
|
||||
description: 'Lead vocals removed, backing vocals preserved',
|
||||
},
|
||||
];
|
||||
|
||||
// Standard mocks for app page tests
|
||||
// Standard mocks for the app page
|
||||
const APP_PAGE_MOCKS = [
|
||||
{
|
||||
method: 'GET',
|
||||
@@ -76,53 +80,477 @@ const APP_PAGE_MOCKS = [
|
||||
},
|
||||
];
|
||||
|
||||
test.describe('Karaoke Generation - Search Tab', () => {
|
||||
// Mocks for a successful search flow
|
||||
const SEARCH_FLOW_MOCKS = [
|
||||
...APP_PAGE_MOCKS,
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/api/audio-search/search',
|
||||
response: {
|
||||
body: {
|
||||
job_id: 'new-job-123',
|
||||
status: 'audio_search',
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/api/audio-search/new-job-123/results',
|
||||
response: {
|
||||
body: {
|
||||
results: MOCK_SEARCH_RESULTS,
|
||||
status: 'search_complete',
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/api/audio-search/new-job-123/select',
|
||||
response: {
|
||||
body: {
|
||||
job_id: 'new-job-123',
|
||||
status: 'downloading',
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
test.describe('Step 1: Song Info', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await setAuthToken(page, 'test-token');
|
||||
});
|
||||
|
||||
test('search tab shows artist and title inputs', async ({ page }) => {
|
||||
test('shows artist and title inputs on load', async ({ page }) => {
|
||||
await setupApiFixtures(page, { mocks: APP_PAGE_MOCKS });
|
||||
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Click Search tab
|
||||
await page.getByRole('tab', { name: /search/i }).click();
|
||||
|
||||
// Verify inputs (using data-testid for robust selectors)
|
||||
await expect(page.getByTestId('search-artist-input')).toBeVisible();
|
||||
await expect(page.getByTestId('search-title-input')).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: /search.*create/i })).toBeVisible();
|
||||
await expect(page.getByTestId('guided-artist-input')).toBeVisible();
|
||||
await expect(page.getByTestId('guided-title-input')).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: /choose audio/i })).toBeVisible();
|
||||
});
|
||||
|
||||
test('search form validates required fields', async ({ page }) => {
|
||||
test('shows step indicator with 3 steps', async ({ page }) => {
|
||||
await setupApiFixtures(page, { mocks: APP_PAGE_MOCKS });
|
||||
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByRole('tab', { name: /search/i }).click();
|
||||
|
||||
// Try to submit without filling fields
|
||||
await page.getByRole('button', { name: /search.*create/i }).click();
|
||||
|
||||
// Form should not submit (fields are required)
|
||||
// Page should still be on app
|
||||
expect(page.url()).toContain('/app');
|
||||
// Step indicator should show 3 labels (use navigation region to avoid matching headings/buttons)
|
||||
const stepNav = page.getByLabel('Progress');
|
||||
await expect(stepNav.getByText('Song Info')).toBeVisible();
|
||||
await expect(stepNav.getByText('Choose Audio')).toBeVisible();
|
||||
await expect(stepNav.getByText('Customize & Create')).toBeVisible();
|
||||
});
|
||||
|
||||
test('search creates a new job', async ({ page }) => {
|
||||
test('Choose Audio button is disabled without inputs', async ({ page }) => {
|
||||
await setupApiFixtures(page, { mocks: APP_PAGE_MOCKS });
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
const btn = page.getByRole('button', { name: /choose audio/i });
|
||||
await expect(btn).toBeDisabled();
|
||||
});
|
||||
|
||||
test('Choose Audio button enables after filling both fields', async ({ page }) => {
|
||||
await setupApiFixtures(page, { mocks: APP_PAGE_MOCKS });
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill('Queen');
|
||||
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
|
||||
|
||||
const btn = page.getByRole('button', { name: /choose audio/i });
|
||||
await expect(btn).toBeEnabled();
|
||||
});
|
||||
|
||||
test('shows guidance text about audio sources', async ({ page }) => {
|
||||
await setupApiFixtures(page, { mocks: APP_PAGE_MOCKS });
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Should show compact guidance about audio source options
|
||||
await expect(page.getByText('We find the best audio')).toBeVisible();
|
||||
await expect(page.getByText('upload a file', { exact: true })).toBeVisible();
|
||||
// YouTube URL appears in both guidance row and tip - just check at least one is visible
|
||||
await expect(page.getByText('YouTube URL').first()).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows tip about specific versions', async ({ page }) => {
|
||||
await setupApiFixtures(page, { mocks: APP_PAGE_MOCKS });
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await expect(page.getByText(/specific version/i)).toBeVisible();
|
||||
await expect(page.getByText(/Live at Wembley/)).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('Step 2: Choose Audio - Search Results', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await setAuthToken(page, 'test-token');
|
||||
});
|
||||
|
||||
test('advances to Step 2 and shows search loading', async ({ page }) => {
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
...APP_PAGE_MOCKS,
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/api/audio-search/search',
|
||||
response: {
|
||||
body: { job_id: 'new-job-123', status: 'audio_search' },
|
||||
},
|
||||
},
|
||||
// Don't mock results yet — let it poll
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/api/audio-search/new-job-123/results',
|
||||
response: {
|
||||
body: { results: [], status: 'audio_search' },
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Fill and submit Step 1
|
||||
await page.getByTestId('guided-artist-input').fill('Queen');
|
||||
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
// Should show searching state
|
||||
await expect(page.getByText('Searching for audio sources')).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows pick card with best result after search completes', async ({ page }) => {
|
||||
await setupApiFixtures(page, { mocks: SEARCH_FLOW_MOCKS });
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill('Queen');
|
||||
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
// Wait for results to load
|
||||
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Best result should be the high-seeder lossless one
|
||||
await expect(page.getByText('LOSSLESS').first()).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: /use this audio/i })).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows other options expander', async ({ page }) => {
|
||||
await setupApiFixtures(page, { mocks: SEARCH_FLOW_MOCKS });
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill('Queen');
|
||||
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
// Wait for results
|
||||
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Should show expandable "other options"
|
||||
await expect(page.getByText(/(?:show|see).*other option/i)).toBeVisible();
|
||||
});
|
||||
|
||||
test('expands other options and shows categorized results', async ({ page }) => {
|
||||
await setupApiFixtures(page, { mocks: SEARCH_FLOW_MOCKS });
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill('Queen');
|
||||
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Expand other options
|
||||
await page.getByText(/(?:show|see).*other option/i).click();
|
||||
|
||||
// Should show category headers for remaining results
|
||||
await expect(page.getByText(/hide other options/i)).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows fallback options (YouTube URL and Upload)', async ({ page }) => {
|
||||
await setupApiFixtures(page, { mocks: SEARCH_FLOW_MOCKS });
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill('Queen');
|
||||
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Fallback buttons should be visible
|
||||
await expect(page.getByRole('button', { name: /youtube url/i })).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: /upload file/i })).toBeVisible();
|
||||
});
|
||||
|
||||
test('YouTube URL button toggles form', async ({ page }) => {
|
||||
await setupApiFixtures(page, { mocks: SEARCH_FLOW_MOCKS });
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill('Queen');
|
||||
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Click YouTube URL button
|
||||
await page.getByRole('button', { name: /youtube url/i }).click();
|
||||
|
||||
// Should show URL input form
|
||||
await expect(page.locator('input[type="url"]')).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: /use this url/i })).toBeVisible();
|
||||
});
|
||||
|
||||
test('Upload button toggles file upload form', async ({ page }) => {
|
||||
await setupApiFixtures(page, { mocks: SEARCH_FLOW_MOCKS });
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill('Queen');
|
||||
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Click Upload button
|
||||
await page.getByRole('button', { name: /upload file/i }).click();
|
||||
|
||||
// Should show file upload area
|
||||
await expect(page.locator('input[type="file"]')).toBeAttached();
|
||||
await expect(page.getByRole('button', { name: /upload.*create/i })).toBeVisible();
|
||||
});
|
||||
|
||||
test('Back button returns to Step 1 and cleans up job', async ({ page }) => {
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
...SEARCH_FLOW_MOCKS,
|
||||
{
|
||||
method: 'DELETE',
|
||||
path: '/api/jobs/new-job-123',
|
||||
response: { body: { success: true } },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill('Queen');
|
||||
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Click Back
|
||||
await page.getByRole('button', { name: /back/i }).click();
|
||||
|
||||
// Should return to Step 1 — artist/title inputs should be visible
|
||||
await expect(page.getByTestId('guided-artist-input')).toBeVisible();
|
||||
await expect(page.getByTestId('guided-title-input')).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows no results message when search returns empty', async ({ page }) => {
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
...APP_PAGE_MOCKS,
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/api/audio-search/search',
|
||||
response: {
|
||||
body: { job_id: 'empty-job', status: 'audio_search' },
|
||||
},
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/api/audio-search/empty-job/results',
|
||||
response: {
|
||||
body: { results: [], status: 'search_complete' },
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill('Nonexistent Artist');
|
||||
await page.getByTestId('guided-title-input').fill('Unknown Song');
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
// Wait for empty results
|
||||
await expect(page.getByText('No audio sources found')).toBeVisible({ timeout: 15000 });
|
||||
|
||||
// Fallback options should still be available
|
||||
await expect(page.getByRole('button', { name: /youtube url/i })).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: /upload file/i })).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('Step 2 → Step 3: Audio Selection to Customize', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await setAuthToken(page, 'test-token');
|
||||
});
|
||||
|
||||
test('selecting pick card advances to Step 3', async ({ page }) => {
|
||||
await setupApiFixtures(page, { mocks: SEARCH_FLOW_MOCKS });
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill('Queen');
|
||||
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Click "Use This Audio"
|
||||
await page.getByRole('button', { name: /use this audio/i }).click();
|
||||
|
||||
// Should advance to Step 3 - Customize & Create
|
||||
await expect(page.getByRole('heading', { name: 'Customize & Create' })).toBeVisible();
|
||||
await expect(page.getByText('Title Card Preview')).toBeVisible();
|
||||
});
|
||||
|
||||
test('Step 3 shows display override fields pre-filled from search', async ({ page }) => {
|
||||
await setupApiFixtures(page, { mocks: SEARCH_FLOW_MOCKS });
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill('Queen');
|
||||
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
|
||||
await page.getByRole('button', { name: /use this audio/i }).click();
|
||||
|
||||
// Should show display override fields with placeholders matching search values
|
||||
await expect(page.locator('#guided-display-artist')).toBeVisible();
|
||||
await expect(page.locator('#guided-display-title')).toBeVisible();
|
||||
|
||||
// Labels should indicate "same as above"
|
||||
await expect(page.getByText('Title Card Artist')).toBeVisible();
|
||||
await expect(page.getByText('Title Card Title')).toBeVisible();
|
||||
});
|
||||
|
||||
test('Step 3 shows privacy toggle', async ({ page }) => {
|
||||
await setupApiFixtures(page, { mocks: SEARCH_FLOW_MOCKS });
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill('Queen');
|
||||
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
|
||||
await page.getByRole('button', { name: /use this audio/i }).click();
|
||||
|
||||
// Privacy toggle should be visible
|
||||
await expect(page.getByText(/private.*no youtube/i)).toBeVisible();
|
||||
await expect(page.locator('#guided-private')).toBeVisible();
|
||||
});
|
||||
|
||||
test('Step 3 shows "Create Karaoke Video" button', async ({ page }) => {
|
||||
await setupApiFixtures(page, { mocks: SEARCH_FLOW_MOCKS });
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill('Queen');
|
||||
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
|
||||
await page.getByRole('button', { name: /use this audio/i }).click();
|
||||
|
||||
await expect(page.getByRole('button', { name: /create karaoke video/i })).toBeVisible();
|
||||
});
|
||||
|
||||
test('submitting Step 3 calls selectAudioResult and shows success', async ({ page }) => {
|
||||
await setupApiFixtures(page, { mocks: SEARCH_FLOW_MOCKS });
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill('Queen');
|
||||
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
|
||||
await page.getByRole('button', { name: /use this audio/i }).click();
|
||||
|
||||
// Click create
|
||||
await page.getByRole('button', { name: /create karaoke video/i }).click();
|
||||
|
||||
// Should show success state
|
||||
await expect(page.getByText('Job Created')).toBeVisible({ timeout: 5000 });
|
||||
await expect(page.getByText('Queen - Bohemian Rhapsody')).toBeVisible();
|
||||
await expect(page.getByText('What happens next')).toBeVisible();
|
||||
});
|
||||
|
||||
test('success state shows Create Another button', async ({ page }) => {
|
||||
await setupApiFixtures(page, { mocks: SEARCH_FLOW_MOCKS });
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill('Queen');
|
||||
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
|
||||
await page.getByRole('button', { name: /use this audio/i }).click();
|
||||
await page.getByRole('button', { name: /create karaoke video/i }).click();
|
||||
|
||||
await expect(page.getByText('Job Created')).toBeVisible({ timeout: 5000 });
|
||||
|
||||
// Create Another should reset the flow
|
||||
await page.getByRole('button', { name: /create another/i }).click();
|
||||
await expect(page.getByTestId('guided-artist-input')).toBeVisible();
|
||||
});
|
||||
|
||||
test('Back from Step 3 returns to Step 2', async ({ page }) => {
|
||||
await setupApiFixtures(page, { mocks: SEARCH_FLOW_MOCKS });
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByTestId('guided-artist-input').fill('Queen');
|
||||
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
|
||||
await page.getByRole('button', { name: /use this audio/i }).click();
|
||||
|
||||
await expect(page.getByRole('heading', { name: 'Customize & Create' })).toBeVisible();
|
||||
|
||||
// Click Back
|
||||
await page.getByRole('button', { name: /back/i }).click();
|
||||
|
||||
// Should return to Step 2 with results still visible
|
||||
await expect(page.getByText('Perfect match found')).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('Fallback Paths: YouTube URL and Upload', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await setAuthToken(page, 'test-token');
|
||||
});
|
||||
|
||||
test('YouTube URL path creates job and shows success', async ({ page }) => {
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
...SEARCH_FLOW_MOCKS,
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/api/jobs/create-from-url',
|
||||
response: {
|
||||
body: {
|
||||
job_id: 'new-job-123',
|
||||
status: 'audio_search',
|
||||
job_id: 'url-job-456',
|
||||
status: 'downloading',
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -132,26 +560,28 @@ test.describe('Karaoke Generation - Search Tab', () => {
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByRole('tab', { name: /search/i }).click();
|
||||
await page.getByTestId('guided-artist-input').fill('Queen');
|
||||
await page.getByTestId('guided-title-input').fill('Bohemian Rhapsody');
|
||||
await page.getByRole('button', { name: /choose audio/i }).click();
|
||||
|
||||
// Fill form (using data-testid for robust selectors)
|
||||
await page.getByTestId('search-artist-input').fill('piri');
|
||||
await page.getByTestId('search-title-input').fill('dog');
|
||||
await expect(page.getByText('Perfect match found')).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Submit
|
||||
await page.getByRole('button', { name: /search.*create/i }).click();
|
||||
// Click YouTube URL fallback
|
||||
await page.getByRole('button', { name: /youtube url/i }).click();
|
||||
await page.locator('input[type="url"]').fill('https://youtube.com/watch?v=test');
|
||||
await page.getByRole('button', { name: /use this url/i }).click();
|
||||
|
||||
// Should show loading or job created indication
|
||||
await page.waitForTimeout(2000);
|
||||
// Should show success directly (skip Step 3 for fallback paths)
|
||||
await expect(page.getByText('Job Created')).toBeVisible({ timeout: 10000 });
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('Karaoke Generation - Audio Selection', () => {
|
||||
test.describe('Job Status Display', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await setAuthToken(page, 'test-token');
|
||||
});
|
||||
|
||||
test('job awaiting audio shows select audio button', async ({ page }) => {
|
||||
test('awaiting_audio_selection jobs are hidden from Recent Jobs', async ({ page }) => {
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
{
|
||||
@@ -160,69 +590,16 @@ test.describe('Karaoke Generation - Audio Selection', () => {
|
||||
response: {
|
||||
body: [
|
||||
{
|
||||
job_id: 'job-1',
|
||||
artist: 'Test Artist',
|
||||
title: 'Test Song',
|
||||
job_id: 'search-job',
|
||||
artist: 'Searching Artist',
|
||||
title: 'Searching Song',
|
||||
status: 'awaiting_audio_selection',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/api/users/me',
|
||||
response: {
|
||||
body: {
|
||||
user: { email: 'test@example.com', credits: 5, role: 'user' },
|
||||
has_session: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/api/themes',
|
||||
response: { body: { themes: [] } },
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/api/users/credits/packages',
|
||||
response: { body: { packages: [] } },
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/api/audio-search/job-1/results',
|
||||
response: { body: { results: MOCK_AUDIO_RESULTS } },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Should show Select Audio button for job awaiting audio selection
|
||||
await expect(page.getByRole('button', { name: /select audio/i }).first()).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('Karaoke Generation - Instrumental Selection', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await setAuthToken(page, 'test-token');
|
||||
});
|
||||
|
||||
test('instrumental selection dialog shows options', async ({ page }) => {
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/api/jobs',
|
||||
response: {
|
||||
body: [
|
||||
{
|
||||
job_id: 'job-1',
|
||||
artist: 'Test Artist',
|
||||
title: 'Test Song',
|
||||
status: 'awaiting_instrumental_selection',
|
||||
instrumental_options: MOCK_INSTRUMENTALS,
|
||||
job_id: 'completed-job',
|
||||
artist: 'Done Artist',
|
||||
title: 'Done Song',
|
||||
status: 'complete',
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -253,25 +630,14 @@ test.describe('Karaoke Generation - Instrumental Selection', () => {
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
const instrumentalBtn = page.getByRole('button', { name: /select instrumental/i }).first();
|
||||
if (await instrumentalBtn.isVisible({ timeout: 5000 })) {
|
||||
await instrumentalBtn.click();
|
||||
// Completed job should be visible
|
||||
await expect(page.getByText('Done Artist')).toBeVisible();
|
||||
|
||||
const dialog = page.locator('[role="dialog"]');
|
||||
await expect(dialog).toBeVisible();
|
||||
|
||||
// Should show instrumental options
|
||||
await expect(dialog.getByText(/clean|backing/i).first()).toBeVisible();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('Karaoke Generation - Lyrics Review', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await setAuthToken(page, 'test-token');
|
||||
// awaiting_audio_selection job should NOT be visible in Recent Jobs
|
||||
await expect(page.getByText('Searching Artist')).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('job in review status is displayed', async ({ page }) => {
|
||||
test('in_review job shows review status', async ({ page }) => {
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
{
|
||||
@@ -314,58 +680,7 @@ test.describe('Karaoke Generation - Lyrics Review', () => {
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Should show job artist
|
||||
await expect(page.getByText('Test Artist')).toBeVisible();
|
||||
// Should show review status indicator (button or badge)
|
||||
await expect(page.getByText(/review/i).first()).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('Karaoke Generation - Tabs', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await setAuthToken(page, 'test-token');
|
||||
});
|
||||
|
||||
test('all input tabs are visible', async ({ page }) => {
|
||||
await setupApiFixtures(page, { mocks: APP_PAGE_MOCKS });
|
||||
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Check all tabs exist
|
||||
await expect(page.getByRole('tab', { name: /upload/i })).toBeVisible();
|
||||
await expect(page.getByRole('tab', { name: /url/i })).toBeVisible();
|
||||
await expect(page.getByRole('tab', { name: /search/i })).toBeVisible();
|
||||
});
|
||||
|
||||
test('URL tab shows URL input', async ({ page }) => {
|
||||
await setupApiFixtures(page, { mocks: APP_PAGE_MOCKS });
|
||||
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByRole('tab', { name: /url/i }).click();
|
||||
|
||||
// Should show URL input
|
||||
const urlInput = page.locator('input[type="url"], input[placeholder*="youtube"], input[placeholder*="URL"]');
|
||||
await expect(urlInput.first()).toBeVisible();
|
||||
});
|
||||
|
||||
test('Upload tab shows file input', async ({ page }) => {
|
||||
await setupApiFixtures(page, { mocks: APP_PAGE_MOCKS });
|
||||
|
||||
await page.goto('/app');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await page.getByRole('tab', { name: /upload/i }).click();
|
||||
|
||||
// Should show file upload area
|
||||
const fileInput = page.locator('input[type="file"]');
|
||||
const dropZone = page.locator('text=/drag|drop|upload/i').first();
|
||||
|
||||
const hasFileInput = await fileInput.isVisible().catch(() => false);
|
||||
const hasDropZone = await dropZone.isVisible().catch(() => false);
|
||||
|
||||
expect(hasFileInput || hasDropZone).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useEffect, useRef, useCallback } from 'react'
|
||||
import type { Job } from '@/lib/api'
|
||||
import { isBlockingStatus } from '@/lib/job-status'
|
||||
import { isNotifiableBlockingStatus } from '@/lib/job-status'
|
||||
|
||||
const TITLE_FLASH_INTERVAL = 1000 // ms between title flashes
|
||||
const DEFAULT_TITLE = 'Karaoke Generator'
|
||||
@@ -15,55 +15,87 @@ interface NotificationState {
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a notification sound using Web Audio API.
|
||||
* Returns a function that plays the sound when called.
|
||||
* Play the alert chime — a two-tone chord (A5 + E5) for action-needed / failure.
|
||||
*/
|
||||
function createNotificationSound(): () => void {
|
||||
function playAlertChime(ctx: AudioContext, now: number): void {
|
||||
const oscillator1 = ctx.createOscillator()
|
||||
const oscillator2 = ctx.createOscillator()
|
||||
const gainNode = ctx.createGain()
|
||||
|
||||
oscillator1.connect(gainNode)
|
||||
oscillator2.connect(gainNode)
|
||||
gainNode.connect(ctx.destination)
|
||||
|
||||
oscillator1.frequency.setValueAtTime(880, now) // A5
|
||||
oscillator1.type = 'sine'
|
||||
oscillator2.frequency.setValueAtTime(659.25, now) // E5
|
||||
oscillator2.type = 'sine'
|
||||
|
||||
gainNode.gain.setValueAtTime(0, now)
|
||||
gainNode.gain.linearRampToValueAtTime(0.3, now + 0.02)
|
||||
gainNode.gain.setValueAtTime(0.3, now + 0.1)
|
||||
gainNode.gain.linearRampToValueAtTime(0, now + 0.3)
|
||||
|
||||
oscillator1.start(now)
|
||||
oscillator2.start(now)
|
||||
oscillator1.stop(now + 0.3)
|
||||
oscillator2.stop(now + 0.3)
|
||||
}
|
||||
|
||||
/**
|
||||
* Play the success chime — a rising C major arpeggio (C6 → E6 → G6).
|
||||
* Brighter and quieter than the alert chord so it's unmistakably different.
|
||||
*/
|
||||
function playSuccessChime(ctx: AudioContext, now: number): void {
|
||||
const notes = [1046.50, 1318.51, 1567.98] // C6, E6, G6
|
||||
const noteDuration = 0.12
|
||||
const noteGap = 0.02
|
||||
|
||||
notes.forEach((freq, i) => {
|
||||
const osc = ctx.createOscillator()
|
||||
const gain = ctx.createGain()
|
||||
osc.connect(gain)
|
||||
gain.connect(ctx.destination)
|
||||
|
||||
osc.frequency.setValueAtTime(freq, now)
|
||||
osc.type = 'sine'
|
||||
|
||||
const noteStart = now + i * (noteDuration + noteGap)
|
||||
gain.gain.setValueAtTime(0, noteStart)
|
||||
gain.gain.linearRampToValueAtTime(0.25, noteStart + 0.01)
|
||||
gain.gain.setValueAtTime(0.25, noteStart + noteDuration * 0.7)
|
||||
gain.gain.linearRampToValueAtTime(0, noteStart + noteDuration)
|
||||
|
||||
osc.start(noteStart)
|
||||
osc.stop(noteStart + noteDuration)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a notification sound using Web Audio API.
|
||||
* Returns a function that plays a chime appropriate for the notification reason.
|
||||
*/
|
||||
function createNotificationSound(): (reason: NotificationReason) => void {
|
||||
let audioContext: AudioContext | null = null
|
||||
|
||||
return () => {
|
||||
return (reason: NotificationReason) => {
|
||||
try {
|
||||
// Create or reuse AudioContext (lazy init for browser compatibility)
|
||||
if (!audioContext) {
|
||||
audioContext = new (window.AudioContext || (window as any).webkitAudioContext)()
|
||||
}
|
||||
|
||||
// Resume context if suspended (browsers require user interaction)
|
||||
if (audioContext.state === 'suspended') {
|
||||
audioContext.resume()
|
||||
}
|
||||
|
||||
const now = audioContext.currentTime
|
||||
|
||||
// Create a pleasant two-tone notification sound
|
||||
const oscillator1 = audioContext.createOscillator()
|
||||
const oscillator2 = audioContext.createOscillator()
|
||||
const gainNode = audioContext.createGain()
|
||||
|
||||
oscillator1.connect(gainNode)
|
||||
oscillator2.connect(gainNode)
|
||||
gainNode.connect(audioContext.destination)
|
||||
|
||||
// First tone - higher frequency
|
||||
oscillator1.frequency.setValueAtTime(880, now) // A5
|
||||
oscillator1.type = 'sine'
|
||||
|
||||
// Second tone - lower frequency (harmony)
|
||||
oscillator2.frequency.setValueAtTime(659.25, now) // E5
|
||||
oscillator2.type = 'sine'
|
||||
|
||||
// Envelope: quick attack, short sustain, fade out
|
||||
gainNode.gain.setValueAtTime(0, now)
|
||||
gainNode.gain.linearRampToValueAtTime(0.3, now + 0.02) // Quick attack
|
||||
gainNode.gain.setValueAtTime(0.3, now + 0.1) // Sustain
|
||||
gainNode.gain.linearRampToValueAtTime(0, now + 0.3) // Fade out
|
||||
|
||||
oscillator1.start(now)
|
||||
oscillator2.start(now)
|
||||
oscillator1.stop(now + 0.3)
|
||||
oscillator2.stop(now + 0.3)
|
||||
if (reason === 'complete') {
|
||||
playSuccessChime(audioContext, now)
|
||||
} else {
|
||||
playAlertChime(audioContext, now)
|
||||
}
|
||||
} catch (error) {
|
||||
// Silently fail - notifications are non-critical
|
||||
console.debug('Notification sound failed:', error)
|
||||
}
|
||||
}
|
||||
@@ -79,7 +111,7 @@ export function useJobNotifications(jobs: Job[]) {
|
||||
const previousStatesRef = useRef<Map<string, NotificationState>>(new Map())
|
||||
const titleIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
||||
const originalTitleRef = useRef<string>(DEFAULT_TITLE)
|
||||
const playSoundRef = useRef<() => void>(createNotificationSound())
|
||||
const playSoundRef = useRef<(reason: NotificationReason) => void>(createNotificationSound())
|
||||
const isFlashingRef = useRef<boolean>(false)
|
||||
const hasInteractedRef = useRef<boolean>(false)
|
||||
|
||||
@@ -134,7 +166,7 @@ export function useJobNotifications(jobs: Job[]) {
|
||||
const notify = useCallback((reason: NotificationReason, jobTitle?: string) => {
|
||||
// Play sound if user has interacted with the page
|
||||
if (hasInteractedRef.current) {
|
||||
playSoundRef.current()
|
||||
playSoundRef.current(reason)
|
||||
}
|
||||
|
||||
// Start title flash based on notification type
|
||||
@@ -196,8 +228,8 @@ export function useJobNotifications(jobs: Job[]) {
|
||||
: undefined
|
||||
|
||||
// Check for status transitions that need notifications
|
||||
const wasBlocking = isBlockingStatus(previousState.status)
|
||||
const isNowBlocking = isBlockingStatus(currentStatus)
|
||||
const wasBlocking = isNotifiableBlockingStatus(previousState.status)
|
||||
const isNowBlocking = isNotifiableBlockingStatus(currentStatus)
|
||||
|
||||
// Notify when entering a blocking state (from non-blocking)
|
||||
if (!wasBlocking && isNowBlocking) {
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* Confidence Tier Tests Using Real Production Fixtures
|
||||
*
|
||||
* These tests run against actual search results fetched from production
|
||||
* (stored in e2e/fixtures/data/search-results/) to validate that the
|
||||
* confidence tier system behaves correctly across a variety of real songs.
|
||||
*
|
||||
* To generate/update fixtures:
|
||||
* cd frontend && node e2e/fixtures/fetch-search-fixtures.mjs
|
||||
*
|
||||
* If no fixtures exist, tests are skipped (not failed).
|
||||
*/
|
||||
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import {
|
||||
getSearchConfidence,
|
||||
checkFilenameMismatch,
|
||||
getAvailabilityLabel,
|
||||
categorizeResult,
|
||||
getBestResult,
|
||||
ExtendedAudioSearchResult,
|
||||
} from '../audio-search-utils'
|
||||
|
||||
const FIXTURES_DIR = path.resolve(__dirname, '../../e2e/fixtures/data/search-results')
|
||||
const INDEX_PATH = path.join(FIXTURES_DIR, 'index.json')
|
||||
|
||||
interface FixtureEntry {
|
||||
slug: string
|
||||
artist: string
|
||||
title: string
|
||||
resultCount: number
|
||||
status: string
|
||||
file: string
|
||||
}
|
||||
|
||||
interface Fixture {
|
||||
artist: string
|
||||
title: string
|
||||
resultCount: number
|
||||
results: ExtendedAudioSearchResult[]
|
||||
}
|
||||
|
||||
function loadFixtures(): { index: FixtureEntry[]; fixtures: Map<string, Fixture> } {
|
||||
if (!fs.existsSync(INDEX_PATH)) {
|
||||
return { index: [], fixtures: new Map() }
|
||||
}
|
||||
|
||||
const index: FixtureEntry[] = JSON.parse(fs.readFileSync(INDEX_PATH, 'utf-8'))
|
||||
const fixtures = new Map<string, Fixture>()
|
||||
|
||||
for (const entry of index) {
|
||||
const filePath = path.join(FIXTURES_DIR, entry.file)
|
||||
if (fs.existsSync(filePath)) {
|
||||
fixtures.set(entry.slug, JSON.parse(fs.readFileSync(filePath, 'utf-8')))
|
||||
}
|
||||
}
|
||||
|
||||
return { index, fixtures }
|
||||
}
|
||||
|
||||
const { index, fixtures } = loadFixtures()
|
||||
const hasFixtures = fixtures.size > 0
|
||||
|
||||
describe('Confidence tiers with real production fixtures', () => {
|
||||
if (!hasFixtures) {
|
||||
it('skips — no fixtures found (run: node e2e/fixtures/fetch-search-fixtures.mjs)', () => {
|
||||
console.log('No fixtures found. Run the fixture fetcher to generate them.')
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
it(`loaded ${fixtures.size} fixtures`, () => {
|
||||
expect(fixtures.size).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
// Validate that every fixture gets a valid tier
|
||||
for (const [slug, fixture] of fixtures) {
|
||||
it(`${fixture.artist} - ${fixture.title}: valid tier assignment`, () => {
|
||||
const confidence = getSearchConfidence(fixture.results, fixture.title)
|
||||
expect([1, 2, 3]).toContain(confidence.tier)
|
||||
expect(confidence.reason).toBeTruthy()
|
||||
|
||||
if (fixture.results.length === 0) {
|
||||
expect(confidence.tier).toBe(3)
|
||||
expect(confidence.bestResult).toBeNull()
|
||||
} else {
|
||||
// Best result should be consistent with getBestResult
|
||||
const expectedBest = getBestResult(fixture.results)
|
||||
expect(confidence.bestResult?.index).toBe(expectedBest?.index)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
it('tier distribution is reasonable', () => {
|
||||
const tiers = { 1: 0, 2: 0, 3: 0 }
|
||||
for (const [, fixture] of fixtures) {
|
||||
const confidence = getSearchConfidence(fixture.results, fixture.title)
|
||||
tiers[confidence.tier]++
|
||||
}
|
||||
|
||||
console.log(`Tier distribution: T1=${tiers[1]}, T2=${tiers[2]}, T3=${tiers[3]} (total=${fixtures.size})`)
|
||||
|
||||
// We expect some distribution across tiers, not all one tier
|
||||
// (exact distribution depends on the actual songs, so we just sanity-check)
|
||||
const total = fixtures.size
|
||||
if (total >= 10) {
|
||||
// At least some results should get different tiers
|
||||
const uniqueTiers = Object.values(tiers).filter(v => v > 0).length
|
||||
expect(uniqueTiers).toBeGreaterThanOrEqual(1) // At minimum 1 tier, but ideally 2-3
|
||||
}
|
||||
})
|
||||
|
||||
it('tier 1 results are always BEST CHOICE without mismatch', () => {
|
||||
for (const [, fixture] of fixtures) {
|
||||
const confidence = getSearchConfidence(fixture.results, fixture.title)
|
||||
if (confidence.tier === 1) {
|
||||
expect(confidence.bestCategory).toBe('BEST CHOICE')
|
||||
if (confidence.bestResult?.target_file) {
|
||||
const mismatch = checkFilenameMismatch(fixture.title, confidence.bestResult)
|
||||
expect(mismatch.isMismatch).toBe(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('tier 3 results have no lossless options or have critical warnings', () => {
|
||||
for (const [, fixture] of fixtures) {
|
||||
const confidence = getSearchConfidence(fixture.results, fixture.title)
|
||||
if (confidence.tier === 3 && fixture.results.length > 0) {
|
||||
// Tier 3 should have either: no lossless, or mismatch+low availability
|
||||
const hasLossless = fixture.results.some(r => {
|
||||
const cat = categorizeResult(r)
|
||||
return cat !== 'YOUTUBE' && cat !== 'SPOTIFY' && cat !== 'VINYL RIPS'
|
||||
})
|
||||
if (hasLossless) {
|
||||
// Must have mismatch + low availability to be tier 3 with lossless
|
||||
expect(confidence.warnings.length).toBeGreaterThan(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('warnings array never contains empty strings', () => {
|
||||
for (const [, fixture] of fixtures) {
|
||||
const confidence = getSearchConfidence(fixture.results, fixture.title)
|
||||
for (const warning of confidence.warnings) {
|
||||
expect(warning).toBeTruthy()
|
||||
expect(warning.trim().length).toBeGreaterThan(0)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('availability labels are consistent with seeder counts', () => {
|
||||
for (const [, fixture] of fixtures) {
|
||||
for (const result of fixture.results) {
|
||||
if (result.seeders !== undefined && result.seeders !== null) {
|
||||
const { text } = getAvailabilityLabel(result.seeders)
|
||||
if (result.seeders >= 50) expect(text).toBe('High')
|
||||
else if (result.seeders >= 10) expect(text).toBe('Medium')
|
||||
else expect(text).toBe('Low')
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,508 @@
|
||||
import {
|
||||
categorizeResult,
|
||||
groupResults,
|
||||
getBestResult,
|
||||
getDisplayName,
|
||||
formatCount,
|
||||
formatMetadata,
|
||||
formatQuality,
|
||||
checkFilenameMismatch,
|
||||
getAvailabilityLabel,
|
||||
getSearchConfidence,
|
||||
ExtendedAudioSearchResult,
|
||||
} from '../audio-search-utils'
|
||||
|
||||
// Helper to create a minimal result with overrides
|
||||
function makeResult(overrides: Partial<ExtendedAudioSearchResult> & { index: number }): ExtendedAudioSearchResult {
|
||||
return {
|
||||
title: 'Test Song',
|
||||
artist: 'Test Artist',
|
||||
is_lossless: false,
|
||||
provider: 'other',
|
||||
...overrides,
|
||||
} as ExtendedAudioSearchResult
|
||||
}
|
||||
|
||||
describe('categorizeResult', () => {
|
||||
it('categorizes YouTube provider as YOUTUBE', () => {
|
||||
const result = makeResult({ index: 0, provider: 'YouTube', is_lossless: false })
|
||||
expect(categorizeResult(result)).toBe('YOUTUBE')
|
||||
})
|
||||
|
||||
it('categorizes non-lossless as YOUTUBE', () => {
|
||||
const result = makeResult({ index: 0, is_lossless: false })
|
||||
expect(categorizeResult(result)).toBe('YOUTUBE')
|
||||
})
|
||||
|
||||
it('categorizes lossless with 50+ seeders as BEST CHOICE', () => {
|
||||
const result = makeResult({ index: 0, is_lossless: true, seeders: 55 })
|
||||
expect(categorizeResult(result)).toBe('BEST CHOICE')
|
||||
})
|
||||
|
||||
it('categorizes lossless 24-bit as HI-RES 24-BIT', () => {
|
||||
const result = makeResult({ index: 0, is_lossless: true, seeders: 5, quality_data: { bit_depth: 24 } })
|
||||
expect(categorizeResult(result)).toBe('HI-RES 24-BIT')
|
||||
})
|
||||
|
||||
it('categorizes lossless vinyl media as VINYL RIPS', () => {
|
||||
const result = makeResult({ index: 0, is_lossless: true, seeders: 5, quality_data: { media: 'Vinyl' } })
|
||||
expect(categorizeResult(result)).toBe('VINYL RIPS')
|
||||
})
|
||||
|
||||
it('categorizes vinyl with 50+ seeders as VINYL RIPS (not BEST CHOICE)', () => {
|
||||
const result = makeResult({ index: 0, is_lossless: true, seeders: 100, quality_data: { media: 'Vinyl' } })
|
||||
expect(categorizeResult(result)).toBe('VINYL RIPS')
|
||||
})
|
||||
|
||||
it('categorizes lossless live album as LIVE VERSIONS', () => {
|
||||
const result = makeResult({ index: 0, is_lossless: true, seeders: 5, release_type: 'Live Album' })
|
||||
expect(categorizeResult(result)).toBe('LIVE VERSIONS')
|
||||
})
|
||||
|
||||
it('categorizes lossless compilation as COMPILATIONS', () => {
|
||||
const result = makeResult({ index: 0, is_lossless: true, seeders: 5, release_type: 'Compilation' })
|
||||
expect(categorizeResult(result)).toBe('COMPILATIONS')
|
||||
})
|
||||
|
||||
it('categorizes lossless single as SINGLES', () => {
|
||||
const result = makeResult({ index: 0, is_lossless: true, seeders: 5, release_type: 'Single' })
|
||||
expect(categorizeResult(result)).toBe('SINGLES')
|
||||
})
|
||||
|
||||
it('categorizes lossless album as STUDIO ALBUMS', () => {
|
||||
const result = makeResult({ index: 0, is_lossless: true, seeders: 5, release_type: 'Album' })
|
||||
expect(categorizeResult(result)).toBe('STUDIO ALBUMS')
|
||||
})
|
||||
|
||||
it('categorizes lossless with no release type as STUDIO ALBUMS', () => {
|
||||
const result = makeResult({ index: 0, is_lossless: true, seeders: 5 })
|
||||
expect(categorizeResult(result)).toBe('STUDIO ALBUMS')
|
||||
})
|
||||
|
||||
it('categorizes lossless with unknown release type as OTHER', () => {
|
||||
const result = makeResult({ index: 0, is_lossless: true, seeders: 5, release_type: 'Interview' })
|
||||
expect(categorizeResult(result)).toBe('OTHER')
|
||||
})
|
||||
|
||||
it('categorizes Spotify provider as SPOTIFY', () => {
|
||||
const result = makeResult({ index: 0, provider: 'Spotify', is_lossless: false })
|
||||
expect(categorizeResult(result)).toBe('SPOTIFY')
|
||||
})
|
||||
|
||||
it('categorizes Spotify before checking lossless status', () => {
|
||||
// Spotify results report FLAC quality but is_lossless may vary
|
||||
const result = makeResult({ index: 0, provider: 'Spotify', is_lossless: true, seeders: 100 })
|
||||
expect(categorizeResult(result)).toBe('SPOTIFY')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getBestResult', () => {
|
||||
it('returns null for empty array', () => {
|
||||
expect(getBestResult([])).toBeNull()
|
||||
})
|
||||
|
||||
it('returns the only result when there is one', () => {
|
||||
const result = makeResult({ index: 0, is_lossless: false })
|
||||
expect(getBestResult([result])).toBe(result)
|
||||
})
|
||||
|
||||
it('prefers BEST CHOICE over STUDIO ALBUMS', () => {
|
||||
const bestChoice = makeResult({ index: 0, is_lossless: true, seeders: 100, release_type: 'Album' })
|
||||
const studioAlbum = makeResult({ index: 1, is_lossless: true, seeders: 10, release_type: 'Album' })
|
||||
expect(getBestResult([studioAlbum, bestChoice])).toBe(bestChoice)
|
||||
})
|
||||
|
||||
it('prefers STUDIO ALBUMS over YOUTUBE', () => {
|
||||
const studio = makeResult({ index: 0, is_lossless: true, seeders: 10, release_type: 'Album' })
|
||||
const youtube = makeResult({ index: 1, provider: 'YouTube', is_lossless: false })
|
||||
expect(getBestResult([youtube, studio])).toBe(studio)
|
||||
})
|
||||
|
||||
it('prefers higher seeders within same category', () => {
|
||||
const lowSeeders = makeResult({ index: 0, is_lossless: true, seeders: 5, release_type: 'Album' })
|
||||
const highSeeders = makeResult({ index: 1, is_lossless: true, seeders: 30, release_type: 'Album' })
|
||||
expect(getBestResult([lowSeeders, highSeeders])).toBe(highSeeders)
|
||||
})
|
||||
|
||||
it('skips VINYL RIPS when other options exist', () => {
|
||||
// Use low seeders so vinyl is categorized as VINYL RIPS (not BEST CHOICE)
|
||||
const vinyl = makeResult({ index: 0, is_lossless: true, seeders: 10, quality_data: { media: 'Vinyl' } })
|
||||
const studio = makeResult({ index: 1, is_lossless: true, seeders: 5, release_type: 'Album' })
|
||||
expect(getBestResult([vinyl, studio])).toBe(studio)
|
||||
})
|
||||
|
||||
it('falls back to first result when all are VINYL RIPS', () => {
|
||||
const vinyl1 = makeResult({ index: 0, is_lossless: true, seeders: 10, quality_data: { media: 'Vinyl' } })
|
||||
const vinyl2 = makeResult({ index: 1, is_lossless: true, seeders: 20, quality_data: { media: 'Vinyl' } })
|
||||
expect(getBestResult([vinyl1, vinyl2])).toBe(vinyl1)
|
||||
})
|
||||
|
||||
it('prefers SINGLES over YOUTUBE', () => {
|
||||
const single = makeResult({ index: 0, is_lossless: true, seeders: 3, release_type: 'Single' })
|
||||
const youtube = makeResult({ index: 1, provider: 'YouTube', is_lossless: false, view_count: 1000000 })
|
||||
expect(getBestResult([youtube, single])).toBe(single)
|
||||
})
|
||||
|
||||
it('handles mixed results and picks best category', () => {
|
||||
const results = [
|
||||
makeResult({ index: 0, provider: 'YouTube', is_lossless: false }), // YOUTUBE
|
||||
makeResult({ index: 1, is_lossless: true, seeders: 3, release_type: 'Single' }), // SINGLES
|
||||
makeResult({ index: 2, is_lossless: true, seeders: 80 }), // BEST CHOICE
|
||||
makeResult({ index: 3, is_lossless: true, seeders: 5, quality_data: { media: 'Vinyl' } }), // VINYL (skipped)
|
||||
]
|
||||
expect(getBestResult(results)?.index).toBe(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('groupResults', () => {
|
||||
it('returns empty array for empty input', () => {
|
||||
expect(groupResults([])).toEqual([])
|
||||
})
|
||||
|
||||
it('groups results by category', () => {
|
||||
const results = [
|
||||
makeResult({ index: 0, is_lossless: true, seeders: 100 }), // BEST CHOICE
|
||||
makeResult({ index: 1, is_lossless: true, seeders: 10, release_type: 'Album' }), // STUDIO ALBUMS
|
||||
makeResult({ index: 2, is_lossless: true, seeders: 60 }), // BEST CHOICE
|
||||
]
|
||||
const groups = groupResults(results)
|
||||
expect(groups).toHaveLength(2)
|
||||
expect(groups[0].category).toBe('BEST CHOICE')
|
||||
expect(groups[0].results).toHaveLength(2)
|
||||
expect(groups[1].category).toBe('STUDIO ALBUMS')
|
||||
expect(groups[1].results).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('sorts groups by category order', () => {
|
||||
const results = [
|
||||
makeResult({ index: 0, provider: 'YouTube', is_lossless: false }), // YOUTUBE (lower priority)
|
||||
makeResult({ index: 1, is_lossless: true, seeders: 100 }), // BEST CHOICE (higher priority)
|
||||
]
|
||||
const groups = groupResults(results)
|
||||
expect(groups[0].category).toBe('BEST CHOICE')
|
||||
expect(groups[1].category).toBe('YOUTUBE')
|
||||
})
|
||||
|
||||
it('includes config for each group', () => {
|
||||
const results = [makeResult({ index: 0, is_lossless: true, seeders: 100 })]
|
||||
const groups = groupResults(results)
|
||||
expect(groups[0].config).toBeDefined()
|
||||
expect(groups[0].config.color).toBeDefined()
|
||||
expect(groups[0].config.maxDisplay).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getDisplayName', () => {
|
||||
it('returns channel for YouTube results', () => {
|
||||
const result = makeResult({ index: 0, provider: 'YouTube', channel: 'VEVO' })
|
||||
expect(getDisplayName(result)).toBe('VEVO')
|
||||
})
|
||||
|
||||
it('returns artist for non-YouTube results', () => {
|
||||
const result = makeResult({ index: 0, artist: 'Queen' })
|
||||
expect(getDisplayName(result)).toBe('Queen')
|
||||
})
|
||||
|
||||
it('returns empty string when no artist', () => {
|
||||
const result = makeResult({ index: 0, artist: undefined } as any)
|
||||
expect(getDisplayName(result)).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatCount', () => {
|
||||
it('returns dash for undefined', () => {
|
||||
expect(formatCount(undefined)).toBe('-')
|
||||
})
|
||||
|
||||
it('formats millions', () => {
|
||||
expect(formatCount(1500000)).toBe('1.5M')
|
||||
})
|
||||
|
||||
it('formats thousands', () => {
|
||||
expect(formatCount(5600)).toBe('5.6K')
|
||||
})
|
||||
|
||||
it('returns raw number for small counts', () => {
|
||||
expect(formatCount(42)).toBe('42')
|
||||
})
|
||||
|
||||
it('returns 0 for zero', () => {
|
||||
expect(formatCount(0)).toBe('0')
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatMetadata', () => {
|
||||
it('returns empty string when no metadata', () => {
|
||||
const result = makeResult({ index: 0 })
|
||||
expect(formatMetadata(result)).toBe('')
|
||||
})
|
||||
|
||||
it('formats release type and year', () => {
|
||||
const result = makeResult({ index: 0, release_type: 'Album', year: 1975 } as any)
|
||||
expect(formatMetadata(result)).toBe('[Album / 1975]')
|
||||
})
|
||||
|
||||
it('includes label and edition info', () => {
|
||||
const result = makeResult({ index: 0, release_type: 'Album', label: 'EMI', edition_info: 'Remaster' })
|
||||
expect(formatMetadata(result)).toBe('[Album / EMI / Remaster]')
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatQuality', () => {
|
||||
it('returns quality string when present', () => {
|
||||
const result = makeResult({ index: 0, quality: 'FLAC 16bit 44.1kHz' } as any)
|
||||
expect(formatQuality(result)).toBe('FLAC 16bit 44.1kHz')
|
||||
})
|
||||
|
||||
it('builds quality from quality_data', () => {
|
||||
const result = makeResult({ index: 0, quality_data: { format: 'FLAC', bit_depth: 16, bitrate: 1411 } })
|
||||
expect(formatQuality(result)).toBe('FLAC 16bit 1411kbps')
|
||||
})
|
||||
|
||||
it('returns dash when no quality info', () => {
|
||||
const result = makeResult({ index: 0 })
|
||||
expect(formatQuality(result)).toBe('-')
|
||||
})
|
||||
})
|
||||
|
||||
describe('checkFilenameMismatch', () => {
|
||||
it('returns no mismatch when filename contains search title', () => {
|
||||
const result = makeResult({ index: 0, target_file: 'Coldplay/Parachutes/01 - Yellow.flac' })
|
||||
const check = checkFilenameMismatch('Yellow', result)
|
||||
expect(check.isMismatch).toBe(false)
|
||||
})
|
||||
|
||||
it('returns no mismatch when search title contains filename', () => {
|
||||
const result = makeResult({ index: 0, target_file: 'Yellow.flac' })
|
||||
const check = checkFilenameMismatch('Yellow (Radio Edit)', result)
|
||||
expect(check.isMismatch).toBe(false)
|
||||
})
|
||||
|
||||
it('detects mismatch when filename is a different track', () => {
|
||||
const result = makeResult({ index: 0, target_file: 'Coldplay/Parachutes/03 - Spies.flac' })
|
||||
const check = checkFilenameMismatch('Yellow', result)
|
||||
expect(check.isMismatch).toBe(true)
|
||||
expect(check.suggestedTrack).toBe('Spies')
|
||||
})
|
||||
|
||||
it('strips track number prefixes from filename', () => {
|
||||
const result = makeResult({ index: 0, target_file: '01 - Yellow.flac' })
|
||||
const check = checkFilenameMismatch('Yellow', result)
|
||||
expect(check.isMismatch).toBe(false)
|
||||
})
|
||||
|
||||
it('strips "01. " prefix', () => {
|
||||
const result = makeResult({ index: 0, target_file: '01. Yellow.flac' })
|
||||
const check = checkFilenameMismatch('Yellow', result)
|
||||
expect(check.isMismatch).toBe(false)
|
||||
})
|
||||
|
||||
it('is case-insensitive', () => {
|
||||
const result = makeResult({ index: 0, target_file: 'YELLOW.flac' })
|
||||
const check = checkFilenameMismatch('yellow', result)
|
||||
expect(check.isMismatch).toBe(false)
|
||||
})
|
||||
|
||||
it('ignores punctuation differences', () => {
|
||||
const result = makeResult({ index: 0, target_file: "Don't Look Back in Anger.flac" })
|
||||
const check = checkFilenameMismatch('Dont Look Back in Anger', result)
|
||||
expect(check.isMismatch).toBe(false)
|
||||
})
|
||||
|
||||
it('checks YouTube results using result.title instead of target_file', () => {
|
||||
const matchingResult = makeResult({ index: 0, provider: 'YouTube', title: 'Yellow' })
|
||||
expect(checkFilenameMismatch('Yellow', matchingResult).isMismatch).toBe(false)
|
||||
|
||||
const mismatchResult = makeResult({ index: 0, provider: 'YouTube', title: 'Something Else' })
|
||||
expect(checkFilenameMismatch('Yellow', mismatchResult).isMismatch).toBe(true)
|
||||
})
|
||||
|
||||
it('treats underscores as word separators', () => {
|
||||
const result = makeResult({ index: 0, target_file: '10-Pyro_Sets_A_Wildfire.flac' })
|
||||
const check = checkFilenameMismatch('Pyro Sets a Wildfire', result)
|
||||
expect(check.isMismatch).toBe(false)
|
||||
})
|
||||
|
||||
it('treats hyphens and dots as word separators', () => {
|
||||
const result = makeResult({ index: 0, target_file: 'My-Song.Name.Here.flac' })
|
||||
const check = checkFilenameMismatch('My Song Name Here', result)
|
||||
expect(check.isMismatch).toBe(false)
|
||||
})
|
||||
|
||||
it('returns indeterminate for non-Latin filenames (no false match)', () => {
|
||||
const result = makeResult({ index: 0, target_file: 'תמיד אוהב אותי' })
|
||||
const check = checkFilenameMismatch('I Love You, KoREH', result)
|
||||
// Can't determine match — should return isMismatch: false with empty filename
|
||||
expect(check.isMismatch).toBe(false)
|
||||
expect(check.filename).toBe('')
|
||||
})
|
||||
|
||||
it('rejects very short filenames to avoid false substring matches', () => {
|
||||
const result = makeResult({ index: 0, target_file: 'K.' })
|
||||
const check = checkFilenameMismatch('I Love You, KoREH', result)
|
||||
expect(check.isMismatch).toBe(true)
|
||||
})
|
||||
|
||||
it('uses result.title for Spotify results without target_file', () => {
|
||||
const result = makeResult({ index: 0, provider: 'Spotify', title: 'Yellow', target_file: undefined })
|
||||
// Falls back to title since no target_file
|
||||
const check = checkFilenameMismatch('Yellow', result)
|
||||
expect(check.isMismatch).toBe(false)
|
||||
})
|
||||
|
||||
it('prefers target_file over title when both exist', () => {
|
||||
const result = makeResult({ index: 0, provider: 'Spotify', title: 'Wrong Album', target_file: 'Yellow.flac' })
|
||||
const check = checkFilenameMismatch('Yellow', result)
|
||||
expect(check.isMismatch).toBe(false)
|
||||
})
|
||||
|
||||
it('skips check for very short titles (< 3 chars)', () => {
|
||||
const result = makeResult({ index: 0, target_file: 'Something Else.flac' })
|
||||
const check = checkFilenameMismatch('Go', result)
|
||||
expect(check.isMismatch).toBe(false)
|
||||
})
|
||||
|
||||
it('returns filename in result', () => {
|
||||
const result = makeResult({ index: 0, target_file: 'Coldplay/03 - Spies.flac' })
|
||||
const check = checkFilenameMismatch('Yellow', result)
|
||||
expect(check.filename).toBe('Spies')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getAvailabilityLabel', () => {
|
||||
it('returns High with tooltip for 50+ seeders', () => {
|
||||
const label = getAvailabilityLabel(75)
|
||||
expect(label.text).toBe('High')
|
||||
expect(label.tooltip).toBe('Well-seeded, downloads reliably')
|
||||
})
|
||||
|
||||
it('returns Medium with tooltip for 10-49 seeders', () => {
|
||||
const label = getAvailabilityLabel(25)
|
||||
expect(label.text).toBe('Medium')
|
||||
expect(label.tooltip).toBe('Should download but may be slower')
|
||||
})
|
||||
|
||||
it('returns Low with tooltip for < 10 seeders', () => {
|
||||
const label = getAvailabilityLabel(3)
|
||||
expect(label.text).toBe('Low')
|
||||
expect(label.tooltip).toBe('Few seeders — may take a bit more time to prepare')
|
||||
})
|
||||
|
||||
it('returns empty for undefined', () => {
|
||||
const label = getAvailabilityLabel(undefined)
|
||||
expect(label.text).toBe('')
|
||||
expect(label.tooltip).toBe('')
|
||||
})
|
||||
|
||||
it('returns empty for null', () => {
|
||||
const label = getAvailabilityLabel(null)
|
||||
expect(label.text).toBe('')
|
||||
expect(label.tooltip).toBe('')
|
||||
})
|
||||
|
||||
it('returns Low for 0 seeders', () => {
|
||||
const label = getAvailabilityLabel(0)
|
||||
expect(label.text).toBe('Low')
|
||||
})
|
||||
|
||||
it('returns High for exactly 50 seeders', () => {
|
||||
const label = getAvailabilityLabel(50)
|
||||
expect(label.text).toBe('High')
|
||||
})
|
||||
|
||||
it('returns Medium for exactly 10 seeders', () => {
|
||||
const label = getAvailabilityLabel(10)
|
||||
expect(label.text).toBe('Medium')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getSearchConfidence', () => {
|
||||
it('returns tier 3 for empty results', () => {
|
||||
const confidence = getSearchConfidence([], 'Yellow')
|
||||
expect(confidence.tier).toBe(3)
|
||||
expect(confidence.bestResult).toBeNull()
|
||||
expect(confidence.bestCategory).toBeNull()
|
||||
})
|
||||
|
||||
it('returns tier 1 for BEST CHOICE with no mismatch', () => {
|
||||
const results = [
|
||||
makeResult({ index: 0, is_lossless: true, seeders: 100, target_file: '01 - Yellow.flac' }),
|
||||
]
|
||||
const confidence = getSearchConfidence(results, 'Yellow')
|
||||
expect(confidence.tier).toBe(1)
|
||||
expect(confidence.bestCategory).toBe('BEST CHOICE')
|
||||
expect(confidence.warnings).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('returns tier 2 when BEST CHOICE has filename mismatch (but high availability)', () => {
|
||||
const results = [
|
||||
makeResult({ index: 0, is_lossless: true, seeders: 100, target_file: '03 - Spies.flac' }),
|
||||
]
|
||||
const confidence = getSearchConfidence(results, 'Yellow')
|
||||
expect(confidence.tier).toBe(2)
|
||||
expect(confidence.warnings.length).toBeGreaterThan(0)
|
||||
expect(confidence.warnings.some(w => w.includes('Spies'))).toBe(true)
|
||||
})
|
||||
|
||||
it('returns tier 2 for studio album with moderate seeders', () => {
|
||||
const results = [
|
||||
makeResult({ index: 0, is_lossless: true, seeders: 20, release_type: 'Album', target_file: '01 - Yellow.flac' }),
|
||||
]
|
||||
const confidence = getSearchConfidence(results, 'Yellow')
|
||||
expect(confidence.tier).toBe(2)
|
||||
expect(confidence.bestCategory).toBe('STUDIO ALBUMS')
|
||||
})
|
||||
|
||||
it('returns tier 3 when only YouTube/lossy results', () => {
|
||||
const results = [
|
||||
makeResult({ index: 0, provider: 'YouTube', is_lossless: false }),
|
||||
makeResult({ index: 1, is_lossless: false }),
|
||||
]
|
||||
const confidence = getSearchConfidence(results, 'Yellow')
|
||||
expect(confidence.tier).toBe(3)
|
||||
expect(confidence.warnings.some(w => w.includes('lossless'))).toBe(true)
|
||||
})
|
||||
|
||||
it('returns tier 3 when only vinyl rips', () => {
|
||||
const results = [
|
||||
makeResult({ index: 0, is_lossless: true, seeders: 20, quality_data: { media: 'Vinyl' } }),
|
||||
]
|
||||
const confidence = getSearchConfidence(results, 'Yellow')
|
||||
expect(confidence.tier).toBe(3)
|
||||
})
|
||||
|
||||
it('returns tier 3 for mismatch + low availability', () => {
|
||||
const results = [
|
||||
makeResult({ index: 0, is_lossless: true, seeders: 3, target_file: '03 - Spies.flac' }),
|
||||
]
|
||||
const confidence = getSearchConfidence(results, 'Yellow')
|
||||
expect(confidence.tier).toBe(3)
|
||||
expect(confidence.warnings.some(w => w.includes('Spies'))).toBe(true)
|
||||
expect(confidence.warnings.some(w => w.includes('availability'))).toBe(true)
|
||||
})
|
||||
|
||||
it('includes low availability warning when seeders < 10', () => {
|
||||
const results = [
|
||||
makeResult({ index: 0, is_lossless: true, seeders: 5, target_file: '01 - Yellow.flac' }),
|
||||
]
|
||||
const confidence = getSearchConfidence(results, 'Yellow')
|
||||
expect(confidence.warnings.some(w => w.includes('availability'))).toBe(true)
|
||||
})
|
||||
|
||||
it('builds reason string with quality context', () => {
|
||||
const results = [
|
||||
makeResult({ index: 0, is_lossless: true, seeders: 100, release_type: 'Album', target_file: '01 - Yellow.flac' }),
|
||||
]
|
||||
const confidence = getSearchConfidence(results, 'Yellow')
|
||||
expect(confidence.reason).toContain('lossless')
|
||||
})
|
||||
|
||||
it('bestResult matches getBestResult output', () => {
|
||||
const results = [
|
||||
makeResult({ index: 0, is_lossless: true, seeders: 100 }),
|
||||
makeResult({ index: 1, is_lossless: true, seeders: 5, release_type: 'Album' }),
|
||||
]
|
||||
const confidence = getSearchConfidence(results, 'Test Song')
|
||||
expect(confidence.bestResult?.index).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import type { VideoThemeSummary, VideoThemeDetail, ThemesListResponse, ThemeDetailResponse, ColorOverrides } from './video-themes';
|
||||
import type { MagicLinkResponse, VerifyMagicLinkResponse, UserProfileResponse } from './types';
|
||||
import type { CorrectionData, CorrectionAnnotation } from './lyrics-review/types';
|
||||
import type { CorrectionData, CorrectionAnnotation, EditLog } from './lyrics-review/types';
|
||||
|
||||
// In development, use relative URLs to go through Next.js proxy (avoids CORS)
|
||||
// In production (static export), use the full backend URL
|
||||
@@ -1813,6 +1813,7 @@ export interface OverrideAudioSourceResponse {
|
||||
export interface LyricsReviewApiClient {
|
||||
submitCorrections: (data: CorrectionData) => Promise<void>
|
||||
submitAnnotations: (annotations: Omit<CorrectionAnnotation, 'annotation_id' | 'timestamp'>[]) => Promise<void>
|
||||
submitEditLog: (editLog: EditLog) => Promise<void>
|
||||
updateHandlers: (handlers: string[]) => Promise<CorrectionData>
|
||||
addLyrics: (source: string, lyrics: string) => Promise<CorrectionData>
|
||||
getAudioUrl: (hash: string) => string
|
||||
@@ -1862,7 +1863,7 @@ export function createLyricsReviewApiClient(jobId: string): LyricsReviewApiClien
|
||||
* Submit human annotations/feedback on corrections
|
||||
*/
|
||||
async submitAnnotations(annotations: Omit<CorrectionAnnotation, 'annotation_id' | 'timestamp'>[]): Promise<void> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/annotations`, {
|
||||
const response = await fetch(`${API_BASE_URL}/api/review/${jobId}/v1/annotations`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -1873,6 +1874,18 @@ export function createLyricsReviewApiClient(jobId: string): LyricsReviewApiClien
|
||||
await handleResponse<{ status: string }>(response)
|
||||
},
|
||||
|
||||
async submitEditLog(editLog: EditLog): Promise<void> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/edit-log`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders()
|
||||
},
|
||||
body: JSON.stringify(editLog),
|
||||
})
|
||||
await handleResponse<{ status: string }>(response)
|
||||
},
|
||||
|
||||
/**
|
||||
* Update enabled correction handlers and get recalculated corrections
|
||||
*/
|
||||
|
||||