Compare commits

...
Author SHA1 Message Date
Andrew Beveridge ☄️ 2e145dd927 Merge pull request #11 from nomadkaraoke/feature/batch-3-existing-instrumental
feat: Batch 3 - Existing Instrumental Support for Remote CLI
2025-12-11 02:23:02 -05:00
Andrew Beveridge 2b5ef28789 feat: Batch 3 - Existing Instrumental Support for Remote CLI
Add --existing_instrumental parameter to remote CLI to allow users to upload
and use their own pre-made instrumental file instead of AI-separated audio.

Key changes:
- remote_cli.py: Add existing_instrumental parameter to submit_job()
- file_upload.py: Add existing_instrumental file type with duration validation (±0.5s)
- job.py: Add existing_instrumental_gcs_path field to Job and JobCreate models
- video_worker.py: Download and use user-provided instrumental for final video encoding

Backend still runs AI separation for stems (to provide consistent download outputs),
but uses the user-provided instrumental for the final karaoke video.

Includes 20+ unit tests and maintains >70% coverage.
2025-12-11 02:06:18 -05:00
Andrew Beveridge ☄️ 76940691b1 Merge pull request #10 from nomadkaraoke/fix-upload-max-filesize
feat: implement signed URL uploads to bypass 32MB Cloud Run limit
2025-12-11 01:53:34 -05:00
Andrew Beveridge 4b346dd369 fix: address CodeRabbit review comments
- Remove unused `settings` variable in mark_uploads_complete endpoint
- Rename duplicate TestGCSPathGeneration class to TestSignedUrlGCSPathGeneration
  to avoid shadowing the original test class
2025-12-11 01:45:31 -05:00
Andrew Beveridge 7480950a1b feat: implement signed URL uploads to bypass 32MB Cloud Run limit
The remote CLI was hitting Cloud Run's 32MB request body limit when
uploading large FLAC files with 4K PNG style assets. This implements
a two-step signed URL upload flow that bypasses the limit entirely:

1. CLI calls POST /api/jobs/create-with-upload-urls with job metadata
2. Backend returns signed GCS upload URLs for each file
3. CLI uploads files directly to GCS (no size limit)
4. CLI calls POST /api/jobs/{job_id}/uploads-complete to start processing

Benefits:
- No file size limits (GCS supports up to 5TB)
- Faster uploads (direct to storage, no proxy)
- Works with any HTTP client (no HTTP/2 required)
- Future-proof for web UI uploads

Changes:
- backend/services/storage_service.py: Add generate_signed_upload_url()
- backend/api/routes/file_upload.py: Add two new endpoints + models
- karaoke_gen/utils/remote_cli.py: Refactor submit_job() for signed URLs
- Add 21 new tests for the signed URL upload flow
- Bump version to 0.71.25

Also includes: Download spaCy model at Docker build time (not runtime)
2025-12-11 01:34:15 -05:00
Andrew Beveridge ☄️ 64ada25e9c Merge pull request #9 from nomadkaraoke/feature/batch-2-audio-model-selection
feat: Batch 2 - Audio Separation Model Selection
2025-12-11 01:23:12 -05:00
Andrew Beveridge de6322dd87 feat: Batch 2 - Audio Separation Model Selection
Add support for custom audio separation models in remote CLI:
- `--clean_instrumental_model`: Stage 1 separation model
- `--backing_vocals_models`: Backing vocals separation models
- `--other_stems_models`: Multi-stem separation models (bass, drums, etc.)

Implementation:
- Remote CLI: Added 3 form fields to submit_job(), sends models as comma-separated strings
- Backend: Added 3 Form parameters to /api/jobs/upload, parses comma-separated lists
- Job model: Added clean_instrumental_model, backing_vocals_models, other_stems_models fields
- Audio worker: create_audio_processor() accepts model params from job, passes to Modal API

This enables A/B testing different models and using newer models as they release.
Models are sent to the Modal-hosted audio-separator API which can download any model
on demand and caches them.

Resolves: Batch 2 from BACKEND-FEATURE-PARITY-PLAN.md
2025-12-11 01:05:30 -05:00
Andrew Beveridge ☄️ 49b472429d Merge pull request #8 from nomadkaraoke/chase-feature-parity
feat: Batch 1 - Add lyrics configuration for remote CLI
2025-12-11 00:54:17 -05:00
Andrew Beveridge d57282c770 docs: mark Batch 1 complete, add instructions for future agents
Update BACKEND-FEATURE-PARITY-PLAN.md:
- Mark Batch 1 (Lyrics Configuration) as complete with PR #8
- Update Quick Parity Summary (Lyrics: 100%)
- Mark L1-L4 parameters as ✅ implemented
- Add "Instructions for Implementing a Batch" section:
  - Test coverage requirements (>70%)
  - Required documentation updates checklist
  - Version bump requirement
  - PR format guidelines
- Update Next Steps to reflect current progress
- Add Recent Changes entry for v0.71.22
2025-12-11 00:37:41 -05:00
Andrew Beveridge a41948fe37 test: add unit tests for lyrics configuration parameters
Add comprehensive tests for Batch 1 lyrics configuration:
- TestLyricsFileValidation: validate .txt, .docx, .rtf extensions
- TestLyricsConfigurationFields: verify Job model lyrics fields
- TestLyricsGCSPathGeneration: test GCS path format
- TestJobCreateLyricsFields: verify JobCreate has lyrics fields
- TestLyricsWorkerConfiguration: test LyricsProcessor creation
- TestLyricsOverrideParameters: test lyrics_artist/title overrides
- TestRenderVideoWorkerConfiguration: test subtitle_offset_ms

Bump version to 0.71.22
2025-12-11 00:29:02 -05:00
Andrew Beveridge ffd4e9e377 feat: implement Batch 1 - lyrics configuration for remote CLI
Add support for lyrics override parameters in karaoke-gen-remote:
- L1 --lyrics_artist: Override artist name for lyrics search
- L2 --lyrics_title: Override title for lyrics search
- L3 --lyrics_file: Use user-provided lyrics file instead of API fetch
- L4 --subtitle_offset_ms: Adjust subtitle timing offset

Changes:
- backend/models/job.py: Add lyrics config fields to Job and JobCreate
- backend/api/routes/file_upload.py: Accept lyrics params and file upload
- backend/workers/lyrics_worker.py: Pass lyrics overrides to LyricsProcessor
- backend/workers/render_video_worker.py: Apply subtitle_offset_ms
- karaoke_gen/utils/remote_cli.py: Send lyrics params to backend

Bump version to 0.71.21
2025-12-11 00:24:00 -05:00
Andrew Beveridge ef9c4fc243 Added much improved feature parity plan 2025-12-11 00:15:32 -05:00
Andrew Beveridge 1f030333ae fix: reduce anchor sequence logging verbosity and fix duplicate logs
- Change verbose N-GRAM, ANCHOR SEARCH, and FILTERING logs from INFO to DEBUG level
- Keep only high-level summary logs at INFO (start, completion, totals)
- Fix duplicate logging by removing redundant logger handlers from hierarchy
  - job_log_context no longer adds handlers to root logger
  - LYRICS_WORKER_LOGGERS reduced to top-level package loggers only
- Bump version to 0.71.20
2025-12-10 22:49:59 -05:00
Andrew Beveridge ☄️ 707df6af72 Merge pull request #7 from nomadkaraoke/feature/improve-remote-cli-logging
feat: improve progress logging during video generation for remote CLI
2025-12-10 22:35:01 -05:00
Andrew Beveridge c94c553069 fix: allow job retry by adding FAILED state transitions
The retry endpoint was silently failing because FAILED status had no valid
transitions in STATE_TRANSITIONS. When retrying a failed job:

1. Error state was cleared correctly
2. transition_to_state() returned False (FAILED -> INSTRUMENTAL_SELECTED invalid)
3. Worker was triggered anyway, completed successfully
4. Final transition to COMPLETE also failed (still in FAILED state)

Fix:
- Add retry checkpoint states (INSTRUMENTAL_SELECTED, REVIEW_COMPLETE,
  LYRICS_COMPLETE) as valid transitions from FAILED status
- Add explicit error checking for transition failures in retry endpoint
- Add test coverage for FAILED state retry transitions

This fixes the bug where successfully retried jobs remained stuck in 'failed'
status with error_message=None.
2025-12-10 22:29:30 -05:00
Andrew Beveridge d757b0c860 feat: improve progress logging during video generation for remote CLI
This change addresses the long silence users experienced when monitoring
remote jobs, particularly during video generation (encoding) stage.

Changes:
- video_worker.py: Add detailed progress logging during file downloads
  with estimated times for large files
- video_worker.py: Fix VIDEO_WORKER_LOGGERS to capture KaraokeFinalise
  logs (logger name was mismatched)
- karaoke_finalise.py: Add step-by-step logging for each FFmpeg encoding
  operation with time estimates ([Step 1/6], [Step 2/6], etc.)
- remote_cli.py: Add heartbeat messages when polling has no updates for
  ~30 seconds to show the CLI is still running
- remote_cli.py: Add human-readable status descriptions (e.g. "encoding"
  becomes "Encoding final videos (15-20 min, 4 formats)")

Bump version to 0.71.18
2025-12-10 22:16:57 -05:00
Andrew Beveridge c632e68b5b Updated workflow to push on all branches 2025-12-10 21:54:06 -05:00
Andrew Beveridge ☄️ 9376d53fed Merge pull request #6 from nomadkaraoke/fix-discord-webhook-error
fix: handle Discord webhook errors gracefully and add job retry capability
2025-12-10 20:21:01 -05:00
Andrew Beveridge 18ee2df5a2 test: add comprehensive tests for --retry CLI mode to improve coverage 2025-12-10 20:15:11 -05:00
Andrew Beveridge 68b8cd25a4 fix: handle Discord webhook errors gracefully and add job retry capability
- Fix Discord webhook URL validation to strip trailing whitespace/newlines
  that can be introduced from environment variables or secrets (fixes %0A error)
- Make Discord notification failures non-fatal - log error and continue
- Add --retry CLI command to retry failed jobs from last checkpoint
- Add POST /api/jobs/{job_id}/retry endpoint for retrying failed jobs
- Bump version to 0.71.17

The root cause was environment variables or secrets containing trailing
newline characters (\n) which get URL-encoded as %0A, breaking Discord
API authentication.
2025-12-10 19:31:59 -05:00
Andrew Beveridge ☄️ cd91b06eb9 Merge pull request #5 from nomadkaraoke/replace-modal-with-google-cloud
Replace modal with google cloud for web hosted version
2025-12-10 16:47:53 -05:00
27 changed files with 3895 additions and 296 deletions

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
---
description: Git branching and PR workflow
alwaysApply: true
---
# Branching Workflow
**Never commit directly to `main`.** Always work on a feature branch.
Create descriptive branch names like `feature/add-discord-notifications`, `fix/audio-sync-issue`, or `refactor/cleanup-api-routes`.
# Creating a Pull Request
Once all changes are complete, tests pass, and commits are pushed, create a PR with:
1. **Summary** - Brief overview of the changes
2. **Changes Made** - List of specific modifications
3. **Testing** - How changes were tested (unit tests, manual testing)
4. **Related Issues** - Reference any GitHub issues (e.g., "Fixes #123")
Only merge after review and CI checks pass.
+4 -4
View File
@@ -1,8 +1,7 @@
name: Backend Tests
on:
push:
branches: [ main, replace-modal-with-google-cloud ]
push: # Run on all branch pushes
pull_request:
branches: [ main ]
@@ -143,8 +142,9 @@ jobs:
name: Deploy via Cloud Build
runs-on: ubuntu-latest
needs: [unit-tests, emulator-tests, lint]
# Only deploy on push to the branch (not on PRs)
if: github.event_name == 'push' && github.ref == 'refs/heads/replace-modal-with-google-cloud'
# Deploy on any push where tests pass (pre-alpha: rapid iteration mode)
# TODO: Change back to main-only when ready for production: github.ref == 'refs/heads/main'
if: github.event_name == 'push'
permissions:
contents: read
+4
View File
@@ -27,6 +27,10 @@ COPY lyrics_transcriber_temp /app/lyrics_transcriber_temp
RUN pip install --no-cache-dir --upgrade pip && \
pip install --no-cache-dir -e .
# Download spaCy language model for lyrics transcription
# This must be done at build time, not runtime (Cloud Run network restrictions)
RUN python -m spacy download en_core_web_sm
# Label with build info
ARG BUILD_DATE
ARG BUILD_ID
+587 -2
View File
@@ -1,12 +1,25 @@
"""
File upload route for local file submission with style configuration support.
Supports two upload flows:
1. Direct upload (original): All files sent as multipart form data to /api/jobs/upload
- Simple but limited by Cloud Run's 32MB request body size
2. Signed URL upload (recommended for large files):
- POST /api/jobs/create-with-upload-urls - Creates job, returns signed GCS upload URLs
- Client uploads files directly to GCS using signed URLs (no size limit)
- POST /api/jobs/{job_id}/uploads-complete - Validates uploads, triggers workers
"""
import asyncio
import json
import logging
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Request
import tempfile
import os
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Request, Body
from pathlib import Path
from typing import Optional, List, Dict, Any
from typing import Optional, List, Dict, Any, Tuple
from pydantic import BaseModel, Field
from backend.models.job import JobCreate, JobStatus
from backend.services.job_manager import JobManager
@@ -19,6 +32,79 @@ from backend.version import VERSION
logger = logging.getLogger(__name__)
router = APIRouter(tags=["jobs"])
# ============================================================================
# Pydantic models for signed URL upload flow
# ============================================================================
class FileUploadRequest(BaseModel):
"""Information about a file to be uploaded."""
filename: str = Field(..., description="Original filename with extension")
content_type: str = Field(..., description="MIME type of the file")
file_type: str = Field(..., description="Type of file: 'audio', 'style_params', 'style_intro_background', 'style_karaoke_background', 'style_end_background', 'style_font', 'style_cdg_instrumental_background', 'style_cdg_title_background', 'style_cdg_outro_background', 'lyrics_file'")
class CreateJobWithUploadUrlsRequest(BaseModel):
"""Request to create a job and get signed upload URLs."""
# Required fields
artist: str = Field(..., description="Artist name")
title: str = Field(..., description="Song title")
files: List[FileUploadRequest] = Field(..., description="List of files to upload")
# Processing options
enable_cdg: bool = Field(True, description="Generate CDG+MP3 package")
enable_txt: bool = Field(True, description="Generate TXT+MP3 package")
# Finalisation options
brand_prefix: Optional[str] = Field(None, description="Brand code prefix (e.g., NOMAD)")
enable_youtube_upload: bool = Field(False, description="Upload to YouTube")
youtube_description: Optional[str] = Field(None, description="YouTube video description text")
discord_webhook_url: Optional[str] = Field(None, description="Discord webhook URL for notifications")
webhook_url: Optional[str] = Field(None, description="Generic webhook URL")
user_email: Optional[str] = Field(None, description="User email for notifications")
# Distribution options (native API - preferred for remote CLI)
dropbox_path: Optional[str] = Field(None, description="Dropbox folder path for organized output")
gdrive_folder_id: Optional[str] = Field(None, description="Google Drive folder ID for public share uploads")
# Legacy distribution options (rclone - deprecated)
organised_dir_rclone_root: Optional[str] = Field(None, description="[Deprecated] rclone remote path")
# Lyrics configuration
lyrics_artist: Optional[str] = Field(None, description="Override artist name for lyrics search")
lyrics_title: Optional[str] = Field(None, description="Override title for lyrics search")
subtitle_offset_ms: int = Field(0, description="Subtitle timing offset in milliseconds")
# Audio separation model configuration
clean_instrumental_model: Optional[str] = Field(None, description="Model for clean instrumental separation")
backing_vocals_models: Optional[List[str]] = Field(None, description="Models for backing vocals separation")
other_stems_models: Optional[List[str]] = Field(None, description="Models for other stems")
# Existing instrumental configuration (Batch 3)
existing_instrumental: bool = Field(False, description="Whether an existing instrumental file is being uploaded")
class SignedUploadUrl(BaseModel):
"""Signed URL for uploading a file."""
file_type: str = Field(..., description="Type of file this URL is for")
gcs_path: str = Field(..., description="The GCS path where file will be stored")
upload_url: str = Field(..., description="Signed URL to PUT the file to")
content_type: str = Field(..., description="Content-Type header to use when uploading")
class CreateJobWithUploadUrlsResponse(BaseModel):
"""Response from creating a job with upload URLs."""
status: str
job_id: str
message: str
upload_urls: List[SignedUploadUrl]
server_version: str
class UploadsCompleteRequest(BaseModel):
"""Request to mark uploads as complete and start processing."""
uploaded_files: List[str] = Field(..., description="List of file_types that were successfully uploaded")
# Initialize services
job_manager = JobManager()
storage_service = StorageService()
@@ -126,6 +212,15 @@ async def upload_and_create_job(
gdrive_folder_id: Optional[str] = Form(None, description="Google Drive folder ID for public share uploads"),
# Legacy distribution options (rclone - deprecated)
organised_dir_rclone_root: Optional[str] = Form(None, description="[Deprecated] rclone remote path for Dropbox upload"),
# Lyrics configuration (overrides for search/transcription)
lyrics_artist: Optional[str] = Form(None, description="Override artist name for lyrics search"),
lyrics_title: Optional[str] = Form(None, description="Override title for lyrics search"),
lyrics_file: Optional[UploadFile] = File(None, description="User-provided lyrics file (TXT, DOCX, RTF)"),
subtitle_offset_ms: int = Form(0, description="Subtitle timing offset in milliseconds (positive = delay)"),
# Audio separation model configuration
clean_instrumental_model: Optional[str] = Form(None, description="Model for clean instrumental separation (e.g., model_bs_roformer_ep_317_sdr_12.9755.ckpt)"),
backing_vocals_models: Optional[str] = Form(None, description="Comma-separated list of models for backing vocals separation"),
other_stems_models: Optional[str] = Form(None, description="Comma-separated list of models for other stems (bass, drums, guitar, etc.)"),
):
"""
Upload an audio file and create a karaoke generation job with full style configuration.
@@ -182,6 +277,16 @@ async def upload_and_create_job(
detail=f"Invalid font file type '{ext}'. Allowed: {', '.join(ALLOWED_FONT_EXTENSIONS)}"
)
# Validate lyrics file if provided
ALLOWED_LYRICS_EXTENSIONS = {'.txt', '.docx', '.rtf'}
if lyrics_file:
ext = Path(lyrics_file.filename).suffix.lower()
if ext not in ALLOWED_LYRICS_EXTENSIONS:
raise HTTPException(
status_code=400,
detail=f"Invalid lyrics file type '{ext}'. Allowed: {', '.join(ALLOWED_LYRICS_EXTENSIONS)}"
)
# Apply default distribution settings from environment if not provided
settings = get_settings()
effective_dropbox_path = dropbox_path or settings.default_dropbox_path
@@ -229,6 +334,15 @@ async def upload_and_create_job(
# Extract request metadata for tracking and filtering
request_metadata = extract_request_metadata(request, created_from="upload")
# Parse comma-separated model lists into arrays
parsed_backing_vocals_models = None
if backing_vocals_models:
parsed_backing_vocals_models = [m.strip() for m in backing_vocals_models.split(',') if m.strip()]
parsed_other_stems_models = None
if other_stems_models:
parsed_other_stems_models = [m.strip() for m in other_stems_models.split(',') if m.strip()]
# Create job first to get job_id
job_create = JobCreate(
artist=artist,
@@ -247,6 +361,14 @@ async def upload_and_create_job(
gdrive_folder_id=effective_gdrive_folder_id,
# Legacy rclone distribution (deprecated)
organised_dir_rclone_root=organised_dir_rclone_root,
# Lyrics configuration (overrides for search/transcription)
lyrics_artist=lyrics_artist,
lyrics_title=lyrics_title,
subtitle_offset_ms=subtitle_offset_ms,
# Audio separation model configuration
clean_instrumental_model=clean_instrumental_model,
backing_vocals_models=parsed_backing_vocals_models,
other_stems_models=parsed_other_stems_models,
# Request metadata for tracking and filtering
request_metadata=request_metadata,
)
@@ -308,6 +430,17 @@ async def upload_and_create_job(
)
style_assets['font'] = font_gcs_path
# Upload lyrics file if provided
lyrics_file_gcs_path = None
if lyrics_file:
lyrics_file_gcs_path = f"uploads/{job_id}/lyrics/user_lyrics{Path(lyrics_file.filename).suffix.lower()}"
logger.info(f"Uploading user lyrics file to GCS: {lyrics_file_gcs_path}")
storage_service.upload_fileobj(
lyrics_file.file,
lyrics_file_gcs_path,
content_type='text/plain'
)
# Update job with all GCS paths
update_data = {
'input_media_gcs_path': audio_gcs_path,
@@ -338,6 +471,24 @@ async def upload_and_create_job(
if organised_dir_rclone_root:
update_data['organised_dir_rclone_root'] = organised_dir_rclone_root
# Lyrics configuration
if lyrics_artist:
update_data['lyrics_artist'] = lyrics_artist
if lyrics_title:
update_data['lyrics_title'] = lyrics_title
if lyrics_file_gcs_path:
update_data['lyrics_file_gcs_path'] = lyrics_file_gcs_path
if subtitle_offset_ms != 0:
update_data['subtitle_offset_ms'] = subtitle_offset_ms
# Audio separation model configuration
if clean_instrumental_model:
update_data['clean_instrumental_model'] = clean_instrumental_model
if parsed_backing_vocals_models:
update_data['backing_vocals_models'] = parsed_backing_vocals_models
if parsed_other_stems_models:
update_data['other_stems_models'] = parsed_other_stems_models
job_manager.update_job(job_id, update_data)
# Verify the update
@@ -417,3 +568,437 @@ async def upload_and_create_job(
except Exception as e:
logger.error(f"Error uploading files: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e)) from e
# ============================================================================
# Signed URL Upload Flow - For large files that exceed Cloud Run's 32MB limit
# ============================================================================
# Valid file types and their expected extensions
VALID_FILE_TYPES = {
'audio': ALLOWED_AUDIO_EXTENSIONS,
'style_params': {'.json'},
'style_intro_background': ALLOWED_IMAGE_EXTENSIONS,
'style_karaoke_background': ALLOWED_IMAGE_EXTENSIONS,
'style_end_background': ALLOWED_IMAGE_EXTENSIONS,
'style_font': ALLOWED_FONT_EXTENSIONS,
'style_cdg_instrumental_background': ALLOWED_IMAGE_EXTENSIONS,
'style_cdg_title_background': ALLOWED_IMAGE_EXTENSIONS,
'style_cdg_outro_background': ALLOWED_IMAGE_EXTENSIONS,
'lyrics_file': {'.txt', '.docx', '.rtf'},
'existing_instrumental': ALLOWED_AUDIO_EXTENSIONS, # Batch 3: user-provided instrumental
}
async def _validate_audio_durations(
storage: StorageService,
audio_gcs_path: str,
instrumental_gcs_path: str,
tolerance_seconds: float = 0.5
) -> Tuple[bool, float, float]:
"""
Validate that audio and instrumental files have matching durations.
Downloads both files to temp directory and checks their durations using pydub.
Args:
storage: StorageService instance
audio_gcs_path: GCS path to main audio file
instrumental_gcs_path: GCS path to instrumental file
tolerance_seconds: Maximum allowed difference in seconds (default 0.5s)
Returns:
Tuple of (is_valid, audio_duration, instrumental_duration)
"""
from pydub import AudioSegment
temp_dir = tempfile.mkdtemp(prefix="duration_check_")
try:
# Download audio file
audio_local = os.path.join(temp_dir, "audio" + Path(audio_gcs_path).suffix)
storage.download_file(audio_gcs_path, audio_local)
# Download instrumental file
instrumental_local = os.path.join(temp_dir, "instrumental" + Path(instrumental_gcs_path).suffix)
storage.download_file(instrumental_gcs_path, instrumental_local)
# Get durations using pydub (returns milliseconds)
audio_segment = AudioSegment.from_file(audio_local)
audio_duration = len(audio_segment) / 1000.0 # Convert to seconds
instrumental_segment = AudioSegment.from_file(instrumental_local)
instrumental_duration = len(instrumental_segment) / 1000.0 # Convert to seconds
# Check if durations are within tolerance
difference = abs(audio_duration - instrumental_duration)
is_valid = difference <= tolerance_seconds
return is_valid, audio_duration, instrumental_duration
finally:
# Clean up temp files
import shutil
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
def _get_gcs_path_for_file(job_id: str, file_type: str, filename: str) -> str:
"""Generate the GCS path for a file based on its type."""
ext = Path(filename).suffix.lower()
if file_type == 'audio':
return f"uploads/{job_id}/audio/{filename}"
elif file_type == 'style_params':
return f"uploads/{job_id}/style/style_params.json"
elif file_type.startswith('style_'):
# Map style_intro_background -> intro_background, etc.
asset_key = file_type.replace('style_', '')
return f"uploads/{job_id}/style/{asset_key}{ext}"
elif file_type == 'lyrics_file':
return f"uploads/{job_id}/lyrics/user_lyrics{ext}"
elif file_type == 'existing_instrumental':
# Batch 3: user-provided instrumental file
return f"uploads/{job_id}/audio/existing_instrumental{ext}"
else:
return f"uploads/{job_id}/other/{filename}"
@router.post("/jobs/create-with-upload-urls", response_model=CreateJobWithUploadUrlsResponse)
async def create_job_with_upload_urls(
request: Request,
body: CreateJobWithUploadUrlsRequest,
):
"""
Create a karaoke generation job and return signed URLs for direct file upload to GCS.
This is the first step of the two-step upload flow for large files:
1. Call this endpoint with job metadata and list of files to upload
2. Upload each file directly to GCS using the returned signed URLs
3. Call POST /api/jobs/{job_id}/uploads-complete to start processing
Benefits of this flow:
- No file size limits (GCS supports up to 5TB)
- Faster uploads (direct to storage, no proxy)
- Works with any HTTP client (no HTTP/2 required)
- Resumable uploads possible with GCS
"""
try:
# Validate files list
if not body.files:
raise HTTPException(status_code=400, detail="At least one file is required")
# Check that audio file is included
audio_files = [f for f in body.files if f.file_type == 'audio']
if not audio_files:
raise HTTPException(status_code=400, detail="An audio file is required")
if len(audio_files) > 1:
raise HTTPException(status_code=400, detail="Only one audio file is allowed")
# Validate file types and extensions
for file_info in body.files:
if file_info.file_type not in VALID_FILE_TYPES:
raise HTTPException(
status_code=400,
detail=f"Invalid file_type: '{file_info.file_type}'. Valid types: {list(VALID_FILE_TYPES.keys())}"
)
ext = Path(file_info.filename).suffix.lower()
allowed_extensions = VALID_FILE_TYPES[file_info.file_type]
if ext not in allowed_extensions:
raise HTTPException(
status_code=400,
detail=f"Invalid file extension '{ext}' for file_type '{file_info.file_type}'. Allowed: {allowed_extensions}"
)
# Apply default distribution settings from environment if not provided
settings = get_settings()
effective_dropbox_path = body.dropbox_path or settings.default_dropbox_path
effective_gdrive_folder_id = body.gdrive_folder_id or settings.default_gdrive_folder_id
effective_discord_webhook_url = body.discord_webhook_url or settings.default_discord_webhook_url
# Validate credentials for requested distribution services
invalid_services = []
credential_manager = get_credential_manager()
if body.enable_youtube_upload:
result = credential_manager.check_youtube_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"youtube ({result.message})")
if effective_dropbox_path:
result = credential_manager.check_dropbox_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"dropbox ({result.message})")
if effective_gdrive_folder_id:
result = credential_manager.check_gdrive_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"gdrive ({result.message})")
if invalid_services:
raise HTTPException(
status_code=400,
detail={
"error": "credentials_invalid",
"message": f"The following distribution services need re-authorization: {', '.join(invalid_services)}",
"invalid_services": invalid_services,
"auth_url": "/api/auth/status"
}
)
# Extract request metadata for tracking
request_metadata = extract_request_metadata(request, created_from="signed_url_upload")
# Get original audio filename
audio_file = audio_files[0]
# Create job
job_create = JobCreate(
artist=body.artist,
title=body.title,
filename=audio_file.filename,
enable_cdg=body.enable_cdg,
enable_txt=body.enable_txt,
brand_prefix=body.brand_prefix,
enable_youtube_upload=body.enable_youtube_upload,
youtube_description=body.youtube_description,
discord_webhook_url=effective_discord_webhook_url,
webhook_url=body.webhook_url,
user_email=body.user_email,
dropbox_path=effective_dropbox_path,
gdrive_folder_id=effective_gdrive_folder_id,
organised_dir_rclone_root=body.organised_dir_rclone_root,
lyrics_artist=body.lyrics_artist,
lyrics_title=body.lyrics_title,
subtitle_offset_ms=body.subtitle_offset_ms,
clean_instrumental_model=body.clean_instrumental_model,
backing_vocals_models=body.backing_vocals_models,
other_stems_models=body.other_stems_models,
request_metadata=request_metadata,
)
job = job_manager.create_job(job_create)
job_id = job.job_id
logger.info(f"Created job {job_id} for {body.artist} - {body.title} (signed URL upload flow)")
# Generate signed upload URLs for each file
upload_urls = []
for file_info in body.files:
gcs_path = _get_gcs_path_for_file(job_id, file_info.file_type, file_info.filename)
# Generate signed upload URL (valid for 60 minutes)
signed_url = storage_service.generate_signed_upload_url(
gcs_path,
content_type=file_info.content_type,
expiration_minutes=60
)
upload_urls.append(SignedUploadUrl(
file_type=file_info.file_type,
gcs_path=gcs_path,
upload_url=signed_url,
content_type=file_info.content_type
))
logger.info(f"Generated signed upload URL for {file_info.file_type}: {gcs_path}")
return CreateJobWithUploadUrlsResponse(
status="success",
job_id=job_id,
message="Job created. Upload files to the provided URLs, then call /api/jobs/{job_id}/uploads-complete",
upload_urls=upload_urls,
server_version=VERSION
)
except HTTPException:
raise
except Exception as e:
logger.error(f"Error creating job with upload URLs: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e)) from e
@router.post("/jobs/{job_id}/uploads-complete")
async def mark_uploads_complete(
job_id: str,
background_tasks: BackgroundTasks,
body: UploadsCompleteRequest,
):
"""
Mark file uploads as complete and start job processing.
This is the second step of the signed URL upload flow:
1. Create job with POST /api/jobs/create-with-upload-urls
2. Upload files directly to GCS using signed URLs
3. Call this endpoint to validate uploads and start processing
The endpoint will:
- Verify the job exists and is in PENDING state
- Validate that required files (audio) were uploaded
- Update job with GCS paths
- Trigger audio and lyrics workers
"""
try:
# Get job and verify it exists
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
# Verify job is in pending state
if job.status != JobStatus.PENDING:
raise HTTPException(
status_code=400,
detail=f"Job {job_id} is not in pending state (current: {job.status}). Cannot complete uploads."
)
# Validate required files
if 'audio' not in body.uploaded_files:
raise HTTPException(status_code=400, detail="Audio file upload is required")
# Build GCS paths for uploaded files and validate they exist
update_data = {}
style_assets = {}
for file_type in body.uploaded_files:
if file_type not in VALID_FILE_TYPES:
logger.warning(f"Unknown file_type in uploaded_files: {file_type}")
continue
# Determine the GCS path - we need to find the actual file
prefix = f"uploads/{job_id}/"
if file_type == 'audio':
prefix = f"uploads/{job_id}/audio/"
elif file_type == 'style_params':
prefix = f"uploads/{job_id}/style/style_params"
elif file_type.startswith('style_'):
asset_key = file_type.replace('style_', '')
prefix = f"uploads/{job_id}/style/{asset_key}"
elif file_type == 'lyrics_file':
prefix = f"uploads/{job_id}/lyrics/user_lyrics"
elif file_type == 'existing_instrumental':
prefix = f"uploads/{job_id}/audio/existing_instrumental"
# List files with this prefix to find the actual uploaded file
files = storage_service.list_files(prefix)
if not files:
raise HTTPException(
status_code=400,
detail=f"File for '{file_type}' was not uploaded to GCS. Expected prefix: {prefix}"
)
# Use the first (and should be only) file found
gcs_path = files[0]
# Update appropriate field based on file type
if file_type == 'audio':
update_data['input_media_gcs_path'] = gcs_path
update_data['filename'] = Path(gcs_path).name
elif file_type == 'style_params':
update_data['style_params_gcs_path'] = gcs_path
style_assets['style_params'] = gcs_path
elif file_type.startswith('style_'):
asset_key = file_type.replace('style_', '')
style_assets[asset_key] = gcs_path
elif file_type == 'lyrics_file':
update_data['lyrics_file_gcs_path'] = gcs_path
elif file_type == 'existing_instrumental':
update_data['existing_instrumental_gcs_path'] = gcs_path
# Validate existing instrumental duration if provided (Batch 3)
audio_gcs_path = update_data.get('input_media_gcs_path')
instrumental_gcs_path = update_data.get('existing_instrumental_gcs_path')
if audio_gcs_path and instrumental_gcs_path:
logger.info(f"Validating instrumental duration for job {job_id}")
try:
duration_valid, audio_duration, instrumental_duration = await _validate_audio_durations(
storage_service, audio_gcs_path, instrumental_gcs_path
)
if not duration_valid:
raise HTTPException(
status_code=400,
detail={
"error": "duration_mismatch",
"message": f"Instrumental duration ({instrumental_duration:.2f}s) does not match audio duration ({audio_duration:.2f}s). "
f"Difference must be within 0.5 seconds.",
"audio_duration": audio_duration,
"instrumental_duration": instrumental_duration,
"difference": abs(audio_duration - instrumental_duration),
}
)
logger.info(f"Duration validation passed: audio={audio_duration:.2f}s, instrumental={instrumental_duration:.2f}s")
except HTTPException:
raise
except Exception as e:
logger.warning(f"Duration validation failed with error: {e}. Proceeding without validation.")
# Don't block the job if we can't validate - the video worker will fail more gracefully
# Add style assets to update if any
if style_assets:
update_data['style_assets'] = style_assets
# Update job with GCS paths
job_manager.update_job(job_id, update_data)
logger.info(f"Validated uploads for job {job_id}: {body.uploaded_files}")
# Transition job to DOWNLOADING state
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.DOWNLOADING,
progress=5,
message="Files uploaded, preparing to process"
)
# Trigger workers in parallel
background_tasks.add_task(_trigger_workers_parallel, job_id)
# Get distribution services info for response
credential_manager = get_credential_manager()
distribution_services: Dict[str, Any] = {}
# Get fresh job data
updated_job = job_manager.get_job(job_id)
if updated_job.dropbox_path:
dropbox_result = credential_manager.check_dropbox_credentials()
distribution_services["dropbox"] = {
"enabled": True,
"path": updated_job.dropbox_path,
"credentials_valid": dropbox_result.status == CredentialStatus.VALID,
}
if updated_job.gdrive_folder_id:
gdrive_result = credential_manager.check_gdrive_credentials()
distribution_services["gdrive"] = {
"enabled": True,
"folder_id": updated_job.gdrive_folder_id,
"credentials_valid": gdrive_result.status == CredentialStatus.VALID,
}
if updated_job.enable_youtube_upload:
youtube_result = credential_manager.check_youtube_credentials()
distribution_services["youtube"] = {
"enabled": True,
"credentials_valid": youtube_result.status == CredentialStatus.VALID,
}
if updated_job.discord_webhook_url:
distribution_services["discord"] = {
"enabled": True,
}
return {
"status": "success",
"job_id": job_id,
"message": "Uploads validated. Processing started.",
"files_validated": body.uploaded_files,
"style_assets": list(style_assets.keys()) if style_assets else [],
"server_version": VERSION,
"distribution_services": distribution_services,
}
except HTTPException:
raise
except Exception as e:
logger.error(f"Error completing uploads for job {job_id}: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e)) from e
+153
View File
@@ -722,6 +722,159 @@ async def cancel_job(job_id: str, request: CancelJobRequest) -> dict:
}
@router.post("/{job_id}/retry")
async def retry_job(
job_id: str,
background_tasks: BackgroundTasks
) -> dict:
"""
Retry a failed job from the last successful checkpoint.
This endpoint allows resuming jobs that failed during:
- Video generation (re-runs video worker)
- Encoding (re-runs video worker)
- Packaging (re-runs video worker)
The retry logic determines the appropriate stage to resume from
based on what files/state already exist.
"""
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
if job.status != JobStatus.FAILED:
raise HTTPException(
status_code=400,
detail=f"Only failed jobs can be retried (current status: {job.status})"
)
try:
# Determine retry point based on what's already complete
error_details = job.error_details or {}
error_stage = error_details.get('stage', 'unknown')
logger.info(f"Job {job_id}: Retrying from failed stage '{error_stage}'")
# Check what state exists to determine retry point
file_urls = job.file_urls or {}
state_data = job.state_data or {}
# If we have a video with vocals and instrumental selection, retry video generation
if (file_urls.get('videos', {}).get('with_vocals') and
state_data.get('instrumental_selection')):
logger.info(f"Job {job_id}: Has rendered video and instrumental selection, retrying video generation")
# Clear error state
job_manager.update_job(job_id, {
'error_message': None,
'error_details': None,
})
# Reset to INSTRUMENTAL_SELECTED and trigger video worker
if not job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.INSTRUMENTAL_SELECTED,
progress=65,
message=f"Retrying video generation from failed state"
):
raise HTTPException(
status_code=500,
detail="Failed to transition job status for retry"
)
# Trigger video generation worker
background_tasks.add_task(worker_service.trigger_video_worker, job_id)
return {
"status": "success",
"job_status": "instrumental_selected",
"message": "Job retry started from video generation stage",
"retry_stage": "video_generation"
}
# If we have corrections and screens but no video, retry render
elif (file_urls.get('lyrics', {}).get('corrections') and
file_urls.get('screens', {}).get('title')):
logger.info(f"Job {job_id}: Has corrections and screens, retrying from render stage")
# Clear error state
job_manager.update_job(job_id, {
'error_message': None,
'error_details': None,
})
# Reset to REVIEW_COMPLETE and trigger render worker
if not job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.REVIEW_COMPLETE,
progress=70,
message=f"Retrying video render from failed state"
):
raise HTTPException(
status_code=500,
detail="Failed to transition job status for retry"
)
# Trigger render video worker
background_tasks.add_task(worker_service.trigger_render_video_worker, job_id)
return {
"status": "success",
"job_status": "review_complete",
"message": "Job retry started from render stage",
"retry_stage": "render_video"
}
# If we have stems and corrections, retry from screens generation
elif (file_urls.get('stems', {}).get('instrumental_clean') and
file_urls.get('lyrics', {}).get('corrections')):
logger.info(f"Job {job_id}: Has stems and corrections, retrying from screens stage")
# Clear error state
job_manager.update_job(job_id, {
'error_message': None,
'error_details': None,
})
# Reset to a state before screens and trigger screens worker
if not job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.LYRICS_COMPLETE,
progress=45,
message=f"Retrying from screens generation"
):
raise HTTPException(
status_code=500,
detail="Failed to transition job status for retry"
)
# Trigger screens worker
background_tasks.add_task(worker_service.trigger_screens_worker, job_id)
return {
"status": "success",
"job_status": "lyrics_complete",
"message": "Job retry started from screens generation",
"retry_stage": "screens_generation"
}
else:
# Can't determine a safe retry point, need to restart from beginning
raise HTTPException(
status_code=400,
detail="Cannot determine safe retry point. Job may need to be resubmitted."
)
except HTTPException:
raise
except Exception as e:
logger.error(f"Error retrying job {job_id}: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
@router.get("/{job_id}/logs")
async def get_worker_logs(
job_id: str,
+6 -2
View File
@@ -47,7 +47,10 @@ class Settings(BaseSettings):
# Default distribution settings (can be overridden per-request)
default_dropbox_path: Optional[str] = os.getenv("DEFAULT_DROPBOX_PATH")
default_gdrive_folder_id: Optional[str] = os.getenv("DEFAULT_GDRIVE_FOLDER_ID")
default_discord_webhook_url: Optional[str] = os.getenv("DEFAULT_DISCORD_WEBHOOK_URL")
# Strip whitespace/newlines from webhook URL - common issue when env vars are set with trailing newlines
default_discord_webhook_url: Optional[str] = (
os.getenv("DEFAULT_DISCORD_WEBHOOK_URL", "").strip() or None
)
# Secret Manager cache
_secret_cache: Dict[str, str] = {}
@@ -90,7 +93,8 @@ class Settings(BaseSettings):
client = secretmanager.SecretManagerServiceClient()
name = f"projects/{self.google_cloud_project}/secrets/{secret_id}/versions/latest"
response = client.access_secret_version(request={"name": name})
secret_value = response.payload.data.decode('UTF-8')
# Strip whitespace/newlines - common issue when secrets are created with trailing newlines
secret_value = response.payload.data.decode('UTF-8').strip()
# Cache it
self._secret_cache[secret_id] = secret_value
+35 -2
View File
@@ -120,9 +120,14 @@ STATE_TRANSITIONS = {
JobStatus.UPLOADING: [JobStatus.NOTIFYING, JobStatus.COMPLETE, JobStatus.FAILED],
JobStatus.NOTIFYING: [JobStatus.COMPLETE, JobStatus.FAILED],
# Terminal states have no transitions
# Terminal states - COMPLETE and CANCELLED have no transitions
# FAILED allows retry transitions to resume from checkpoints
JobStatus.COMPLETE: [],
JobStatus.FAILED: [],
JobStatus.FAILED: [
JobStatus.INSTRUMENTAL_SELECTED, # Retry from video generation
JobStatus.REVIEW_COMPLETE, # Retry from render stage
JobStatus.LYRICS_COMPLETE, # Retry from screens generation
],
JobStatus.CANCELLED: [],
# Legacy states (for backward compatibility)
@@ -206,6 +211,20 @@ class Job(BaseModel):
# Legacy distribution configuration (rclone - for local CLI backward compat)
organised_dir_rclone_root: Optional[str] = None # Deprecated: use dropbox_path instead
# Lyrics configuration (overrides for search/transcription)
lyrics_artist: Optional[str] = None # Override artist name for lyrics search
lyrics_title: Optional[str] = None # Override title for lyrics search
lyrics_file_gcs_path: Optional[str] = None # GCS path to user-provided lyrics file
subtitle_offset_ms: int = 0 # Offset for subtitle timing (positive = delay)
# Audio separation model configuration
clean_instrumental_model: Optional[str] = None # Model for clean instrumental separation
backing_vocals_models: Optional[List[str]] = None # Models for backing vocals separation
other_stems_models: Optional[List[str]] = None # Models for other stems (bass, drums, etc.)
# Existing instrumental configuration (Batch 3)
existing_instrumental_gcs_path: Optional[str] = None # GCS path to user-provided instrumental file
# Processing state
track_output_dir: Optional[str] = None # Local output directory (temp)
audio_hash: Optional[str] = None # Hash for deduplication
@@ -368,6 +387,20 @@ class JobCreate(BaseModel):
# Legacy (rclone - deprecated, use dropbox_path instead)
organised_dir_rclone_root: Optional[str] = None
# Lyrics configuration (overrides for search/transcription)
lyrics_artist: Optional[str] = None # Override artist name for lyrics search
lyrics_title: Optional[str] = None # Override title for lyrics search
lyrics_file_gcs_path: Optional[str] = None # GCS path to user-provided lyrics file
subtitle_offset_ms: int = 0 # Offset for subtitle timing (positive = delay)
# Audio separation model configuration
clean_instrumental_model: Optional[str] = None # Model for clean instrumental separation
backing_vocals_models: Optional[List[str]] = None # Models for backing vocals separation
other_stems_models: Optional[List[str]] = None # Models for other stems (bass, drums, etc.)
# Existing instrumental configuration (Batch 3)
existing_instrumental_gcs_path: Optional[str] = None # GCS path to user-provided instrumental file
# Request metadata (set by API endpoint from request headers)
request_metadata: Dict[str, Any] = Field(default_factory=dict)
"""
+4 -5
View File
@@ -138,7 +138,7 @@ def job_log_context(
Args:
job_id: Job ID to associate logs with
worker: Worker name for log categorization
logger_names: List of logger names to capture (None = capture root + common loggers)
logger_names: List of logger names to capture (None = capture common loggers)
min_level: Minimum log level to capture
Usage:
@@ -147,14 +147,13 @@ def job_log_context(
correction_operations.add_lyrics_source(...)
"""
# Default loggers to capture - these cover most of our processing
# Note: We intentionally DON'T include the root logger ('') to avoid
# duplicate log entries since logs propagate up the logger hierarchy.
# Only capture at the top-level package loggers.
if logger_names is None:
logger_names = [
'', # Root logger
'backend.api.routes.review',
'lyrics_transcriber',
'lyrics_transcriber.correction',
'lyrics_transcriber.correction.anchor_sequence',
'lyrics_transcriber.correction.corrector',
'karaoke_gen',
]
+37 -16
View File
@@ -65,6 +65,26 @@ class StorageService:
a private key available. Requires the service account to have
roles/iam.serviceAccountTokenCreator on itself.
"""
return self._generate_signed_url_internal(blob_path, "GET", expiration_minutes)
def generate_signed_upload_url(self, blob_path: str, content_type: str = "application/octet-stream", expiration_minutes: int = 60) -> str:
"""Generate a signed URL for uploading a file directly to GCS.
This allows clients to upload files directly to GCS without going through
the backend, bypassing any request body size limits.
Args:
blob_path: The destination path in GCS
content_type: The expected content type of the upload
expiration_minutes: How long the URL is valid for
Returns:
A signed URL that accepts PUT requests with the file content
"""
return self._generate_signed_url_internal(blob_path, "PUT", expiration_minutes, content_type)
def _generate_signed_url_internal(self, blob_path: str, method: str, expiration_minutes: int = 60, content_type: Optional[str] = None) -> str:
"""Internal method to generate signed URLs for GET or PUT operations."""
import google.auth
from google.auth.transport import requests
@@ -74,6 +94,17 @@ class StorageService:
# Get default credentials and refresh to ensure we have a valid token
credentials, project = google.auth.default()
# Common kwargs for signed URL generation
kwargs = {
"version": "v4",
"expiration": timedelta(minutes=expiration_minutes),
"method": method,
}
# For PUT requests, we need to specify the content type in headers
if method == "PUT" and content_type:
kwargs["headers"] = {"Content-Type": content_type}
# Check if we're using compute credentials (Cloud Run/GCE)
# These need to use IAM signBlob via service_account_email + access_token
if hasattr(credentials, 'service_account_email'):
@@ -81,25 +112,15 @@ class StorageService:
auth_request = requests.Request()
credentials.refresh(auth_request)
url = blob.generate_signed_url(
version="v4",
expiration=timedelta(minutes=expiration_minutes),
method="GET",
service_account_email=credentials.service_account_email,
access_token=credentials.token
)
else:
# Local development with service account key or user credentials
url = blob.generate_signed_url(
version="v4",
expiration=timedelta(minutes=expiration_minutes),
method="GET"
)
kwargs["service_account_email"] = credentials.service_account_email
kwargs["access_token"] = credentials.token
logger.info(f"Generated signed URL for {blob_path}")
url = blob.generate_signed_url(**kwargs)
logger.info(f"Generated signed {method} URL for {blob_path}")
return url
except Exception as e:
logger.error(f"Error generating signed URL for {blob_path}: {e}")
logger.error(f"Error generating signed {method} URL for {blob_path}: {e}")
raise
def delete_file(self, blob_path: str) -> None:
+693
View File
@@ -266,6 +266,699 @@ class TestJobModelFieldPresence:
assert job_dict["input_media_gcs_path"] == "uploads/test123/file.flac"
class TestLyricsFileValidation:
"""Test lyrics file upload validation."""
@pytest.mark.parametrize("filename,expected_valid", [
("lyrics.txt", True),
("lyrics.docx", True),
("lyrics.rtf", True),
("lyrics.pdf", False),
("lyrics.mp3", False),
("lyrics", False),
])
def test_lyrics_file_extension_validation(self, filename, expected_valid):
"""Test that only valid lyrics file extensions are accepted."""
from pathlib import Path
allowed_extensions = {'.txt', '.docx', '.rtf'}
file_ext = Path(filename).suffix.lower()
is_valid = file_ext in allowed_extensions
assert is_valid == expected_valid
class TestLyricsConfigurationFields:
"""Test that lyrics configuration fields are handled correctly."""
def test_job_has_lyrics_artist_field(self):
"""Test that Job model has lyrics_artist field."""
from backend.models.job import Job
from datetime import datetime
job = Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
lyrics_artist="Override Artist"
)
assert hasattr(job, 'lyrics_artist')
assert job.lyrics_artist == "Override Artist"
def test_job_has_lyrics_title_field(self):
"""Test that Job model has lyrics_title field."""
from backend.models.job import Job
from datetime import datetime
job = Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
lyrics_title="Override Title"
)
assert hasattr(job, 'lyrics_title')
assert job.lyrics_title == "Override Title"
def test_job_has_lyrics_file_gcs_path_field(self):
"""Test that Job model has lyrics_file_gcs_path field."""
from backend.models.job import Job
from datetime import datetime
job = Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
lyrics_file_gcs_path="uploads/test123/lyrics/user_lyrics.txt"
)
assert hasattr(job, 'lyrics_file_gcs_path')
assert job.lyrics_file_gcs_path == "uploads/test123/lyrics/user_lyrics.txt"
def test_job_has_subtitle_offset_ms_field(self):
"""Test that Job model has subtitle_offset_ms field."""
from backend.models.job import Job
from datetime import datetime
job = Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
subtitle_offset_ms=500
)
assert hasattr(job, 'subtitle_offset_ms')
assert job.subtitle_offset_ms == 500
def test_subtitle_offset_default_is_zero(self):
"""Test that subtitle_offset_ms defaults to 0."""
from backend.models.job import Job
from datetime import datetime
job = Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.utcnow(),
updated_at=datetime.utcnow()
)
assert job.subtitle_offset_ms == 0
class TestLyricsGCSPathGeneration:
"""Test lyrics file GCS path generation."""
def test_lyrics_gcs_path_format(self):
"""Test that lyrics GCS paths follow expected format."""
job_id = "test123"
filename = "user_lyrics.txt"
expected_path = f"uploads/{job_id}/lyrics/{filename}"
assert expected_path == "uploads/test123/lyrics/user_lyrics.txt"
def test_lyrics_gcs_path_preserves_extension(self):
"""Test that lyrics file extension is preserved."""
job_id = "test123"
for ext in ['.txt', '.docx', '.rtf']:
filename = f"user_lyrics{ext}"
gcs_path = f"uploads/{job_id}/lyrics/{filename}"
assert gcs_path.endswith(ext)
class TestJobCreateLyricsFields:
"""Test that JobCreate model supports lyrics fields."""
def test_job_create_has_lyrics_fields(self):
"""Test that JobCreate model has all lyrics configuration fields."""
from backend.models.job import JobCreate
job_create = JobCreate(
artist="Artist",
title="Title",
lyrics_artist="Override Artist",
lyrics_title="Override Title",
lyrics_file_gcs_path="uploads/test/lyrics/file.txt",
subtitle_offset_ms=250
)
assert job_create.lyrics_artist == "Override Artist"
assert job_create.lyrics_title == "Override Title"
assert job_create.lyrics_file_gcs_path == "uploads/test/lyrics/file.txt"
assert job_create.subtitle_offset_ms == 250
def test_job_create_lyrics_fields_optional(self):
"""Test that lyrics fields are optional in JobCreate."""
from backend.models.job import JobCreate
job_create = JobCreate(
artist="Artist",
title="Title"
)
assert job_create.lyrics_artist is None
assert job_create.lyrics_title is None
assert job_create.lyrics_file_gcs_path is None
assert job_create.subtitle_offset_ms == 0
class TestAudioModelConfigurationFields:
"""Test that Job and JobCreate models support audio model configuration fields."""
def test_job_has_clean_instrumental_model_field(self):
"""Test that Job model has clean_instrumental_model field."""
from backend.models.job import Job
from datetime import datetime
job = Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
clean_instrumental_model="custom_model.ckpt"
)
assert hasattr(job, 'clean_instrumental_model')
assert job.clean_instrumental_model == "custom_model.ckpt"
def test_job_has_backing_vocals_models_field(self):
"""Test that Job model has backing_vocals_models field."""
from backend.models.job import Job
from datetime import datetime
job = Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
backing_vocals_models=["model1.ckpt", "model2.ckpt"]
)
assert hasattr(job, 'backing_vocals_models')
assert job.backing_vocals_models == ["model1.ckpt", "model2.ckpt"]
def test_job_has_other_stems_models_field(self):
"""Test that Job model has other_stems_models field."""
from backend.models.job import Job
from datetime import datetime
job = Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
other_stems_models=["htdemucs_6s.yaml"]
)
assert hasattr(job, 'other_stems_models')
assert job.other_stems_models == ["htdemucs_6s.yaml"]
def test_audio_model_fields_are_optional(self):
"""Test that audio model fields default to None."""
from backend.models.job import Job
from datetime import datetime
job = Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.utcnow(),
updated_at=datetime.utcnow()
)
assert job.clean_instrumental_model is None
assert job.backing_vocals_models is None
assert job.other_stems_models is None
def test_job_create_has_audio_model_fields(self):
"""Test that JobCreate model has all audio model configuration fields."""
from backend.models.job import JobCreate
job_create = JobCreate(
artist="Artist",
title="Title",
clean_instrumental_model="custom_clean.ckpt",
backing_vocals_models=["custom_bv.ckpt"],
other_stems_models=["custom_stems.yaml"]
)
assert job_create.clean_instrumental_model == "custom_clean.ckpt"
assert job_create.backing_vocals_models == ["custom_bv.ckpt"]
assert job_create.other_stems_models == ["custom_stems.yaml"]
def test_job_create_audio_model_fields_optional(self):
"""Test that audio model fields are optional in JobCreate."""
from backend.models.job import JobCreate
job_create = JobCreate(
artist="Artist",
title="Title"
)
assert job_create.clean_instrumental_model is None
assert job_create.backing_vocals_models is None
assert job_create.other_stems_models is None
def test_pydantic_includes_audio_model_fields_in_serialization(self):
"""Test that Pydantic includes audio model fields in serialization."""
from backend.models.job import Job
from datetime import datetime
job = Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
clean_instrumental_model="custom.ckpt",
backing_vocals_models=["bv1.ckpt", "bv2.ckpt"],
other_stems_models=["stems.yaml"]
)
job_dict = job.model_dump()
assert "clean_instrumental_model" in job_dict
assert job_dict["clean_instrumental_model"] == "custom.ckpt"
assert "backing_vocals_models" in job_dict
assert job_dict["backing_vocals_models"] == ["bv1.ckpt", "bv2.ckpt"]
assert "other_stems_models" in job_dict
assert job_dict["other_stems_models"] == ["stems.yaml"]
class TestCommaDelimitedModelParsing:
"""Test parsing of comma-delimited model strings."""
def test_parse_single_model(self):
"""Test parsing a single model string."""
model_str = "model1.ckpt"
result = [m.strip() for m in model_str.split(',') if m.strip()]
assert result == ["model1.ckpt"]
def test_parse_multiple_models(self):
"""Test parsing multiple models."""
model_str = "model1.ckpt,model2.ckpt,model3.ckpt"
result = [m.strip() for m in model_str.split(',') if m.strip()]
assert result == ["model1.ckpt", "model2.ckpt", "model3.ckpt"]
def test_parse_models_with_whitespace(self):
"""Test parsing models with whitespace around commas."""
model_str = "model1.ckpt , model2.ckpt, model3.ckpt "
result = [m.strip() for m in model_str.split(',') if m.strip()]
assert result == ["model1.ckpt", "model2.ckpt", "model3.ckpt"]
def test_parse_empty_string(self):
"""Test parsing empty string."""
model_str = ""
result = [m.strip() for m in model_str.split(',') if m.strip()]
assert result == []
def test_parse_none_returns_none(self):
"""Test that None model string is handled correctly."""
model_str = None
result = None
if model_str:
result = [m.strip() for m in model_str.split(',') if m.strip()]
assert result is None
class TestSignedUrlUploadModels:
"""Test Pydantic models for signed URL upload flow."""
def test_file_upload_request_model(self):
"""Test FileUploadRequest model."""
from backend.api.routes.file_upload import FileUploadRequest
file_req = FileUploadRequest(
filename="test.flac",
content_type="audio/flac",
file_type="audio"
)
assert file_req.filename == "test.flac"
assert file_req.content_type == "audio/flac"
assert file_req.file_type == "audio"
def test_create_job_with_upload_urls_request_model(self):
"""Test CreateJobWithUploadUrlsRequest model."""
from backend.api.routes.file_upload import CreateJobWithUploadUrlsRequest, FileUploadRequest
request = CreateJobWithUploadUrlsRequest(
artist="Test Artist",
title="Test Song",
files=[
FileUploadRequest(filename="test.flac", content_type="audio/flac", file_type="audio")
],
enable_cdg=True,
enable_txt=True,
brand_prefix="NOMAD"
)
assert request.artist == "Test Artist"
assert request.title == "Test Song"
assert len(request.files) == 1
assert request.files[0].file_type == "audio"
assert request.brand_prefix == "NOMAD"
def test_signed_upload_url_model(self):
"""Test SignedUploadUrl model."""
from backend.api.routes.file_upload import SignedUploadUrl
url_info = SignedUploadUrl(
file_type="audio",
gcs_path="uploads/test123/audio/test.flac",
upload_url="https://storage.googleapis.com/signed-url",
content_type="audio/flac"
)
assert url_info.file_type == "audio"
assert url_info.gcs_path == "uploads/test123/audio/test.flac"
assert url_info.upload_url.startswith("https://")
assert url_info.content_type == "audio/flac"
def test_uploads_complete_request_model(self):
"""Test UploadsCompleteRequest model."""
from backend.api.routes.file_upload import UploadsCompleteRequest
request = UploadsCompleteRequest(
uploaded_files=["audio", "style_params", "style_intro_background"]
)
assert len(request.uploaded_files) == 3
assert "audio" in request.uploaded_files
class TestValidFileTypes:
"""Test file type validation for signed URL upload."""
def test_valid_file_types_includes_audio(self):
"""Test that audio is a valid file type."""
from backend.api.routes.file_upload import VALID_FILE_TYPES
assert 'audio' in VALID_FILE_TYPES
assert '.flac' in VALID_FILE_TYPES['audio']
assert '.mp3' in VALID_FILE_TYPES['audio']
def test_valid_file_types_includes_style_assets(self):
"""Test that all style assets are valid file types."""
from backend.api.routes.file_upload import VALID_FILE_TYPES
assert 'style_params' in VALID_FILE_TYPES
assert 'style_intro_background' in VALID_FILE_TYPES
assert 'style_karaoke_background' in VALID_FILE_TYPES
assert 'style_end_background' in VALID_FILE_TYPES
assert 'style_font' in VALID_FILE_TYPES
assert 'style_cdg_instrumental_background' in VALID_FILE_TYPES
assert 'style_cdg_title_background' in VALID_FILE_TYPES
assert 'style_cdg_outro_background' in VALID_FILE_TYPES
def test_valid_file_types_includes_lyrics(self):
"""Test that lyrics file is a valid file type."""
from backend.api.routes.file_upload import VALID_FILE_TYPES
assert 'lyrics_file' in VALID_FILE_TYPES
assert '.txt' in VALID_FILE_TYPES['lyrics_file']
assert '.docx' in VALID_FILE_TYPES['lyrics_file']
class TestSignedUrlGCSPathGeneration:
"""Test GCS path generation for signed URL upload."""
def test_audio_gcs_path(self):
"""Test GCS path generation for audio file."""
from backend.api.routes.file_upload import _get_gcs_path_for_file
path = _get_gcs_path_for_file("test123", "audio", "song.flac")
assert path == "uploads/test123/audio/song.flac"
def test_style_params_gcs_path(self):
"""Test GCS path generation for style params."""
from backend.api.routes.file_upload import _get_gcs_path_for_file
path = _get_gcs_path_for_file("test123", "style_params", "style.json")
assert path == "uploads/test123/style/style_params.json"
def test_style_background_gcs_path(self):
"""Test GCS path generation for style background images."""
from backend.api.routes.file_upload import _get_gcs_path_for_file
path = _get_gcs_path_for_file("test123", "style_intro_background", "bg.png")
assert path == "uploads/test123/style/intro_background.png"
def test_style_font_gcs_path(self):
"""Test GCS path generation for font file."""
from backend.api.routes.file_upload import _get_gcs_path_for_file
path = _get_gcs_path_for_file("test123", "style_font", "font.ttf")
assert path == "uploads/test123/style/font.ttf"
def test_lyrics_file_gcs_path(self):
"""Test GCS path generation for lyrics file."""
from backend.api.routes.file_upload import _get_gcs_path_for_file
path = _get_gcs_path_for_file("test123", "lyrics_file", "lyrics.txt")
assert path == "uploads/test123/lyrics/user_lyrics.txt"
class TestStorageServiceSignedUrls:
"""Test StorageService signed URL generation."""
def test_generate_signed_upload_url_method_exists(self):
"""Test that generate_signed_upload_url method exists in StorageService."""
from backend.services.storage_service import StorageService
assert hasattr(StorageService, 'generate_signed_upload_url')
def test_generate_signed_url_internal_method_exists(self):
"""Test that _generate_signed_url_internal method exists in StorageService."""
from backend.services.storage_service import StorageService
assert hasattr(StorageService, '_generate_signed_url_internal')
class TestCreateJobWithUploadUrlsValidation:
"""Test validation for create_job_with_upload_urls endpoint."""
def test_request_without_audio_is_invalid(self):
"""Test that request without audio file is rejected."""
from backend.api.routes.file_upload import CreateJobWithUploadUrlsRequest, FileUploadRequest
import pytest
# This should be caught during endpoint validation
# Here we test the model can be created but endpoint should reject
request = CreateJobWithUploadUrlsRequest(
artist="Artist",
title="Title",
files=[
FileUploadRequest(filename="style.json", content_type="application/json", file_type="style_params")
]
)
# Endpoint validation should catch this
audio_files = [f for f in request.files if f.file_type == 'audio']
assert len(audio_files) == 0 # No audio - should be rejected by endpoint
def test_request_with_multiple_audio_is_invalid(self):
"""Test that request with multiple audio files is rejected."""
from backend.api.routes.file_upload import CreateJobWithUploadUrlsRequest, FileUploadRequest
request = CreateJobWithUploadUrlsRequest(
artist="Artist",
title="Title",
files=[
FileUploadRequest(filename="song1.flac", content_type="audio/flac", file_type="audio"),
FileUploadRequest(filename="song2.flac", content_type="audio/flac", file_type="audio")
]
)
audio_files = [f for f in request.files if f.file_type == 'audio']
assert len(audio_files) == 2 # Multiple audio - should be rejected by endpoint
def test_request_with_invalid_file_type(self):
"""Test that request with invalid file type is rejected."""
from backend.api.routes.file_upload import VALID_FILE_TYPES
assert 'invalid_type' not in VALID_FILE_TYPES
class TestExistingInstrumentalSupport:
"""Test existing instrumental support (Batch 3)."""
def test_valid_file_types_includes_existing_instrumental(self):
"""Test that existing_instrumental is a valid file type."""
from backend.api.routes.file_upload import VALID_FILE_TYPES, ALLOWED_AUDIO_EXTENSIONS
assert 'existing_instrumental' in VALID_FILE_TYPES
assert VALID_FILE_TYPES['existing_instrumental'] == ALLOWED_AUDIO_EXTENSIONS
def test_existing_instrumental_gcs_path(self):
"""Test GCS path generation for existing instrumental file."""
from backend.api.routes.file_upload import _get_gcs_path_for_file
path = _get_gcs_path_for_file("test123", "existing_instrumental", "instrumental.flac")
assert path == "uploads/test123/audio/existing_instrumental.flac"
def test_existing_instrumental_gcs_path_mp3(self):
"""Test GCS path generation for existing instrumental MP3 file."""
from backend.api.routes.file_upload import _get_gcs_path_for_file
path = _get_gcs_path_for_file("test123", "existing_instrumental", "instrumental.mp3")
assert path == "uploads/test123/audio/existing_instrumental.mp3"
def test_existing_instrumental_gcs_path_wav(self):
"""Test GCS path generation for existing instrumental WAV file."""
from backend.api.routes.file_upload import _get_gcs_path_for_file
path = _get_gcs_path_for_file("test123", "existing_instrumental", "my_instrumental.wav")
assert path == "uploads/test123/audio/existing_instrumental.wav"
def test_job_has_existing_instrumental_gcs_path_field(self):
"""Test that Job model has existing_instrumental_gcs_path field."""
from backend.models.job import Job
from datetime import datetime, UTC
job = Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
existing_instrumental_gcs_path="uploads/test123/audio/existing_instrumental.flac"
)
assert hasattr(job, 'existing_instrumental_gcs_path')
assert job.existing_instrumental_gcs_path == "uploads/test123/audio/existing_instrumental.flac"
def test_existing_instrumental_gcs_path_optional(self):
"""Test that existing_instrumental_gcs_path is optional."""
from backend.models.job import Job
from datetime import datetime, UTC
job = Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC)
)
assert job.existing_instrumental_gcs_path is None
def test_job_create_has_existing_instrumental_gcs_path_field(self):
"""Test that JobCreate model has existing_instrumental_gcs_path field."""
from backend.models.job import JobCreate
job_create = JobCreate(
artist="Artist",
title="Title",
existing_instrumental_gcs_path="uploads/test123/audio/existing_instrumental.flac"
)
assert hasattr(job_create, 'existing_instrumental_gcs_path')
assert job_create.existing_instrumental_gcs_path == "uploads/test123/audio/existing_instrumental.flac"
def test_job_create_existing_instrumental_optional(self):
"""Test that existing_instrumental_gcs_path is optional in JobCreate."""
from backend.models.job import JobCreate
job_create = JobCreate(
artist="Artist",
title="Title"
)
assert job_create.existing_instrumental_gcs_path is None
def test_pydantic_includes_existing_instrumental_in_serialization(self):
"""Test that Pydantic includes existing_instrumental_gcs_path in serialization."""
from backend.models.job import Job
from datetime import datetime, UTC
job = Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
existing_instrumental_gcs_path="uploads/test123/audio/existing_instrumental.flac"
)
job_dict = job.model_dump()
assert "existing_instrumental_gcs_path" in job_dict
assert job_dict["existing_instrumental_gcs_path"] == "uploads/test123/audio/existing_instrumental.flac"
@pytest.mark.parametrize("filename,expected_valid", [
("instrumental.mp3", True),
("instrumental.flac", True),
("instrumental.wav", True),
("instrumental.m4a", True),
("instrumental.ogg", True),
("instrumental.aac", True),
("instrumental.txt", False),
("instrumental.pdf", False),
])
def test_existing_instrumental_extension_validation(self, filename, expected_valid):
"""Test that only valid audio extensions are accepted for existing instrumental."""
from pathlib import Path
from backend.api.routes.file_upload import VALID_FILE_TYPES
allowed_extensions = VALID_FILE_TYPES['existing_instrumental']
file_ext = Path(filename).suffix.lower()
is_valid = file_ext in allowed_extensions
assert is_valid == expected_valid
def test_create_job_with_upload_urls_request_has_existing_instrumental_flag(self):
"""Test that CreateJobWithUploadUrlsRequest has existing_instrumental field."""
from backend.api.routes.file_upload import CreateJobWithUploadUrlsRequest, FileUploadRequest
request = CreateJobWithUploadUrlsRequest(
artist="Test Artist",
title="Test Song",
files=[
FileUploadRequest(filename="test.flac", content_type="audio/flac", file_type="audio"),
FileUploadRequest(filename="instr.flac", content_type="audio/flac", file_type="existing_instrumental"),
],
existing_instrumental=True
)
assert request.existing_instrumental is True
def test_create_job_with_upload_urls_request_existing_instrumental_default_false(self):
"""Test that existing_instrumental defaults to False."""
from backend.api.routes.file_upload import CreateJobWithUploadUrlsRequest, FileUploadRequest
request = CreateJobWithUploadUrlsRequest(
artist="Test Artist",
title="Test Song",
files=[
FileUploadRequest(filename="test.flac", content_type="audio/flac", file_type="audio"),
]
)
assert request.existing_instrumental is False
class TestDurationValidation:
"""Test audio duration validation for existing instrumental (Batch 3)."""
def test_validate_audio_durations_function_exists(self):
"""Test that _validate_audio_durations function exists."""
from backend.api.routes.file_upload import _validate_audio_durations
assert callable(_validate_audio_durations)
@pytest.mark.asyncio
async def test_duration_validation_returns_tuple(self):
"""Test that duration validation returns correct tuple structure."""
# This is a structural test - actual implementation tested in integration tests
# The function should return (is_valid: bool, audio_duration: float, instrumental_duration: float)
from backend.api.routes.file_upload import _validate_audio_durations
import inspect
# Verify it's an async function
assert inspect.iscoroutinefunction(_validate_audio_durations)
if __name__ == "__main__":
pytest.main([__file__, "-v"])
+93
View File
@@ -577,6 +577,99 @@ class TestJobModelIntegration:
assert restored_job.state_data["lyrics_metadata"]["line_count"] == 50
class TestExistingInstrumentalModelFields:
"""Test existing instrumental field in Job and JobCreate models (Batch 3)."""
def test_job_has_existing_instrumental_gcs_path(self):
"""Test that Job model has existing_instrumental_gcs_path field."""
job = Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
existing_instrumental_gcs_path="uploads/test123/audio/existing_instrumental.flac"
)
assert hasattr(job, 'existing_instrumental_gcs_path')
assert job.existing_instrumental_gcs_path == "uploads/test123/audio/existing_instrumental.flac"
def test_job_existing_instrumental_defaults_to_none(self):
"""Test that existing_instrumental_gcs_path defaults to None."""
job = Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC)
)
assert job.existing_instrumental_gcs_path is None
def test_job_create_has_existing_instrumental_gcs_path(self):
"""Test that JobCreate model has existing_instrumental_gcs_path field."""
from backend.models.job import JobCreate
job_create = JobCreate(
artist="Artist",
title="Title",
existing_instrumental_gcs_path="uploads/test/audio/existing_instrumental.mp3"
)
assert job_create.existing_instrumental_gcs_path == "uploads/test/audio/existing_instrumental.mp3"
def test_job_create_existing_instrumental_optional(self):
"""Test that existing_instrumental_gcs_path is optional in JobCreate."""
from backend.models.job import JobCreate
job_create = JobCreate(
artist="Artist",
title="Title"
)
assert job_create.existing_instrumental_gcs_path is None
def test_existing_instrumental_roundtrip_serialization(self):
"""Test that existing_instrumental_gcs_path survives serialization/deserialization."""
job = Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
existing_instrumental_gcs_path="uploads/test123/audio/existing_instrumental.wav"
)
# Serialize to dict (simulates writing to Firestore)
job_dict = job.model_dump()
# Convert to JSON and back (simulates Firestore storage)
json_str = json.dumps(job_dict, default=str)
restored_dict = json.loads(json_str)
# Deserialize back to Job (simulates reading from Firestore)
restored_job = Job(**restored_dict)
assert restored_job.existing_instrumental_gcs_path == "uploads/test123/audio/existing_instrumental.wav"
def test_job_with_full_audio_config(self):
"""Test Job with complete audio configuration including existing instrumental."""
job = Job(
job_id="test123",
status=JobStatus.AUDIO_COMPLETE,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test Artist",
title="Test Song",
# Audio model configuration
clean_instrumental_model="model_bs_roformer_ep_317_sdr_12.9755.ckpt",
backing_vocals_models=["mel_band_roformer_karaoke.ckpt"],
other_stems_models=["htdemucs_6s.yaml"],
# Existing instrumental
existing_instrumental_gcs_path="uploads/test123/audio/my_instrumental.flac",
)
assert job.clean_instrumental_model == "model_bs_roformer_ep_317_sdr_12.9755.ckpt"
assert job.existing_instrumental_gcs_path == "uploads/test123/audio/my_instrumental.flac"
if __name__ == "__main__":
pytest.main([__file__, "-v"])
+10
View File
@@ -62,6 +62,16 @@ class TestJobStatusTransitions:
if status not in excluded:
valid_transitions = STATE_TRANSITIONS.get(status, [])
assert JobStatus.FAILED in valid_transitions, f"{status} should be able to fail"
def test_failed_can_transition_for_retry(self):
"""Test FAILED status can transition to retry checkpoint states."""
from backend.models.job import STATE_TRANSITIONS
valid_transitions = STATE_TRANSITIONS.get(JobStatus.FAILED, [])
# FAILED should allow retry transitions
assert JobStatus.INSTRUMENTAL_SELECTED in valid_transitions, "FAILED should allow retry to INSTRUMENTAL_SELECTED"
assert JobStatus.REVIEW_COMPLETE in valid_transitions, "FAILED should allow retry to REVIEW_COMPLETE"
assert JobStatus.LYRICS_COMPLETE in valid_transitions, "FAILED should allow retry to LYRICS_COMPLETE"
class TestJobModelSerialization:
+328
View File
@@ -353,6 +353,108 @@ class TestLyricsWorker:
mock_job_manager.mark_job_failed.assert_called()
class TestLyricsWorkerConfiguration:
"""Tests for lyrics worker configuration parameters."""
def test_create_lyrics_processor_with_defaults(self):
"""Test creating LyricsProcessor with default parameters."""
with patch('backend.workers.lyrics_worker.LyricsProcessor') as mock_processor:
from backend.workers.lyrics_worker import create_lyrics_processor
result = create_lyrics_processor()
mock_processor.assert_called_once()
call_kwargs = mock_processor.call_args[1]
assert call_kwargs['lyrics_file'] is None
assert call_kwargs['subtitle_offset_ms'] == 0
def test_create_lyrics_processor_with_lyrics_file(self):
"""Test creating LyricsProcessor with custom lyrics file."""
with patch('backend.workers.lyrics_worker.LyricsProcessor') as mock_processor:
from backend.workers.lyrics_worker import create_lyrics_processor
result = create_lyrics_processor(
lyrics_file="/path/to/lyrics.txt",
subtitle_offset_ms=0
)
mock_processor.assert_called_once()
call_kwargs = mock_processor.call_args[1]
assert call_kwargs['lyrics_file'] == "/path/to/lyrics.txt"
def test_create_lyrics_processor_with_subtitle_offset(self):
"""Test creating LyricsProcessor with subtitle offset."""
with patch('backend.workers.lyrics_worker.LyricsProcessor') as mock_processor:
from backend.workers.lyrics_worker import create_lyrics_processor
result = create_lyrics_processor(
subtitle_offset_ms=500
)
mock_processor.assert_called_once()
call_kwargs = mock_processor.call_args[1]
assert call_kwargs['subtitle_offset_ms'] == 500
class TestLyricsOverrideParameters:
"""Tests for lyrics artist/title override functionality."""
@pytest.fixture
def mock_job_with_overrides(self):
"""Create a mock job with lyrics override fields."""
return Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Beatles, The",
title="Hey Jude - 2009 Remaster",
lyrics_artist="The Beatles",
lyrics_title="Hey Jude",
subtitle_offset_ms=250,
input_media_gcs_path="uploads/test123/song.flac"
)
def test_job_uses_lyrics_artist_override(self, mock_job_with_overrides):
"""Test that job uses lyrics_artist when searching for lyrics."""
job = mock_job_with_overrides
# Use override if present, else fall back to main artist
lyrics_search_artist = job.lyrics_artist or job.artist
assert lyrics_search_artist == "The Beatles"
assert lyrics_search_artist != job.artist # Override is different
def test_job_uses_lyrics_title_override(self, mock_job_with_overrides):
"""Test that job uses lyrics_title when searching for lyrics."""
job = mock_job_with_overrides
# Use override if present, else fall back to main title
lyrics_search_title = job.lyrics_title or job.title
assert lyrics_search_title == "Hey Jude"
assert lyrics_search_title != job.title # Override is different
def test_job_falls_back_when_no_override(self):
"""Test that job falls back to main artist/title when no override."""
job = Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test Artist",
title="Test Song",
input_media_gcs_path="uploads/test123/song.flac"
)
# When override is None, use main values
lyrics_search_artist = job.lyrics_artist or job.artist
lyrics_search_title = job.lyrics_title or job.title
assert lyrics_search_artist == "Test Artist"
assert lyrics_search_title == "Test Song"
class TestScreensWorker:
"""Tests for screens_worker.py functions.
@@ -379,6 +481,71 @@ class TestVideoWorker:
assert hasattr(video_worker, 'logger')
class TestRenderVideoWorkerConfiguration:
"""Tests for render_video_worker subtitle_offset_ms support."""
@pytest.fixture
def mock_job_with_offset(self):
"""Create a mock job with subtitle offset."""
return Job(
job_id="test123",
status=JobStatus.RENDERING_VIDEO,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test Artist",
title="Test Song",
subtitle_offset_ms=500,
input_media_gcs_path="uploads/test123/song.flac"
)
def test_job_has_subtitle_offset_ms(self, mock_job_with_offset):
"""Test that job has subtitle_offset_ms field."""
assert mock_job_with_offset.subtitle_offset_ms == 500
def test_subtitle_offset_from_job(self, mock_job_with_offset):
"""Test extracting subtitle offset from job with getattr."""
job = mock_job_with_offset
# This mirrors the logic in render_video_worker.py
subtitle_offset = getattr(job, 'subtitle_offset_ms', 0) or 0
assert subtitle_offset == 500
def test_subtitle_offset_default_zero(self):
"""Test that subtitle offset defaults to 0 when not set."""
job = Job(
job_id="test123",
status=JobStatus.RENDERING_VIDEO,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test Artist",
title="Test Song",
input_media_gcs_path="uploads/test123/song.flac"
)
subtitle_offset = getattr(job, 'subtitle_offset_ms', 0) or 0
assert subtitle_offset == 0
def test_subtitle_offset_negative_value(self):
"""Test that subtitle offset can be negative (advance subtitles)."""
job = Job(
job_id="test123",
status=JobStatus.RENDERING_VIDEO,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test Artist",
title="Test Song",
subtitle_offset_ms=-250, # Negative = advance subtitles
input_media_gcs_path="uploads/test123/song.flac"
)
subtitle_offset = getattr(job, 'subtitle_offset_ms', 0) or 0
# Negative values should be preserved (not converted to 0)
assert subtitle_offset == -250
class TestDownloadHelpers:
"""Tests for download helper functions in workers."""
@@ -406,3 +573,164 @@ class TestDownloadHelpers:
# Should have downloaded from GCS
mock_storage.download_file.assert_called()
class TestAudioWorkerModelConfiguration:
"""Tests for audio worker model configuration parameters."""
def test_create_audio_processor_with_defaults(self):
"""Test creating AudioProcessor with default models."""
with patch('backend.workers.audio_worker.AudioProcessor') as mock_processor:
from backend.workers.audio_worker import create_audio_processor
with tempfile.TemporaryDirectory() as temp_dir:
result = create_audio_processor(temp_dir)
mock_processor.assert_called_once()
call_kwargs = mock_processor.call_args[1]
# Should use default models
assert call_kwargs['clean_instrumental_model'] == "model_bs_roformer_ep_317_sdr_12.9755.ckpt"
assert call_kwargs['backing_vocals_models'] == ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"]
assert call_kwargs['other_stems_models'] == ["htdemucs_6s.yaml"]
def test_create_audio_processor_with_custom_clean_model(self):
"""Test creating AudioProcessor with custom clean instrumental model."""
with patch('backend.workers.audio_worker.AudioProcessor') as mock_processor:
from backend.workers.audio_worker import create_audio_processor
with tempfile.TemporaryDirectory() as temp_dir:
result = create_audio_processor(
temp_dir,
clean_instrumental_model="custom_clean_model.ckpt"
)
mock_processor.assert_called_once()
call_kwargs = mock_processor.call_args[1]
# Should use custom clean model
assert call_kwargs['clean_instrumental_model'] == "custom_clean_model.ckpt"
# Other models should still be defaults
assert call_kwargs['backing_vocals_models'] == ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"]
def test_create_audio_processor_with_custom_backing_models(self):
"""Test creating AudioProcessor with custom backing vocals models."""
with patch('backend.workers.audio_worker.AudioProcessor') as mock_processor:
from backend.workers.audio_worker import create_audio_processor
with tempfile.TemporaryDirectory() as temp_dir:
result = create_audio_processor(
temp_dir,
backing_vocals_models=["custom_bv1.ckpt", "custom_bv2.ckpt"]
)
mock_processor.assert_called_once()
call_kwargs = mock_processor.call_args[1]
# Should use custom backing vocals models
assert call_kwargs['backing_vocals_models'] == ["custom_bv1.ckpt", "custom_bv2.ckpt"]
def test_create_audio_processor_with_custom_other_stems_models(self):
"""Test creating AudioProcessor with custom other stems models."""
with patch('backend.workers.audio_worker.AudioProcessor') as mock_processor:
from backend.workers.audio_worker import create_audio_processor
with tempfile.TemporaryDirectory() as temp_dir:
result = create_audio_processor(
temp_dir,
other_stems_models=["custom_demucs.yaml"]
)
mock_processor.assert_called_once()
call_kwargs = mock_processor.call_args[1]
# Should use custom other stems models
assert call_kwargs['other_stems_models'] == ["custom_demucs.yaml"]
def test_create_audio_processor_with_all_custom_models(self):
"""Test creating AudioProcessor with all custom models."""
with patch('backend.workers.audio_worker.AudioProcessor') as mock_processor:
from backend.workers.audio_worker import create_audio_processor
with tempfile.TemporaryDirectory() as temp_dir:
result = create_audio_processor(
temp_dir,
clean_instrumental_model="custom_clean.ckpt",
backing_vocals_models=["custom_bv.ckpt"],
other_stems_models=["custom_stems.yaml"]
)
mock_processor.assert_called_once()
call_kwargs = mock_processor.call_args[1]
# All models should be custom
assert call_kwargs['clean_instrumental_model'] == "custom_clean.ckpt"
assert call_kwargs['backing_vocals_models'] == ["custom_bv.ckpt"]
assert call_kwargs['other_stems_models'] == ["custom_stems.yaml"]
def test_job_model_fields_are_passed_to_processor(self):
"""Test that job model fields can be passed to create_audio_processor."""
mock_job = Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test",
title="Test",
clean_instrumental_model="job_clean.ckpt",
backing_vocals_models=["job_bv.ckpt"],
other_stems_models=["job_stems.yaml"]
)
with patch('backend.workers.audio_worker.AudioProcessor') as mock_processor:
from backend.workers.audio_worker import create_audio_processor
with tempfile.TemporaryDirectory() as temp_dir:
# Simulate passing job model fields to create_audio_processor
result = create_audio_processor(
temp_dir,
clean_instrumental_model=mock_job.clean_instrumental_model,
backing_vocals_models=mock_job.backing_vocals_models,
other_stems_models=mock_job.other_stems_models
)
mock_processor.assert_called_once()
call_kwargs = mock_processor.call_args[1]
# Models from job should be used
assert call_kwargs['clean_instrumental_model'] == "job_clean.ckpt"
assert call_kwargs['backing_vocals_models'] == ["job_bv.ckpt"]
assert call_kwargs['other_stems_models'] == ["job_stems.yaml"]
def test_none_model_values_use_defaults(self):
"""Test that None model values fall back to defaults."""
mock_job = Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test",
title="Test",
clean_instrumental_model=None, # Not specified
backing_vocals_models=None, # Not specified
other_stems_models=None # Not specified
)
with patch('backend.workers.audio_worker.AudioProcessor') as mock_processor:
from backend.workers.audio_worker import create_audio_processor
with tempfile.TemporaryDirectory() as temp_dir:
result = create_audio_processor(
temp_dir,
clean_instrumental_model=mock_job.clean_instrumental_model,
backing_vocals_models=mock_job.backing_vocals_models,
other_stems_models=mock_job.other_stems_models
)
mock_processor.assert_called_once()
call_kwargs = mock_processor.call_args[1]
# Should fall back to defaults
assert call_kwargs['clean_instrumental_model'] == "model_bs_roformer_ep_317_sdr_12.9755.ckpt"
assert call_kwargs['backing_vocals_models'] == ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"]
assert call_kwargs['other_stems_models'] == ["htdemucs_6s.yaml"]
+31 -10
View File
@@ -112,7 +112,12 @@ async def download_from_url(url: str, temp_dir: str, artist: str, title: str) ->
return None
def create_audio_processor(temp_dir: str) -> AudioProcessor:
def create_audio_processor(
temp_dir: str,
clean_instrumental_model: Optional[str] = None,
backing_vocals_models: Optional[list] = None,
other_stems_models: Optional[list] = None
) -> AudioProcessor:
"""
Create an AudioProcessor instance configured for remote API processing.
@@ -120,10 +125,13 @@ def create_audio_processor(temp_dir: str) -> AudioProcessor:
- Uses remote Modal API (via AUDIO_SEPARATOR_API_URL env var)
- No local models needed (model_file_dir=None)
- FLAC output format for quality
- Standard model configurations from karaoke-gen CLI
- Model configurations from job or CLI defaults
Args:
temp_dir: Temporary directory for processing
clean_instrumental_model: Model for clean instrumental separation (optional, uses default if not provided)
backing_vocals_models: List of models for backing vocals separation (optional, uses default if not provided)
other_stems_models: List of models for other stems separation (optional, uses default if not provided)
Returns:
Configured AudioProcessor instance
@@ -132,10 +140,10 @@ def create_audio_processor(temp_dir: str) -> AudioProcessor:
audio_logger = logging.getLogger("karaoke_gen.audio_processor")
audio_logger.setLevel(logging.INFO)
# Model configurations (same as CLI defaults)
clean_instrumental_model = "model_bs_roformer_ep_317_sdr_12.9755.ckpt"
backing_vocals_models = ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"]
other_stems_models = ["htdemucs_6s.yaml"] # For 6-stem separation (bass, drums, etc.)
# Model configurations - use provided values or CLI defaults
effective_clean_model = clean_instrumental_model or "model_bs_roformer_ep_317_sdr_12.9755.ckpt"
effective_backing_models = backing_vocals_models or ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"]
effective_other_models = other_stems_models or ["htdemucs_6s.yaml"] # For 6-stem separation (bass, drums, etc.)
# FFmpeg command for combining audio files (must be a string, not a list)
ffmpeg_base_command = "ffmpeg -hide_banner -loglevel error -nostats -y"
@@ -146,9 +154,9 @@ def create_audio_processor(temp_dir: str) -> AudioProcessor:
log_formatter=None, # Not needed for our use case
model_file_dir=None, # No local models, using remote API
lossless_output_format="FLAC",
clean_instrumental_model=clean_instrumental_model,
backing_vocals_models=backing_vocals_models,
other_stems_models=other_stems_models,
clean_instrumental_model=effective_clean_model,
backing_vocals_models=effective_backing_models,
other_stems_models=effective_other_models,
ffmpeg_base_command=ffmpeg_base_command
)
@@ -226,8 +234,21 @@ async def process_audio_separation(job_id: str) -> bool:
})
# Create AudioProcessor instance (reuses karaoke_gen code)
# Use model configuration from job if provided, otherwise use defaults
job_log.info("Creating AudioProcessor instance...")
audio_processor = create_audio_processor(temp_dir)
if job.clean_instrumental_model:
job_log.info(f" Using clean instrumental model: {job.clean_instrumental_model}")
if job.backing_vocals_models:
job_log.info(f" Using backing vocals models: {job.backing_vocals_models}")
if job.other_stems_models:
job_log.info(f" Using other stems models: {job.other_stems_models}")
audio_processor = create_audio_processor(
temp_dir,
clean_instrumental_model=job.clean_instrumental_model,
backing_vocals_models=job.backing_vocals_models,
other_stems_models=job.other_stems_models
)
# Format artist-title for file naming (matches CLI behavior)
artist_title = f"{job.artist} - {job.title}"
+49 -21
View File
@@ -36,27 +36,21 @@ from karaoke_gen.lyrics_processor import LyricsProcessor
logger = logging.getLogger(__name__)
# Loggers to capture for lyrics worker (includes LyricsTranscriber internals)
# Loggers to capture for lyrics worker (top-level package loggers only)
# Note: We only capture at top-level package loggers to avoid duplicate log entries.
# Logs from sub-modules (e.g., lyrics_transcriber.correction.anchor_sequence) will
# propagate up to their parent logger (lyrics_transcriber) where they get captured.
LYRICS_WORKER_LOGGERS = [
"karaoke_gen.lyrics_processor",
"lyrics_transcriber",
"lyrics_transcriber.core",
"lyrics_transcriber.core.controller",
"lyrics_transcriber.lyrics",
"lyrics_transcriber.lyrics.genius",
"lyrics_transcriber.lyrics.spotify",
"lyrics_transcriber.lyrics.musixmatch",
"lyrics_transcriber.lyrics.lrclib",
"lyrics_transcriber.correction",
"lyrics_transcriber.correction.corrector",
"lyrics_transcriber.correction.anchor_sequence",
"lyrics_transcriber.transcribers",
"lyrics_transcriber.transcribers.audioshake",
"lyrics_transcriber.output",
]
def create_lyrics_processor(style_params_json: Optional[str] = None) -> LyricsProcessor:
def create_lyrics_processor(
style_params_json: Optional[str] = None,
lyrics_file: Optional[str] = None,
subtitle_offset_ms: int = 0
) -> LyricsProcessor:
"""
Create a LyricsProcessor instance configured for Cloud Run processing.
@@ -68,6 +62,8 @@ def create_lyrics_processor(style_params_json: Optional[str] = None) -> LyricsPr
Args:
style_params_json: Optional path to style parameters JSON file
lyrics_file: Optional path to user-provided lyrics file (overrides API fetch)
subtitle_offset_ms: Offset for subtitle timing in milliseconds
Returns:
Configured LyricsProcessor instance
@@ -79,11 +75,11 @@ def create_lyrics_processor(style_params_json: Optional[str] = None) -> LyricsPr
return LyricsProcessor(
logger=lyrics_logger,
style_params_json=style_params_json,
lyrics_file=None, # Will fetch from APIs
lyrics_file=lyrics_file, # Use user-provided lyrics if available
skip_transcription=False, # We want transcription
skip_transcription_review=True, # Skip interactive review (use React UI instead)
render_video=False, # Skip video generation for now (will be done after review)
subtitle_offset_ms=0 # No offset by default
subtitle_offset_ms=subtitle_offset_ms
)
@@ -201,10 +197,29 @@ async def process_lyrics_transcription(job_id: str) -> bool:
else:
job_log.info("No custom style params found, using defaults")
# Download user-provided lyrics file if available
lyrics_file_path = None
if hasattr(job, 'lyrics_file_gcs_path') and job.lyrics_file_gcs_path:
lyrics_file_path = os.path.join(temp_dir, "user_lyrics.txt")
job_log.info(f"Downloading user-provided lyrics file: {job.lyrics_file_gcs_path}")
storage.download_file(job.lyrics_file_gcs_path, lyrics_file_path)
job_log.info(f"User lyrics file downloaded to: {lyrics_file_path}")
# Get lyrics configuration from job
subtitle_offset = getattr(job, 'subtitle_offset_ms', 0) or 0
if subtitle_offset != 0:
job_log.info(f"Subtitle offset: {subtitle_offset}ms")
# Create LyricsProcessor instance (reuses karaoke_gen code)
job_log.info("Creating LyricsProcessor instance...")
job_log.info(f" style_params_json: {style_params_json_path}")
lyrics_processor = create_lyrics_processor(style_params_json=style_params_json_path)
job_log.info(f" lyrics_file: {lyrics_file_path}")
job_log.info(f" subtitle_offset_ms: {subtitle_offset}")
lyrics_processor = create_lyrics_processor(
style_params_json=style_params_json_path,
lyrics_file=lyrics_file_path,
subtitle_offset_ms=subtitle_offset
)
# Run transcription + correction
# This will:
@@ -213,19 +228,32 @@ async def process_lyrics_transcription(job_id: str) -> bool:
# 3. Run automatic correction with lyrics_transcriber
# 4. Generate corrections JSON (no interactive review)
# 5. Skip video generation (render_video=False)
# Use lyrics_artist/lyrics_title overrides if provided, else fall back to job artist/title
lyrics_search_artist = getattr(job, 'lyrics_artist', None) or job.artist
lyrics_search_title = getattr(job, 'lyrics_title', None) or job.title
job_log.info("Starting LyricsTranscriber processing...")
job_log.info(f" Artist: {job.artist}")
job_log.info(f" Title: {job.title}")
if lyrics_search_artist != job.artist:
job_log.info(f" Lyrics search artist override: {lyrics_search_artist}")
if lyrics_search_title != job.title:
job_log.info(f" Lyrics search title override: {lyrics_search_title}")
logger.info(f"Job {job_id}: Calling lyrics_processor.transcribe_lyrics()")
# Run transcription in thread pool to avoid blocking the event loop
# (transcribe_lyrics is synchronous and takes 1-2 minutes)
# Note: We pass the original artist/title for file naming, but the LyricsProcessor
# will use lyrics_artist/lyrics_title for the search (set via constructor args)
result = await asyncio.to_thread(
lyrics_processor.transcribe_lyrics,
input_audio_wav=audio_path,
artist=job.artist,
title=job.title,
track_output_dir=temp_dir
artist=job.artist, # Original artist for file naming
title=job.title, # Original title for file naming
track_output_dir=temp_dir,
lyrics_artist=lyrics_search_artist, # Override for lyrics search
lyrics_title=lyrics_search_title # Override for lyrics search
)
job_log.info("Transcription processing complete")
+6 -1
View File
@@ -190,6 +190,11 @@ async def process_render_video(job_id: str) -> bool:
job_log.info(f"Using styles from: {styles_path}")
# Get subtitle offset from job (user-specified timing adjustment)
subtitle_offset = getattr(job, 'subtitle_offset_ms', 0) or 0
if subtitle_offset != 0:
job_log.info(f"Applying subtitle offset: {subtitle_offset}ms")
config = OutputConfig(
output_dir=output_dir,
cache_dir=cache_dir,
@@ -199,7 +204,7 @@ async def process_render_video(job_id: str) -> bool:
generate_plain_text=True,
generate_lrc=True,
video_resolution="4k",
subtitle_offset_ms=0
subtitle_offset_ms=subtitle_offset
)
job_log.info(f"OutputConfig: output_styles_json={config.output_styles_json}, render_video={config.render_video}")
+59 -22
View File
@@ -41,8 +41,10 @@ logger = logging.getLogger(__name__)
# Loggers to capture for video worker
# Include the full module path to properly capture KaraokeFinalise logs
VIDEO_WORKER_LOGGERS = [
"karaoke_gen.karaoke_finalise",
"karaoke_gen.karaoke_finalise.karaoke_finalise", # The actual logger name from __name__
]
@@ -116,9 +118,9 @@ async def generate_video(job_id: str) -> bool:
# Download and set up files in the format KaraokeFinalise expects
base_name = f"{job.artist} - {job.title}"
job_log.info("Downloading files from GCS...")
await _setup_working_directory(job_id, job, storage, temp_dir, base_name)
job_log.info("Files downloaded successfully")
job_log.info("Downloading files from GCS (this may take a few minutes for large files)...")
await _setup_working_directory(job_id, job, storage, temp_dir, base_name, job_log)
job_log.info("All files downloaded successfully")
# Load style config for CDG styles
job_log.info("Loading CDG style configuration...")
@@ -133,9 +135,20 @@ async def generate_video(job_id: str) -> bool:
os.chdir(temp_dir)
# Get the selected instrumental file path
# Batch 3: If user provided existing instrumental, use that; otherwise use AI-separated
instrumental_selection = job.state_data['instrumental_selection']
instrumental_suffix = "Clean" if instrumental_selection == 'clean' else "Backing"
instrumental_file = os.path.join(temp_dir, f"{base_name} (Instrumental {instrumental_suffix}).flac")
existing_instrumental_path = getattr(job, 'existing_instrumental_gcs_path', None)
if existing_instrumental_path:
# User provided existing instrumental
ext = Path(existing_instrumental_path).suffix.lower()
instrumental_file = os.path.join(temp_dir, f"{base_name} (Instrumental User){ext}")
instrumental_source = "user-provided"
else:
# Use AI-separated instrumental
instrumental_suffix = "Clean" if instrumental_selection == 'clean' else "Backing"
instrumental_file = os.path.join(temp_dir, f"{base_name} (Instrumental {instrumental_suffix}).flac")
instrumental_source = instrumental_selection
# Transition to encoding state
job_manager.transition_to_state(
@@ -151,7 +164,9 @@ async def generate_video(job_id: str) -> bool:
job_log.info(f" enable_txt: {getattr(job, 'enable_txt', False)}")
job_log.info(f" brand_prefix: {getattr(job, 'brand_prefix', None)}")
job_log.info(f" discord_webhook: {'configured' if getattr(job, 'discord_webhook_url', None) else 'not configured'}")
job_log.info(f" instrumental: {instrumental_selection}")
job_log.info(f" instrumental source: {instrumental_source}")
if existing_instrumental_path:
job_log.info(f" using user-provided instrumental (selection was: {instrumental_selection})")
# Create KaraokeFinalise with ALL the parameters from the job
# This reuses all existing functionality!
@@ -443,7 +458,8 @@ async def _setup_working_directory(
job,
storage: StorageService,
temp_dir: str,
base_name: str
base_name: str,
job_log=None
) -> None:
"""
Download files from GCS and set up the directory structure KaraokeFinalise expects.
@@ -455,34 +471,55 @@ async def _setup_working_directory(
- {base_name} (Karaoke).lrc
- Instrumental audio file
"""
logger.info(f"Job {job_id}: Setting up working directory")
def log_progress(message: str):
"""Log to both module logger and job logger if available."""
logger.info(f"Job {job_id}: {message}")
if job_log:
job_log.info(message)
log_progress("Setting up working directory")
# Download title screen
log_progress("Downloading title screen...")
title_url = job.file_urls['screens']['title']
title_path = os.path.join(temp_dir, f"{base_name} (Title).mov")
storage.download_file(title_url, title_path)
logger.info(f"Job {job_id}: Downloaded title screen")
log_progress("Downloaded title screen")
# Download end screen
log_progress("Downloading end screen...")
end_url = job.file_urls['screens']['end']
end_path = os.path.join(temp_dir, f"{base_name} (End).mov")
storage.download_file(end_url, end_path)
logger.info(f"Job {job_id}: Downloaded end screen")
log_progress("Downloaded end screen")
# Download lyrics video (with vocals)
# Download lyrics video (with vocals) - this is the largest file, ~1-2GB
log_progress("Downloading karaoke video (largest file, may take 1-2 minutes)...")
lyrics_video_url = job.file_urls['videos']['with_vocals']
lyrics_video_path = os.path.join(temp_dir, f"{base_name} (With Vocals).mov")
storage.download_file(lyrics_video_url, lyrics_video_path)
logger.info(f"Job {job_id}: Downloaded lyrics video")
log_progress("Downloaded karaoke video")
# Download selected instrumental
# Download instrumental - either user-provided existing instrumental or AI-separated
existing_instrumental_path = getattr(job, 'existing_instrumental_gcs_path', None)
instrumental_selection = job.state_data['instrumental_selection']
instrumental_key = 'instrumental_clean' if instrumental_selection == 'clean' else 'instrumental_with_backing'
instrumental_url = job.file_urls['stems'][instrumental_key]
instrumental_suffix = "Clean" if instrumental_selection == 'clean' else "Backing"
instrumental_path = os.path.join(temp_dir, f"{base_name} (Instrumental {instrumental_suffix}).flac")
storage.download_file(instrumental_url, instrumental_path)
logger.info(f"Job {job_id}: Downloaded instrumental ({instrumental_selection})")
if existing_instrumental_path:
# Batch 3: Use user-provided existing instrumental
ext = Path(existing_instrumental_path).suffix.lower()
instrumental_path = os.path.join(temp_dir, f"{base_name} (Instrumental User){ext}")
log_progress(f"Downloading user-provided existing instrumental...")
storage.download_file(existing_instrumental_path, instrumental_path)
log_progress("Downloaded user-provided instrumental")
else:
# Use AI-separated instrumental based on selection
instrumental_key = 'instrumental_clean' if instrumental_selection == 'clean' else 'instrumental_with_backing'
instrumental_url = job.file_urls['stems'][instrumental_key]
instrumental_suffix = "Clean" if instrumental_selection == 'clean' else "Backing"
instrumental_path = os.path.join(temp_dir, f"{base_name} (Instrumental {instrumental_suffix}).flac")
log_progress(f"Downloading {instrumental_selection} instrumental audio...")
storage.download_file(instrumental_url, instrumental_path)
log_progress(f"Downloaded instrumental ({instrumental_selection})")
# Download LRC file if available (needed for CDG/TXT)
lyrics_urls = job.file_urls.get('lyrics', {})
@@ -490,19 +527,19 @@ async def _setup_working_directory(
lrc_url = lyrics_urls['lrc']
lrc_path = os.path.join(temp_dir, f"{base_name} (Karaoke).lrc")
storage.download_file(lrc_url, lrc_path)
logger.info(f"Job {job_id}: Downloaded LRC file")
log_progress("Downloaded LRC file")
# Download title/end JPG files (used for YouTube thumbnail)
screens = job.file_urls.get('screens', {})
if screens.get('title_jpg'):
title_jpg_path = os.path.join(temp_dir, f"{base_name} (Title).jpg")
storage.download_file(screens['title_jpg'], title_jpg_path)
logger.info(f"Job {job_id}: Downloaded title JPG for thumbnail")
log_progress("Downloaded title JPG for thumbnail")
if screens.get('end_jpg'):
end_jpg_path = os.path.join(temp_dir, f"{base_name} (End).jpg")
storage.download_file(screens['end_jpg'], end_jpg_path)
logger.info(f"Job {job_id}: Downloaded end JPG")
log_progress("Downloaded end JPG")
async def _upload_results(
@@ -1,10 +1,32 @@
# Backend Feature Parity Plan
**Last Updated:** 2024-12-10
**Status:** ✅ Core Feature Parity Achieved (v0.71.0)
**Last Updated:** 2024-12-11
**Status:** ✅ Core Feature Parity Achieved (v0.71.0) | Batch 1 ✅ | Batch 2 ✅ | Batch 3 ✅
This document tracks the progress toward complete feature parity between the local `karaoke-gen` CLI and the cloud backend, enabling the `karaoke-gen-remote` CLI to have equivalent functionality.
### Quick Parity Summary
| Category | Supported | Needed | Parity | Notes |
|----------|-----------|--------|--------|-------|
| Core Processing | 12 | 12 | **100%** | ✅ Complete |
| Distribution | 5 | 5 | **100%** | ✅ Complete |
| Lyrics Configuration | 5 | 5 | **100%** | ✅ **Batch 1 Complete** (L1-L4) |
| Style Configuration | 1 | 4 | **25%** | S2-S4 are MEDIUM priority |
| Workflow Control | 0 | 3 | **0%** | W1/W2 HIGH, W7 MEDIUM (skip flags deferred) |
| Audio Processing | 4 | 4 | **100%** | ✅ **Batch 2 & 3 Complete** (AP1-AP3, AP5) |
| Input Modes | 1 | 3 | **33%** | P2, P3 are HIGH priority |
| Audio Fetching | 0 | 1 | **0%** | A1 is HIGH priority |
| Flags to Remove | - | - | - | I3-I6, AP6 (simplify codebase) |
**Overall:** Core workflow complete. See [CLI Parameter Parity Analysis](#-cli-parameter-parity-analysis) for detailed parameter list with implementation plans.
**Priority Summary:**
- **HIGH**: L1-L4 (lyrics), AP1-AP5 (audio models/instrumental), P2-P3 (YouTube/flacfetch), A1 (interactive search), W1/W2 (prep/finalise phases), F15 (keep-brand-code)
- **MEDIUM**: S2-S4 (style overrides/video bg), W7 (edit-lyrics), F14 (email template)
- **LOW/DEFERRED**: W3-W6 (skip flags), D2-D3 (debugging)
- **REMOVE**: I3, I4, I5, I6, AP6 (unnecessary options)
---
## 🎉 Milestone: First Successful End-to-End Run
@@ -39,6 +61,501 @@ karaoke-gen-remote \
---
## 📊 CLI Parameter Parity Analysis
This section provides a comprehensive comparison of all CLI parameters between `karaoke-gen` (local) and `karaoke-gen-remote`, including detailed explanations of what each parameter does and how it could work remotely.
**Legend:**
- ✅ Fully supported
- ⚠️ Partially supported (limited functionality)
- ❌ Not supported (ignored or errors)
- 🔹 Remote-only (not applicable to local CLI)
- N/A Not applicable to this mode
---
### Positional Arguments
| # | Parameter | Local | Remote | Description |
|---|-----------|-------|--------|-------------|
| P1 | `<file>` | ✅ | ✅ | **Local audio file path.** Copies file to output directory, converts to WAV for processing. Supports MP3, FLAC, WAV, M4A, OGG, AAC. |
| P2 | `<url>` (YouTube) | ✅ | ❌ | **YouTube/online URL.** Uses yt-dlp to download audio and extract metadata (artist/title from video title). |
| P3 | `<artist> <title>` | ✅ | ❌ | **Audio search mode.** When no file is provided, uses flacfetch to search Deezer/Tidal/etc for high-quality audio and downloads it. |
| P4 | `<folder>` | ✅ | ❌ | **Batch folder processing.** Process all audio files in a folder, using `--filename_pattern` to extract track titles from filenames. |
**Remote Implementation Plan:**
- **P2 YouTube URLs**: HIGH PRIORITY. Install yt-dlp in Docker container. Backend downloads audio to GCS, extracts metadata, then processes. Use case: Niche live versions only on YouTube.
- **P3 Flacfetch search**: HIGH PRIORITY. Backend integrates flacfetch to search Deezer/Tidal/etc. IMPORTANT: Must support interactive mode via API - return search results to client, let user select, then proceed. Default should be interactive (not auto-select). Use case: Eventually expose audio source selection in web UI.
- **P4 Folder batch**: LOW PRIORITY. Could accept ZIP upload, process each as separate job. Defer for now.
---
### Workflow Control
| # | Parameter | Local | Remote | Description |
|---|-----------|-------|--------|-------------|
| W1 | `--prep-only` | ✅ | ❌ | **Stop after preparation phase.** Downloads audio, separates stems, transcribes lyrics, creates title/end screens, but does NOT run finalisation (encoding, YouTube upload, etc.). Useful for reviewing intermediate outputs before committing to final render. |
| W2 | `--finalise-only` | ✅ | ❌ | **Run only finalisation phase.** Must be run from a directory that was previously prepared with `--prep-only`. Picks up where prep left off: encodes videos, creates CDG/TXT packages, uploads to YouTube/Dropbox, etc. |
| W3 | `--skip-transcription` | ✅ | ❌ | **Skip automatic lyrics transcription.** Skips the AudioShake transcription and auto-correction steps. Use this if you want to manually provide lyrics or if transcription keeps failing. Lyrics review UI will still open if you have existing lyrics files. |
| W4 | `--skip-separation` | ✅ | ❌ | **Skip audio separation.** Skips the AI-powered stem separation (Modal API). Useful when re-processing a track where you already have the stems from a previous run, or when combined with `--existing_instrumental`. |
| W5 | `--skip-lyrics` | ✅ | ❌ | **Skip all lyrics processing.** Skips fetching lyrics from Genius/Spotify, transcription, and review. Output will have no lyrics overlay - just instrumental video with title/end screens. |
| W6 | `--lyrics-only` | ✅ | ❌ | **Process only lyrics.** Sets `--skip-separation` and skips title/end screen generation. Useful for re-doing just the lyrics on an existing track without re-running expensive audio separation. |
| W7 | `--edit-lyrics` | ✅ | ❌ | **Edit lyrics of existing track.** Run from inside an existing track directory (e.g., `NOMAD-1234 - Artist - Title/`). Backs up existing outputs, re-runs lyrics transcription with the existing audio, then re-renders and re-uploads. Uses `--keep-brand-code` implicitly. |
| W8 | `--resume` | N/A | 🔹 | **Resume monitoring a job.** Reconnects to an existing remote job and continues monitoring its progress, handling review/instrumental selection if needed. |
| W9 | `--cancel` | N/A | 🔹 | **Cancel a running job.** Stops processing but keeps the job record in Firestore. Useful for aborting stuck jobs. |
| W10 | `--retry` | N/A | 🔹 | **Retry a failed job.** Restarts processing from the last successful checkpoint. Only works on jobs with `failed` status. |
| W11 | `--delete` | N/A | 🔹 | **Delete a job.** Permanently removes job record from Firestore and all associated files from GCS. |
| W12 | `--list` | N/A | 🔹 | **List all jobs.** Shows all jobs with their status, artist, title. Supports filtering with `--filter-environment` and `--filter-client-id`. |
**Remote Implementation Plan:**
- **W1 `--prep-only`**: HIGH PRIORITY. Remote CLI submits job with `prep_only=true`. Backend runs all prep tasks (audio separation, lyrics transcription with review UI, initial render). After completion, CLI downloads the entire output folder and exits. No finalisation (encoding, YouTube, Dropbox, etc.) runs. Use case: Client needs custom edits to stems or lyrics before final render.
- **W2 `--finalise-only`**: HIGH PRIORITY. Remote CLI checks current directory for expected prep output files. Uploads ALL files from that folder to backend (including any manual customizations user made since prep). Backend runs finalisation and distribution steps. Use case: User edited instrumental manually, now wants cloud to handle encoding/distribution.
- **W3-W6 Skip flags**: LOW PRIORITY. Rarely used; typically all together to regenerate title/end screens with different artist/title. Defer until pipeline refactor provides cleaner stage-targeting.
- **W7 `--edit-lyrics`**: MEDIUM PRIORITY. Re-runs lyrics worker with existing audio/stems. Creates NEW YouTube upload (doesn't delete/replace existing). Backend should handle gracefully if video with identical title already exists (user will have manually deleted old one). Use case: Customer found typo in published video.
---
### Logging & Debugging
| # | Parameter | Local | Remote | Description |
|---|-----------|-------|--------|-------------|
| D1 | `--log_level` | ✅ | ✅ | **Set logging verbosity.** Options: `debug`, `info`, `warning`, `error`. Default: `info`. Affects console output detail level. |
| D2 | `--dry_run` | ✅ | ❌ | **Simulate without changes.** Runs through the workflow logic but doesn't actually download, process, or create files. Useful for testing argument combinations. |
| D3 | `--render_bounding_boxes` | ✅ | ❌ | **Debug text positioning.** Renders red bounding boxes around text regions in title/end screen images. Helps debug custom style configurations. |
**Remote Implementation Plan:**
- **D2 `--dry_run`**: LOW PRIORITY. Backend could accept `dry_run=true`, validate inputs and return what WOULD happen without processing. Nice to have for testing.
- **D3 `--render_bounding_boxes`**: LOW PRIORITY. Backend could enable this, useful for testing styles before full render. Nice to have for debugging style configs.
---
### Input/Output Configuration
| # | Parameter | Local | Remote | Description |
|---|-----------|-------|--------|-------------|
| I1 | `--filename_pattern` | ✅ | N/A | **Regex for batch processing.** Python regex with named group `(?P<title>...)` to extract track title from filenames. Used with folder input. Example: `'(?P<index>\d+) - (?P<title>.+).mp3'` |
| I2 | `--output_dir` | ✅ | ✅ | **Output directory.** Where to write output files. Local: creates subdirectory per track. Remote: where to download completed files. Default: current directory. |
| I3 | `--no_track_subfolders` | 🗑️ | N/A | **REMOVE FROM LOCAL CLI.** Flat output structure. Not needed - always create subfolders. |
| I4 | `--lossless_output_format` | 🗑️ | N/A | **REMOVE FROM LOCAL CLI.** Stem audio format. FLAC is always fine, no need for WAV option. |
| I5 | `--output_png` | 🗑️ | N/A | **REMOVE FROM LOCAL CLI.** Always output both PNG and JPG, no need for flag. |
| I6 | `--output_jpg` | 🗑️ | N/A | **REMOVE FROM LOCAL CLI.** Always output both PNG and JPG, no need for flag. |
**Remote Implementation Plan:**
- **I3, I4, I5, I6**: REMOVE from local CLI entirely. Not worth maintaining. Backend always uses FLAC, outputs both PNG+JPG, creates subfolders.
---
### Audio Fetching Configuration
| # | Parameter | Local | Remote | Description |
|---|-----------|-------|--------|-------------|
| A1 | `--auto-download` | ✅ | ❌ | **Auto-select audio source.** When using artist+title search mode (flacfetch), automatically select the best quality source instead of prompting for manual selection. Useful for scripted/batch processing. |
**Remote Implementation Plan:**
- **A1 `--auto-download`**: HIGH PRIORITY. Backend must support BOTH modes:
- **Interactive (default)**: API returns search results to client. Client displays options, user selects, client sends selection back to backend. Use case: Web UI will show audio source picker.
- **Auto-download (`--auto-download` or `-y`)**: Backend auto-selects best quality source. Use case: Automated/batch processing.
---
### Audio Processing Configuration
| # | Parameter | Local | Remote | Description |
|---|-----------|-------|--------|-------------|
| AP1 | `--clean_instrumental_model` | ✅ | ✅ | **Stage 1 separation model.** AI model for initial vocal/instrumental separation. Default: `model_bs_roformer_ep_317_sdr_12.9755.ckpt`. Different models have different quality/speed tradeoffs. |
| AP2 | `--backing_vocals_models` | ✅ | ✅ | **Stage 2 separation model(s).** AI model(s) for separating lead vocals from backing vocals. Default: `mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt`. |
| AP3 | `--other_stems_models` | ✅ | ✅ | **Multi-stem separation model.** AI model for separating drums, bass, guitar, piano, other. Default: `htdemucs_6s.yaml`. |
| AP4 | `--model_file_dir` | ✅ | N/A | **Model cache directory.** Where to store/load AI model files. Default: `/tmp/audio-separator-models/`. |
| AP5 | `--existing_instrumental` | ✅ | ✅ | **Use pre-made instrumental.** Path to an existing instrumental file to use instead of running AI separation. Useful when you have a better instrumental from another source (official instrumental release, manual editing, etc.). Backend still runs separation for stems, but uses provided instrumental for final video. |
| AP6 | `--instrumental_format` | 🗑️ | N/A | **REMOVE FROM LOCAL CLI.** FLAC is always fine, no need for format option. |
**Remote Implementation Status:** ✅ **BATCH 2 & 3 COMPLETE** (PR #9 v0.71.24, PR #10 v0.71.26)
- **AP1 `--clean_instrumental_model`**: ✅ IMPLEMENTED. Sent as form field to backend. Audio worker passes to Modal API.
- **AP2 `--backing_vocals_models`**: ✅ IMPLEMENTED. Sent as comma-separated list, parsed and passed to Modal API.
- **AP3 `--other_stems_models`**: ✅ IMPLEMENTED. Sent as comma-separated list, parsed and passed to Modal API.
- **AP4 `--model_file_dir`**: N/A for remote - Modal API handles model caching internally.
- **AP5 `--existing_instrumental`**: ✅ IMPLEMENTED (Batch 3). User uploads instrumental file with job. Backend validates duration match (±0.5s), still runs separation for stems, but uses provided instrumental for final video encoding.
- **AP6**: REMOVE from local CLI - FLAC is always fine.
---
### Lyrics Configuration
| # | Parameter | Local | Remote | Description |
|---|-----------|-------|--------|-------------|
| L1 | `--lyrics_artist` | ✅ | ✅ | **Override artist for lyrics search.** Use different artist name when searching Genius/Spotify/Musixmatch for lyrics. Useful for covers, remixes, or when artist name differs in lyrics databases. Example: `--lyrics_artist="The Beatles"` when your file says "Beatles, The". |
| L2 | `--lyrics_title` | ✅ | ✅ | **Override title for lyrics search.** Use different song title when searching for lyrics. Useful for songs with alternate titles, subtitle variations, or "(Remastered)" suffixes. Example: `--lyrics_title="Hey Jude"` when file says "Hey Jude - 2009 Remaster". |
| L3 | `--lyrics_file` | ✅ | ✅ | **Use existing lyrics file.** Path to a text file containing lyrics to use instead of fetching from online sources. Supports TXT, DOCX, RTF formats. Useful when online lyrics are wrong or unavailable. Transcription still runs to generate timestamps. |
| L4 | `--subtitle_offset_ms` | ✅ | ✅ | **Adjust subtitle timing.** Shift all subtitle timestamps by N milliseconds. Positive values delay subtitles, negative values advance them. Useful when audio has intro padding or sync drift. Example: `--subtitle_offset_ms=500` delays by 0.5 seconds. |
| L5 | `--skip_transcription_review` | ✅ | ⚠️ | **Skip review UI.** Don't open the browser-based lyrics review interface after transcription. Use existing auto-corrected lyrics as-is. Remote: use `-y` flag instead for non-interactive mode. |
**Remote Implementation Status:** ✅ **BATCH 1 COMPLETE** (PR #8, v0.71.22)
- **L1 `--lyrics_artist`**: ✅ IMPLEMENTED. Sent as form field to backend. Lyrics worker uses for Genius/Spotify/AudioShake queries.
- **L2 `--lyrics_title`**: ✅ IMPLEMENTED. Sent as form field to backend. Lyrics worker uses for search instead of main title.
- **L3 `--lyrics_file`**: ✅ IMPLEMENTED. Uploaded with job, stored in GCS. Lyrics worker reads it instead of fetching online.
- **L4 `--subtitle_offset_ms`**: ✅ IMPLEMENTED. Sent to backend, render worker applies offset when burning subtitles.
- **L5 `--skip_transcription_review`**: Already works via `-y` flag which auto-accepts corrections.
---
### Style Configuration
| # | Parameter | Local | Remote | Description |
|---|-----------|-------|--------|-------------|
| S1 | `--style_params_json` | ✅ | ✅ | **Style configuration file.** Path to JSON file defining visual style: background images, fonts, colors, text positioning for intro/karaoke/end screens and CDG. All referenced image/font files are auto-uploaded in remote mode. |
| S2 | `--style_override` | ✅ | ❌ | **Quick style tweaks.** Override specific style parameters without editing JSON. Can be used multiple times. Format: `section.key=value`. Example: `--style_override 'intro.background_image=/path/to/new_bg.png'`. Creates a temp JSON file with overrides merged. |
| S3 | `--background_video` | ✅ | ❌ | **Video background for karaoke.** Path to video file to use as animated background instead of static image for the karaoke section. Video is looped/trimmed to match audio duration, with lyrics overlaid. |
| S4 | `--background_video_darkness` | ✅ | ❌ | **Dim video background.** Darkness overlay percentage (0-100) applied to video background so lyrics are more readable. 0 = no darkening, 100 = completely black. Default: 0. |
**Remote Implementation Plan:**
- **S2 `--style_override`**: MEDIUM PRIORITY. Send override strings to backend, merge server-side before passing to workers. Works same as local (creates merged config). Use case: Web UI will let users tweak font colors etc., needs to pass adjustments to backend.
- **S3 `--background_video`**: MEDIUM PRIORITY. Upload video file with job. Backend processes with VideoBackgroundProcessor (loop/trim to audio duration). Requires larger file upload limits. Future: Web UI could allow YouTube URL or direct upload for video background.
- **S4 `--background_video_darkness`**: Depends on S3. Send percentage to backend, apply overlay during video processing.
---
### Finalisation Configuration
| # | Parameter | Local | Remote | Description |
|---|-----------|-------|--------|-------------|
| F1 | `--enable_cdg` | ✅ | ✅ | **Generate CDG+MP3 package.** Create CD+Graphics karaoke format files (used by karaoke machines). Produces ZIP containing `.cdg` and `.mp3` files. Requires `cdg` section in style_params_json. |
| F2 | `--enable_txt` | ✅ | ✅ | **Generate TXT+MP3 package.** Create text-based karaoke format with timed lyrics. Produces ZIP containing `.txt` (with timestamps) and `.mp3` files. |
| F3 | `--brand_prefix` | ✅ | ✅ | **Brand code prefix.** Your brand identifier for sequential numbering. When set, output folder is renamed to `PREFIX-XXXX - Artist - Title` where XXXX is the next sequential number found in `organised_dir` or Dropbox. Example: `NOMAD` produces `NOMAD-1234`. |
| F4 | `--organised_dir` | ✅ | N/A | **Local organized output.** Local filesystem path where final track folders are moved after processing. Used with `--brand_prefix` to maintain organized library. Example: `/Volumes/Media/Karaoke/Tracks-Organized/`. |
| F5 | `--organised_dir_rclone_root` | ✅ | ✅ | **Rclone path for Dropbox.** Rclone remote path that maps to your organised_dir. Used to calculate next brand code number and for rclone-based uploads. Example: `dropbox:Media/Karaoke/Tracks-Organized`. |
| F6 | `--public_share_dir` | ✅ | N/A | **Local public share folder.** Local filesystem path where shareable versions (720p video, CDG, TXT) are copied for public distribution. |
| F7 | `--enable_youtube_upload` | ✅ | ✅ | **Upload to YouTube.** After encoding, upload the lossy 4K video to YouTube. Local: uses OAuth flow with client secrets. Remote: uses server-side stored credentials. |
| F8 | `--youtube_client_secrets_file` | ✅ | N/A | **YouTube OAuth credentials.** Local path to Google OAuth client secrets JSON file for YouTube API. Only needed for local mode - remote uses server-stored credentials. |
| F9 | `--youtube_description_file` | ✅ | ✅ | **YouTube video description.** Path to text file containing YouTube video description template. Supports placeholders like `{artist}`, `{title}`, `{brand_code}`. |
| F10 | `--rclone_destination` | ✅ | N/A | **Rclone sync destination.** Rclone remote path to sync public_share_dir to. Used for Google Drive public sharing. Example: `googledrive:KaraokePublic`. |
| F11 | `--dropbox_path` | N/A | 🔹 | **Dropbox folder (native API).** Remote-only: Dropbox folder path for organized output upload using native Dropbox API. Example: `/Karaoke/Tracks-Organized`. |
| F12 | `--gdrive_folder_id` | N/A | 🔹 | **Google Drive folder (native API).** Remote-only: Google Drive folder ID for public share uploads using native API. Example: `1abc123xyz`. |
| F13 | `--discord_webhook_url` | ✅ | ✅ | **Discord notification.** Webhook URL for sending completion notifications to Discord. Posts message with track info, brand code, and links. |
| F14 | `--email_template_file` | ✅ | ❌ | **Email draft template.** Path to email template file for creating Gmail drafts with track info. Supports placeholders. Uses pyperclip for manual email composition. |
| F15 | `--keep-brand-code` | ✅ | ❌ | **Preserve existing brand code.** When run from an existing track directory (with brand code in folder name), use that brand code instead of calculating a new one. Implicitly enabled with `--edit-lyrics`. |
| F16 | `-y` / `--yes` | ✅ | ✅ | **Non-interactive mode.** Auto-accept all prompts: lyrics corrections, instrumental selection, confirmations. Useful for automated/CI pipelines. Remote: auto-completes review, selects clean instrumental. |
| F17 | `--test_email_template` | ✅ | N/A | **Test email template.** Debug mode: test the email template rendering with fake data without processing any track. |
**Remote Implementation Plan:**
- **F14 `--email_template_file`**: MEDIUM PRIORITY. Two behaviors needed:
1. **Finalisation**: Same as local - use template to create Gmail draft (requires Gmail API OAuth). User just changes recipient and sends.
2. **API endpoint**: Expose endpoint to fetch templated message text for a job. Use case: Web frontend button to copy message for pasting into Fiverr, etc.
- **F15 `--keep-brand-code`**: HIGH PRIORITY (for `--finalise-only` workflow). When using `--finalise-only` remotely, user may be re-processing an already-published track. Must preserve existing brand code so updated files overwrite in Dropbox/GDrive rather than creating new sequence number. Implementation: Remote CLI reads brand code from local folder name, sends to backend.
---
### Remote CLI Specific Options
| # | Parameter | Local | Remote | Description |
|---|-----------|-------|--------|-------------|
| R1 | `--service-url` | N/A | 🔹 | **Backend service URL.** URL of the karaoke-gen cloud backend. Can also be set via `KARAOKE_GEN_URL` environment variable. Required for remote mode. |
| R2 | `--review-ui-url` | N/A | 🔹 | **Lyrics review UI URL.** URL of the hosted lyrics review web application. Default: `https://lyrics.nomadkaraoke.com`. |
| R3 | `--poll-interval` | N/A | 🔹 | **Status poll frequency.** Seconds between job status checks while monitoring. Default: 5 seconds. |
| R4 | `--environment` | N/A | 🔹 | **Job environment tag.** Tag jobs with environment label (test/production/development) for filtering and cleanup. Sent as `X-Environment` header. |
| R5 | `--client-id` | N/A | 🔹 | **Client identifier tag.** Tag jobs with client/user identifier for filtering. Sent as `X-Client-ID` header. |
| R6 | `--filter-environment` | N/A | 🔹 | **Filter by environment.** When using `--list` or `--bulk-delete`, only show/delete jobs matching this environment. |
| R7 | `--filter-client-id` | N/A | 🔹 | **Filter by client ID.** When using `--list` or `--bulk-delete`, only show/delete jobs matching this client ID. |
| R8 | `--bulk-delete` | N/A | 🔹 | **Bulk delete jobs.** Delete all jobs matching filter criteria. Requires at least one filter (`--filter-environment` or `--filter-client-id`). |
---
## 🚀 Implementation Batches
The following batches are ordered by priority and grouped by similar functionality. Each batch is designed to be a self-contained unit of work that can be tackled by a single agent session.
### 📋 Instructions for Implementing a Batch
**Before starting a batch, ensure you follow these steps:**
#### 1. Test Coverage Requirements
All code changes must have **>70% test coverage** on modified files. Run:
```bash
python -m pytest backend/tests/ --cov=backend.models.job --cov=backend.api.routes.file_upload --cov=backend.workers.<worker_name> --cov-report=term-missing
```
**Required tests for each batch:**
- **Model changes:** Test new fields exist, have correct defaults, serialize properly
- **API changes:** Test form validation (valid/invalid inputs), file upload handling
- **Worker changes:** Test parameter passing, configuration, error handling
- **CLI changes:** Test submit_job() passes parameters correctly
#### 2. Documentation Updates (REQUIRED)
As part of your PR, you MUST update this document:
- [ ] Update the **Quick Parity Summary** table to reflect new parity percentages
- [ ] Mark parameters as ✅ in the relevant **CLI Parameter Parity Analysis** section
- [ ] Update **Remote Implementation Plan/Status** to show ✅ IMPLEMENTED
- [ ] Mark the batch as **✅ COMPLETE** with PR number in the **Summary Table**
- [ ] Add entry to **Recently Completed** table with version and PR number
- [ ] Remove items from **Not Yet Implemented** list
#### 3. Version Bump
Bump the patch version in `pyproject.toml` before committing.
#### 4. PR Requirements
- Title: `feat: Batch N - <description>`
- Include: Summary of changes, files modified, tests added
- Link to this document in PR description
---
### Batch 1: Lyrics Configuration (HIGH) ✅ COMPLETE
**Parameters:** L1 `--lyrics_artist`, L2 `--lyrics_title`, L3 `--lyrics_file`, L4 `--subtitle_offset_ms`
**Status:** ✅ **IMPLEMENTED** - PR #8 merged (v0.71.22)
**Implementation Summary:**
- Remote CLI: Added 4 form fields to `submit_job()`, uploads lyrics file if provided
- Backend: Added 4 Form parameters to `/api/jobs/upload` endpoint
- Backend: Lyrics worker downloads user lyrics file, passes overrides to LyricsProcessor
- Backend: Render worker applies subtitle offset via OutputConfig
**Files modified:**
- `karaoke_gen/utils/remote_cli.py` - submit_job() with lyrics params
- `backend/api/routes/file_upload.py` - Form fields + lyrics file upload
- `backend/models/job.py` - lyrics_artist, lyrics_title, lyrics_file_gcs_path, subtitle_offset_ms fields
- `backend/workers/lyrics_worker.py` - override values passed to LyricsProcessor
- `backend/workers/render_video_worker.py` - subtitle_offset_ms applied
**Tests added:** 25+ unit tests covering lyrics file validation, Job model fields, worker configuration
**Complexity:** Low-Medium (straightforward form fields + file upload)
---
### Batch 2: Audio Separation Model Selection (HIGH) ✅ COMPLETE
**Parameters:** AP1 `--clean_instrumental_model`, AP2 `--backing_vocals_models`, AP3 `--other_stems_models`
**Status:** ✅ **IMPLEMENTED** - PR #9 merged (v0.71.24)
**Implementation Summary:**
- Remote CLI: Added 3 form fields to `submit_job()`, sends models as comma-separated strings
- Backend: Added 3 Form parameters to `/api/jobs/upload` endpoint, parses comma-separated lists
- Backend: Job model stores model configuration as optional fields
- Backend: Audio worker passes model names to AudioProcessor which uses Modal API
**Files modified:**
- `karaoke_gen/utils/remote_cli.py` - submit_job() with model params
- `backend/api/routes/file_upload.py` - Form fields + comma parsing
- `backend/models/job.py` - clean_instrumental_model, backing_vocals_models, other_stems_models fields
- `backend/workers/audio_worker.py` - create_audio_processor() accepts model params from job
**Tests added:** 15+ unit tests covering Job model fields, form parsing, AudioProcessor configuration
**Complexity:** Low (Modal API already supports dynamic model selection)
---
### Batch 3: Existing Instrumental Support (HIGH) ✅ COMPLETE
**Parameters:** AP5 `--existing_instrumental`
**Status:** ✅ **IMPLEMENTED** - PR #10 merged (v0.71.26)
**Implementation Summary:**
- Remote CLI: Added `--existing_instrumental` parameter, uploads file as `existing_instrumental` type
- Backend: Added `existing_instrumental` to VALID_FILE_TYPES with audio extension validation
- Backend: Duration validation (±0.5s tolerance) at uploads-complete endpoint using pydub
- Backend: Job model has `existing_instrumental_gcs_path` field
- Backend: Video worker downloads user-provided instrumental if present, uses it for final encoding
**Files modified:**
- `karaoke_gen/utils/remote_cli.py` - submit_job() with existing_instrumental param
- `backend/api/routes/file_upload.py` - VALID_FILE_TYPES, GCS path generation, duration validation
- `backend/models/job.py` - existing_instrumental_gcs_path field
- `backend/workers/video_worker.py` - downloads and uses user-provided instrumental
**Tests added:** 20+ unit tests covering model fields, file type validation, GCS path generation, duration validation
**Complexity:** Medium (file upload + validation + conditional logic)
---
### Batch 4: YouTube URL Input (HIGH)
**Parameters:** P2 `<url>` (YouTube/online URL)
**Scope:**
- Remote CLI: Detect URL input, send URL instead of file
- Backend: Accept URL as alternative to file upload
- Backend: Download audio using yt-dlp, extract metadata
- Docker: Add yt-dlp to container image
**Files to modify:**
- `karaoke_gen/utils/remote_cli.py` - detect URL, change submission flow
- `backend/api/routes/file_upload.py` - accept URL parameter
- `backend/workers/audio_worker.py` or new `download_worker.py` - yt-dlp download
- `backend/Dockerfile` - add yt-dlp
**Complexity:** Medium-High (new input mode, container changes, rate limiting considerations)
---
### Batch 5: Flacfetch Audio Search (HIGH)
**Parameters:** P3 `<artist> <title>` (search mode), A1 `--auto-download`
**Scope:**
- Remote CLI: Detect artist+title without file, trigger search flow
- Backend: New endpoint to search for audio sources via flacfetch
- Backend: Return search results to client for interactive selection
- Remote CLI: Display results, let user select, send selection back
- Backend: Download selected audio, proceed with job
- Support `--auto-download` / `-y` to skip interactive selection
**Files to modify:**
- `karaoke_gen/utils/remote_cli.py` - search flow, display results, selection
- `backend/api/routes/` - new search endpoint
- `backend/services/` - flacfetch integration service
- `backend/workers/` - download from selected source
**Complexity:** High (new interactive API flow, new service integration)
---
### Batch 6: Two-Phase Workflow (HIGH)
**Parameters:** W1 `--prep-only`, W2 `--finalise-only`, F15 `--keep-brand-code`
**Scope:**
- **prep-only:** Remote CLI submits with `prep_only=true`. Backend runs through review, then stops. CLI downloads all outputs and exits.
- **finalise-only:** Remote CLI checks local folder for prep outputs, uploads ALL files, sends `finalise_only=true`. Backend runs finalisation only.
- **keep-brand-code:** Remote CLI extracts brand code from local folder name, sends to backend to preserve.
**Files to modify:**
- `karaoke_gen/utils/remote_cli.py` - prep-only flow, finalise-only upload flow, brand code extraction
- `backend/api/routes/file_upload.py` - accept prep_only, finalise_only flags
- `backend/api/routes/` - new endpoint for finalise-only upload (multiple files)
- `backend/workers/orchestrator.py` or job state machine - conditional worker execution
**Complexity:** High (significant workflow changes, new upload flow)
---
### Batch 7: Style Overrides (MEDIUM)
**Parameters:** S2 `--style_override`
**Scope:**
- Remote CLI: Parse override strings, send as array to backend
- Backend: Accept style_override array
- Backend: Merge overrides with uploaded style JSON before processing
- Handle asset references in overrides (upload referenced files)
**Files to modify:**
- `karaoke_gen/utils/remote_cli.py` - parse and send overrides
- `backend/api/routes/file_upload.py` - accept overrides
- `backend/services/style_service.py` or similar - merge logic
**Complexity:** Medium (string parsing, merge logic, asset handling)
---
### Batch 8: Video Background (MEDIUM)
**Parameters:** S3 `--background_video`, S4 `--background_video_darkness`
**Scope:**
- Remote CLI: Upload video file (larger file support needed)
- Backend: Accept video upload, store in GCS
- Backend: Render worker uses VideoBackgroundProcessor
- Backend: Apply darkness overlay
**Files to modify:**
- `karaoke_gen/utils/remote_cli.py` - upload video file
- `backend/api/routes/file_upload.py` - accept video upload (larger limits)
- `backend/workers/render_worker.py` - integrate VideoBackgroundProcessor
**Complexity:** Medium (large file upload, video processing)
---
### Batch 9: Edit Lyrics Mode (MEDIUM)
**Parameters:** W7 `--edit-lyrics`
**Scope:**
- Remote CLI: Accept job_id for existing job, trigger edit mode
- Backend: Load existing job's audio/stems from GCS
- Backend: Re-run lyrics worker only
- Backend: Re-render with new lyrics
- Backend: Create NEW YouTube upload (handle duplicate title gracefully)
**Files to modify:**
- `karaoke_gen/utils/remote_cli.py` - edit mode flow
- `backend/api/routes/` - edit endpoint or flag
- `backend/workers/orchestrator.py` - partial re-processing logic
**Complexity:** Medium-High (partial re-processing, state management)
---
### Batch 10: Email Template + Cleanup (LOW)
**Parameters:** F14 `--email_template_file`, D2 `--dry_run`, D3 `--render_bounding_boxes`
**Removal:** I3 `--no_track_subfolders`, I4 `--lossless_output_format`, I5 `--output_png`, I6 `--output_jpg`, AP6 `--instrumental_format`
**Scope:**
- **Email template:** Upload template, backend creates Gmail draft + new API endpoint to fetch formatted text
- **Dry run:** Backend validates inputs, returns plan without executing
- **Bounding boxes:** Enable debug rendering in screens worker
- **Removal:** Remove 5 unnecessary CLI flags from local CLI
**Files to modify:**
- `karaoke_gen/utils/cli_args.py` - remove flags
- `karaoke_gen/utils/remote_cli.py` - email template upload
- `backend/api/routes/` - email template endpoint
- `backend/services/email_service.py` - Gmail API integration
**Complexity:** Mixed (Gmail OAuth is complex, removals are simple)
---
### Summary Table
| Batch | Parameters | Priority | Complexity | Status |
|-------|------------|----------|------------|--------|
| 1 | L1-L4 (lyrics config) | HIGH | Low-Medium | ✅ **COMPLETE** (PR #8) |
| 2 | AP1-AP3 (model selection) | HIGH | Low | ✅ **COMPLETE** (PR #9) |
| 3 | AP5 (existing instrumental) | HIGH | Medium | ✅ **COMPLETE** (PR #10) |
| 4 | P2 (YouTube URLs) | HIGH | Medium-High | ⏳ Pending |
| 5 | P3, A1 (flacfetch search) | HIGH | High | ⏳ Pending |
| 6 | W1, W2, F15 (two-phase) | HIGH | High | ⏳ Pending |
| 7 | S2 (style overrides) | MEDIUM | Medium | ⏳ Pending |
| 8 | S3, S4 (video background) | MEDIUM | Medium | ⏳ Pending |
| 9 | W7 (edit-lyrics) | MEDIUM | Medium-High | ⏳ Pending |
| 10 | F14, D2, D3, removals | LOW | Mixed | ⏳ Pending |
**Recommended Order:** ~~1~~ → ~~2~~ → ~~3~~ → 4 → 5 → 6 → 7 → 8 → 9 → 10
Batches 1-3 are quick wins that add significant value. Batches 4-6 are larger but high priority. Batches 7-10 can be done as time permits.
---
## ✅ Implementation Decisions (Answered 2024-12-10)
All questions have been answered and incorporated into the "Remote Implementation Plan" sections above. Summary of key decisions:
### Workflow Control
- **W1/W2**: YES, two-phase workflow needed. `--prep-only` downloads all prep outputs after review, `--finalise-only` uploads local folder (with any manual edits) for cloud finalisation.
- **W3-W6 Skip flags**: LOW PRIORITY - rarely used, defer until pipeline refactor provides cleaner stage-targeting.
- **W7 Edit-lyrics**: Creates NEW YouTube upload (user deletes old one manually). Backend handles duplicate title gracefully.
### Input Modes
- **P2 YouTube**: HIGH PRIORITY - needed for niche live versions only on YouTube.
- **P3 Flacfetch**: HIGH PRIORITY - MUST be interactive via API (not auto-select) for future web UI audio source picker.
### Audio Processing
- **AP1-AP3 Models**: HIGH PRIORITY - all model options must work remotely (Modal API can load any model on demand).
- **AP5 Existing Instrumental**: Still run separation (for consistent stem downloads), but use provided instrumental for final video. Validate duration match (±0.5s) at job start before proceeding.
### I/O & Audio Format Options
- **I3, I4, I5, I6, AP6**: REMOVE from local CLI entirely - unnecessary options, simplifies codebase.
### Audio Fetching
- **A1 `--auto-download`**: Backend must support BOTH interactive (default, for web UI) AND auto-select (with `-y` flag) modes.
### Style
- **S2 Style Override**: MEDIUM PRIORITY - needed for web UI style tweaks (font colors, etc.).
- **S3/S4 Background Video**: MEDIUM PRIORITY - implement, will eventually allow YouTube URL or direct upload in web UI.
### Finalisation
- **F14 Email Template**: BOTH - create Gmail draft (like local) AND expose API endpoint to fetch templated text (for Fiverr copy-paste).
- **F15 Keep-brand-code**: HIGH PRIORITY for `--finalise-only` workflow - preserves brand code so updates overwrite existing Dropbox/GDrive files.
---
## Vision
The karaoke-gen system supports multiple interfaces to the same core functionality:
@@ -105,14 +622,27 @@ The karaoke-gen system supports multiple interfaces to the same core functionali
| Google Drive upload | ✅ | Service account credentials |
| Discord notification | ✅ | Webhook URL from job or default |
### ⏳ Not Yet Implemented (Lower Priority)
### ✅ Recently Completed
| Feature | Version | PR | Notes |
|---------|---------|-----|-------|
| Existing instrumental | v0.71.26 | #10 | `--existing_instrumental` - upload and use user-provided instrumental |
| Audio model selection | v0.71.24 | #9 | `--clean_instrumental_model`, `--backing_vocals_models`, `--other_stems_models` |
| Lyrics override params | v0.71.22 | #8 | `--lyrics_artist`, `--lyrics_title`, `--lyrics_file`, `--subtitle_offset_ms` |
### ⏳ Not Yet Implemented
| Feature | Priority | Notes |
|---------|----------|-------|
| Style override | MEDIUM | `--style_override` for quick tweaks |
| Skip separation/transcription | MEDIUM | Workflow control for re-processing |
| Edit lyrics mode | MEDIUM | `--edit-lyrics` for fixing existing tracks |
| Background video | MEDIUM | `--background_video` requires video upload |
| YouTube URL input | HIGH | Requires yt-dlp in container |
| Audio search (flacfetch) | HIGH | Artist+title search, auto-download |
| Two-phase workflow | HIGH | `--prep-only`, `--finalise-only` |
| Batch folder processing | LOW | Process multiple files at once |
| Gmail draft creation | LOW | Nice-to-have, not blocking |
| YouTube URL input | LOW | Requires yt-dlp in container |
| Batch processing | LOW | Queue management needed |
| Existing instrumental support | LOW | For re-processing existing tracks |
---
@@ -355,6 +885,37 @@ DEFAULT_DISCORD_WEBHOOK_URL=https://discord.com/...
## Recent Changes Log
### 2024-12-11: v0.71.26 - Batch 3 Complete (Existing Instrumental Support)
**PR #10: Existing Instrumental Support for Remote CLI**
- ✅ `--existing_instrumental` - Upload and use user-provided instrumental file
- Duration validation (±0.5s tolerance) before processing starts
- Backend still runs AI separation for stem downloads, but uses provided instrumental for final video
- Added 20+ unit tests for new functionality
- Files: `remote_cli.py`, `file_upload.py`, `job.py`, `video_worker.py`
### 2024-12-11: v0.71.24 - Batch 2 Complete (Audio Model Selection)
**PR #9: Audio Model Selection for Remote CLI**
- ✅ `--clean_instrumental_model` - Custom Stage 1 separation model
- ✅ `--backing_vocals_models` - Custom backing vocals separation models
- ✅ `--other_stems_models` - Custom multi-stem separation models (bass, drums, etc.)
- Added 15+ unit tests for new functionality
- Files: `remote_cli.py`, `file_upload.py`, `job.py`, `audio_worker.py`
### 2024-12-10: v0.71.22 - Batch 1 Complete (Lyrics Configuration)
**PR #8: Lyrics Configuration for Remote CLI**
- ✅ `--lyrics_artist` - Override artist name for lyrics search
- ✅ `--lyrics_title` - Override title for lyrics search
- ✅ `--lyrics_file` - Upload custom lyrics file (TXT, DOCX, RTF)
- ✅ `--subtitle_offset_ms` - Adjust subtitle timing offset
- Added 25+ unit tests for new functionality
- Files: `remote_cli.py`, `file_upload.py`, `job.py`, `lyrics_worker.py`, `render_video_worker.py`
### 2024-12-10: v0.71.0 - Core Feature Parity Complete
**First successful end-to-end remote run!**
@@ -400,10 +961,41 @@ DEFAULT_DISCORD_WEBHOOK_URL=https://discord.com/...
2. ✅ Tag v0.71.0 release
3. Update PyPI package
### Short-Term
1. Monitor production usage
2. Address any edge cases found
3. Improve error messages and logging
### Short-Term: Feature Parity (Priority Order)
1. ✅ **Lyrics Configuration** (Batch 1 - COMPLETE)
- `--lyrics_artist`, `--lyrics_title`, `--lyrics_file`, `--subtitle_offset_ms`
- PR #8, v0.71.22
2. ✅ **Audio Model Selection** (Batch 2 - COMPLETE)
- `--clean_instrumental_model`, `--backing_vocals_models`, `--other_stems_models`
- PR #9, v0.71.24
3. ✅ **Existing Instrumental** (Batch 3 - COMPLETE)
- Added `--existing_instrumental` upload support
- PR #10, v0.71.26
4. **YouTube URL Input** (Batch 4 - NEXT)
- Accept YouTube URLs as input
- Requires: yt-dlp in container
- Enables: Processing niche live versions only on YouTube
### Medium-Term: Workflow Features
1. **Flacfetch Audio Search** (Batch 5)
- Interactive audio source selection via API
2. **Two-Phase Workflow** (Batch 6)
- `--prep-only` and `--finalise-only` modes
3. **Style Override** (Batch 7)
- Quick style tweaks without editing JSON
4. **Background Video Support** (Batch 8)
- Upload and use video backgrounds
5. **Edit Lyrics Mode** (Batch 9)
- Allow fixing lyrics on completed jobs
### Long-Term (Shared Pipeline Refactor)
1. Create new branch for shared pipeline architecture
@@ -268,6 +268,8 @@ class KaraokeFinalise:
# Enable discord notifications if webhook URL is provided and is valid URL
if self.discord_webhook_url is not None:
# Strip whitespace/newlines that may have been introduced from environment variables or secrets
self.discord_webhook_url = self.discord_webhook_url.strip()
if not self.discord_webhook_url.startswith("https://discord.com/api/webhooks/"):
raise Exception(f"Discord webhook URL is not valid: {self.discord_webhook_url}")
@@ -858,7 +860,7 @@ class KaraokeFinalise:
return env_mov_input, ffmpeg_filter
def remux_and_encode_output_video_files(self, with_vocals_file, input_files, output_files):
self.logger.info(f"Remuxing and encoding output video files...")
self.logger.info(f"Remuxing and encoding output video files (4 formats, ~15-20 minutes total)...")
# Check if output files already exist
if os.path.isfile(output_files["final_karaoke_lossless_mp4"]) and os.path.isfile(output_files["final_karaoke_lossless_mkv"]):
@@ -869,16 +871,20 @@ class KaraokeFinalise:
return
# Create karaoke version with instrumental audio
self.logger.info(f"[Step 1/6] Remuxing video with instrumental audio...")
self.remux_with_instrumental(with_vocals_file, input_files["instrumental_audio"], output_files["karaoke_mp4"])
# Convert the with vocals video to MP4 if needed
if not with_vocals_file.endswith(".mp4"):
self.logger.info(f"[Step 2/6] Converting karaoke video to MP4...")
self.convert_mov_to_mp4(with_vocals_file, output_files["with_vocals_mp4"])
# Delete the with vocals mov after successfully converting it to mp4
if not self.dry_run and os.path.isfile(with_vocals_file):
self.logger.info(f"Deleting with vocals MOV file: {with_vocals_file}")
os.remove(with_vocals_file)
else:
self.logger.info(f"[Step 2/6] Skipped - video already in MP4 format")
# Quote file paths to handle special characters
title_mov_file = shlex.quote(os.path.abspath(input_files["title_mov"]))
@@ -887,10 +893,17 @@ class KaraokeFinalise:
# Prepare concat filter for combining videos
env_mov_input, ffmpeg_filter = self.prepare_concat_filter(input_files)
# Create all output versions
# Create all output versions with progress logging
self.logger.info(f"[Step 3/6] Encoding lossless 4K MP4 (title + karaoke + end, ~5 minutes)...")
self.encode_lossless_mp4(title_mov_file, karaoke_mp4_file, env_mov_input, ffmpeg_filter, output_files["final_karaoke_lossless_mp4"])
self.logger.info(f"[Step 4/6] Encoding lossy 4K MP4 with AAC audio (~1 minute)...")
self.encode_lossy_mp4(output_files["final_karaoke_lossless_mp4"], output_files["final_karaoke_lossy_mp4"])
self.logger.info(f"[Step 5/6] Creating MKV with FLAC audio for YouTube (~1 minute)...")
self.encode_lossless_mkv(output_files["final_karaoke_lossless_mp4"], output_files["final_karaoke_lossless_mkv"])
self.logger.info(f"[Step 6/6] Encoding 720p version (~3 minutes)...")
self.encode_720p_version(output_files["final_karaoke_lossless_mp4"], output_files["final_karaoke_lossy_720p_mp4"])
# Skip user confirmation in non-interactive mode for Modal deployment
@@ -1298,8 +1311,13 @@ class KaraokeFinalise:
self.logger.error("YouTube upload failed in non-interactive mode, skipping")
# Discord notification - runs independently of YouTube upload
# Wrapped in try/except so failures don't crash the entire job
if self.discord_notication_enabled:
self.post_discord_notification()
try:
self.post_discord_notification()
except Exception as e:
self.logger.error(f"Failed to send Discord notification: {e}")
self.logger.warning("Continuing without Discord notification - this is non-fatal")
# Handle folder organization - different logic for server-side vs local mode
if self.server_side_mode and self.brand_prefix and self.organised_dir_rclone_root:
@@ -1661,11 +1679,17 @@ class KaraokeFinalise:
if self.dry_run:
self.logger.warning("Dry run enabled. No actions will be performed.")
self.logger.info("=" * 60)
self.logger.info("Starting KaraokeFinalise processing pipeline")
self.logger.info("=" * 60)
# Check required input files and parameters exist, get user to confirm features before proceeding
self.validate_input_parameters_for_features()
with_vocals_file = self.find_with_vocals_file()
base_name, artist, title = self.get_names_from_withvocals(with_vocals_file)
self.logger.info(f"Processing: {artist} - {title}")
# Use the selected instrumental file if provided, otherwise search for one
if self.selected_instrumental_file:
@@ -1681,13 +1705,20 @@ class KaraokeFinalise:
output_files = self.prepare_output_filenames(base_name)
if self.enable_cdg:
self.logger.info("Creating CDG package...")
self.create_cdg_zip_file(input_files, output_files, artist, title)
self.logger.info("CDG package created successfully")
if self.enable_txt:
self.logger.info("Creating TXT package...")
self.create_txt_zip_file(input_files, output_files)
self.logger.info("TXT package created successfully")
self.logger.info("Starting video encoding (this is the longest step, ~15-20 minutes)...")
self.remux_and_encode_output_video_files(with_vocals_file, input_files, output_files)
self.logger.info("Video encoding completed successfully")
self.logger.info("Executing distribution features (YouTube, Dropbox, Discord)...")
self.execute_optional_features(artist, title, base_name, input_files, output_files, replace_existing)
result = {
+5
View File
@@ -90,6 +90,11 @@ def create_parser(prog: str = "karaoke-gen") -> argparse.ArgumentParser:
metavar="JOB_ID",
help="Cancel a running job (remote mode only). Stops processing but keeps the job record. Example: --cancel abc12345",
)
workflow_group.add_argument(
"--retry",
metavar="JOB_ID",
help="Retry a failed job from the last successful checkpoint (remote mode only). Example: --retry abc12345",
)
workflow_group.add_argument(
"--delete",
metavar="JOB_ID",
+401 -87
View File
@@ -8,6 +8,7 @@ Set KARAOKE_GEN_URL environment variable to your cloud backend URL.
Usage:
karaoke-gen-remote <filepath> <artist> <title>
karaoke-gen-remote --resume <job_id>
karaoke-gen-remote --retry <job_id>
karaoke-gen-remote --list
karaoke-gen-remote --cancel <job_id>
karaoke-gen-remote --delete <job_id>
@@ -142,6 +143,70 @@ class RemoteKaraokeClient:
response = self.session.request(method, url, **kwargs)
return response
def _upload_file_to_signed_url(self, signed_url: str, file_path: str, content_type: str) -> bool:
"""
Upload a file directly to GCS using a signed URL.
Args:
signed_url: The signed URL from the backend
file_path: Local path to the file to upload
content_type: MIME type for the Content-Type header
Returns:
True if upload succeeded, False otherwise
"""
try:
with open(file_path, 'rb') as f:
# Use a fresh requests session (not self.session) because
# signed URLs should not have our auth headers
response = requests.put(
signed_url,
data=f,
headers={'Content-Type': content_type},
timeout=600 # 10 minutes for large files
)
if response.status_code in (200, 201):
return True
else:
self.logger.error(f"Failed to upload to signed URL: HTTP {response.status_code} - {response.text}")
return False
except Exception as e:
self.logger.error(f"Error uploading to signed URL: {e}")
return False
def _get_content_type(self, file_path: str) -> str:
"""Get the MIME content type for a file based on its extension."""
ext = Path(file_path).suffix.lower()
content_types = {
# Audio
'.mp3': 'audio/mpeg',
'.wav': 'audio/wav',
'.flac': 'audio/flac',
'.m4a': 'audio/mp4',
'.ogg': 'audio/ogg',
'.aac': 'audio/aac',
# Images
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
# Fonts
'.ttf': 'font/ttf',
'.otf': 'font/otf',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
# Other
'.json': 'application/json',
'.txt': 'text/plain',
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'.rtf': 'application/rtf',
}
return content_types.get(ext, 'application/octet-stream')
def _parse_style_params(self, style_params_path: str) -> Dict[str, str]:
"""
Parse style_params.json and extract file paths that need to be uploaded.
@@ -198,10 +263,26 @@ class RemoteKaraokeClient:
# Native API distribution (uses server-side credentials)
dropbox_path: Optional[str] = None,
gdrive_folder_id: Optional[str] = None,
# Lyrics configuration
lyrics_artist: Optional[str] = None,
lyrics_title: Optional[str] = None,
lyrics_file: Optional[str] = None,
subtitle_offset_ms: int = 0,
# Audio separation model configuration
clean_instrumental_model: Optional[str] = None,
backing_vocals_models: Optional[list] = None,
other_stems_models: Optional[list] = None,
# Existing instrumental (Batch 3)
existing_instrumental: Optional[str] = None,
) -> Dict[str, Any]:
"""
Submit a new karaoke generation job with optional style configuration.
Uses signed URL upload flow to bypass Cloud Run's 32MB request body limit:
1. Create job and get signed upload URLs from backend
2. Upload files directly to GCS using signed URLs
3. Notify backend that uploads are complete to start processing
Args:
filepath: Path to audio file
artist: Artist name
@@ -216,6 +297,14 @@ class RemoteKaraokeClient:
enable_youtube_upload: Enable YouTube upload
dropbox_path: Dropbox folder path for organized output (native API)
gdrive_folder_id: Google Drive folder ID for public share (native API)
lyrics_artist: Override artist name for lyrics search
lyrics_title: Override title for lyrics search
lyrics_file: Path to user-provided lyrics file
subtitle_offset_ms: Subtitle timing offset in milliseconds
clean_instrumental_model: Model for clean instrumental separation
backing_vocals_models: List of models for backing vocals separation
other_stems_models: List of models for other stems (bass, drums, etc.)
existing_instrumental: Path to existing instrumental file to use instead of AI separation
"""
file_path = Path(filepath)
@@ -229,95 +318,168 @@ class RemoteKaraokeClient:
f"Allowed: {', '.join(self.ALLOWED_AUDIO_EXTENSIONS)}"
)
self.logger.info(f"Uploading audio file: {filepath}")
# Step 1: Build list of files to upload
files_info = []
local_files = {} # file_type -> local_path
# Prepare files dict for multipart upload
files_to_upload = {}
files_to_close = []
# Main audio file
audio_content_type = self._get_content_type(filepath)
files_info.append({
'filename': file_path.name,
'content_type': audio_content_type,
'file_type': 'audio'
})
local_files['audio'] = filepath
self.logger.info(f"Will upload audio: {filepath}")
try:
# Main audio file
audio_file = open(filepath, 'rb')
files_to_close.append(audio_file)
files_to_upload['file'] = (file_path.name, audio_file)
# Parse style params and find referenced files
style_assets = {}
if style_params_path and os.path.isfile(style_params_path):
self.logger.info(f"Parsing style configuration: {style_params_path}")
style_assets = self._parse_style_params(style_params_path)
# Parse style params and find referenced files
style_assets = {}
if style_params_path and os.path.isfile(style_params_path):
self.logger.info(f"Parsing style configuration: {style_params_path}")
style_assets = self._parse_style_params(style_params_path)
# Upload style_params.json
style_file = open(style_params_path, 'rb')
files_to_close.append(style_file)
files_to_upload['style_params'] = (Path(style_params_path).name, style_file, 'application/json')
self.logger.info(f" Will upload style_params.json")
# Upload each style asset file
for asset_key, asset_path in style_assets.items():
if os.path.isfile(asset_path):
asset_file = open(asset_path, 'rb')
files_to_close.append(asset_file)
# Determine content type
ext = Path(asset_path).suffix.lower()
if ext in self.ALLOWED_IMAGE_EXTENSIONS:
content_type = f'image/{ext[1:]}'
elif ext in self.ALLOWED_FONT_EXTENSIONS:
content_type = 'font/ttf'
else:
content_type = 'application/octet-stream'
files_to_upload[asset_key] = (Path(asset_path).name, asset_file, content_type)
self.logger.info(f" Will upload {asset_key}: {asset_path}")
# Prepare form data
data = {
'artist': artist,
'title': title,
'enable_cdg': str(enable_cdg).lower(),
'enable_txt': str(enable_txt).lower(),
}
if brand_prefix:
data['brand_prefix'] = brand_prefix
if discord_webhook_url:
data['discord_webhook_url'] = discord_webhook_url
if youtube_description:
data['youtube_description'] = youtube_description
if enable_youtube_upload:
data['enable_youtube_upload'] = str(enable_youtube_upload).lower()
# Native API distribution (preferred for remote CLI)
if dropbox_path:
data['dropbox_path'] = dropbox_path
if gdrive_folder_id:
data['gdrive_folder_id'] = gdrive_folder_id
# Legacy rclone distribution (deprecated)
if organised_dir_rclone_root:
data['organised_dir_rclone_root'] = organised_dir_rclone_root
self.logger.info(f"Submitting job to {self.config.service_url}/api/jobs/upload")
response = self._request('POST', '/api/jobs/upload', files=files_to_upload, data=data)
finally:
# Close all opened files
for f in files_to_close:
try:
f.close()
except:
pass
# Add style_params.json
files_info.append({
'filename': Path(style_params_path).name,
'content_type': 'application/json',
'file_type': 'style_params'
})
local_files['style_params'] = style_params_path
self.logger.info(f" Will upload style_params.json")
# Add each style asset file
for asset_key, asset_path in style_assets.items():
if os.path.isfile(asset_path):
content_type = self._get_content_type(asset_path)
files_info.append({
'filename': Path(asset_path).name,
'content_type': content_type,
'file_type': asset_key # e.g., 'style_intro_background'
})
local_files[asset_key] = asset_path
self.logger.info(f" Will upload {asset_key}: {asset_path}")
# Add lyrics file if provided
if lyrics_file and os.path.isfile(lyrics_file):
content_type = self._get_content_type(lyrics_file)
files_info.append({
'filename': Path(lyrics_file).name,
'content_type': content_type,
'file_type': 'lyrics_file'
})
local_files['lyrics_file'] = lyrics_file
self.logger.info(f"Will upload lyrics file: {lyrics_file}")
# Add existing instrumental file if provided (Batch 3)
if existing_instrumental and os.path.isfile(existing_instrumental):
content_type = self._get_content_type(existing_instrumental)
files_info.append({
'filename': Path(existing_instrumental).name,
'content_type': content_type,
'file_type': 'existing_instrumental'
})
local_files['existing_instrumental'] = existing_instrumental
self.logger.info(f"Will upload existing instrumental: {existing_instrumental}")
# Step 2: Create job and get signed upload URLs
self.logger.info(f"Creating job at {self.config.service_url}/api/jobs/create-with-upload-urls")
create_request = {
'artist': artist,
'title': title,
'files': files_info,
'enable_cdg': enable_cdg,
'enable_txt': enable_txt,
}
if brand_prefix:
create_request['brand_prefix'] = brand_prefix
if discord_webhook_url:
create_request['discord_webhook_url'] = discord_webhook_url
if youtube_description:
create_request['youtube_description'] = youtube_description
if enable_youtube_upload:
create_request['enable_youtube_upload'] = enable_youtube_upload
if dropbox_path:
create_request['dropbox_path'] = dropbox_path
if gdrive_folder_id:
create_request['gdrive_folder_id'] = gdrive_folder_id
if organised_dir_rclone_root:
create_request['organised_dir_rclone_root'] = organised_dir_rclone_root
if lyrics_artist:
create_request['lyrics_artist'] = lyrics_artist
if lyrics_title:
create_request['lyrics_title'] = lyrics_title
if subtitle_offset_ms != 0:
create_request['subtitle_offset_ms'] = subtitle_offset_ms
if clean_instrumental_model:
create_request['clean_instrumental_model'] = clean_instrumental_model
if backing_vocals_models:
create_request['backing_vocals_models'] = backing_vocals_models
if other_stems_models:
create_request['other_stems_models'] = other_stems_models
response = self._request('POST', '/api/jobs/create-with-upload-urls', json=create_request)
if response.status_code != 200:
try:
error_detail = response.json()
except Exception:
error_detail = response.text
raise RuntimeError(f"Error submitting job: {error_detail}")
raise RuntimeError(f"Error creating job: {error_detail}")
create_result = response.json()
if create_result.get('status') != 'success':
raise RuntimeError(f"Error creating job: {create_result}")
job_id = create_result['job_id']
upload_urls = create_result['upload_urls']
self.logger.info(f"Job {job_id} created. Uploading {len(upload_urls)} files directly to storage...")
# Step 3: Upload each file directly to GCS using signed URLs
uploaded_files = []
for url_info in upload_urls:
file_type = url_info['file_type']
signed_url = url_info['upload_url']
content_type = url_info['content_type']
local_path = local_files.get(file_type)
if not local_path:
self.logger.warning(f"No local file found for file_type: {file_type}")
continue
# Calculate file size for logging
file_size = os.path.getsize(local_path)
file_size_mb = file_size / (1024 * 1024)
self.logger.info(f" Uploading {file_type} ({file_size_mb:.1f} MB)...")
success = self._upload_file_to_signed_url(signed_url, local_path, content_type)
if not success:
raise RuntimeError(f"Failed to upload {file_type} to storage")
uploaded_files.append(file_type)
self.logger.info(f" ✓ Uploaded {file_type}")
# Step 4: Notify backend that uploads are complete
self.logger.info(f"Notifying backend that uploads are complete...")
complete_request = {
'uploaded_files': uploaded_files
}
response = self._request('POST', f'/api/jobs/{job_id}/uploads-complete', json=complete_request)
if response.status_code != 200:
try:
error_detail = response.json()
except Exception:
error_detail = response.text
raise RuntimeError(f"Error completing uploads: {error_detail}")
result = response.json()
if result.get('status') != 'success':
raise RuntimeError(f"Error submitting job: {result}")
raise RuntimeError(f"Error completing uploads: {result}")
# Log distribution services info if available
if 'distribution_services' in result:
@@ -383,7 +545,25 @@ class RemoteKaraokeClient:
if response.status_code != 200:
raise RuntimeError(f"Error deleting job: {response.text}")
return response.json()
def retry_job(self, job_id: str) -> Dict[str, Any]:
"""Retry a failed job from the last successful checkpoint."""
response = self._request(
'POST',
f'/api/jobs/{job_id}/retry'
)
if response.status_code == 404:
raise ValueError(f"Job not found: {job_id}")
if response.status_code == 400:
try:
error_detail = response.json().get('detail', response.text)
except Exception:
error_detail = response.text
raise RuntimeError(f"Cannot retry job: {error_detail}")
if response.status_code != 200:
raise RuntimeError(f"Error retrying job: {response.text}")
return response.json()
def list_jobs(
self,
status: Optional[str] = None,
@@ -591,6 +771,40 @@ class JobMonitor:
self._last_timeline_index = 0
self._last_log_index = 0
self._show_worker_logs = True # Enable worker log display
self._polls_without_updates = 0 # Track polling activity for heartbeat
self._heartbeat_interval = 6 # Show heartbeat every N polls without updates (~30s with 5s poll)
# Status descriptions for user-friendly logging
STATUS_DESCRIPTIONS = {
'pending': 'Job queued, waiting to start',
'downloading': 'Downloading and preparing input files',
'separating_stage1': 'AI audio separation (stage 1 of 2)',
'separating_stage2': 'AI audio separation (stage 2 of 2)',
'audio_complete': 'Audio separation complete',
'transcribing': 'Transcribing lyrics from audio',
'correcting': 'Auto-correcting lyrics against reference sources',
'lyrics_complete': 'Lyrics processing complete',
'generating_screens': 'Creating title and end screens',
'applying_padding': 'Adding intro/outro padding',
'awaiting_review': 'Waiting for lyrics review',
'in_review': 'Lyrics review in progress',
'review_complete': 'Review complete, preparing video render',
'rendering_video': 'Rendering karaoke video with lyrics',
'awaiting_instrumental_selection': 'Waiting for instrumental selection',
'instrumental_selected': 'Instrumental selected, preparing final encoding',
'generating_video': 'Downloading files for final video encoding',
'encoding': 'Encoding final videos (15-20 min, 4 formats)',
'packaging': 'Creating CDG/TXT packages',
'uploading': 'Uploading to distribution services',
'notifying': 'Sending notifications',
'complete': 'All processing complete',
'failed': 'Job failed',
'cancelled': 'Job cancelled',
}
def _get_status_description(self, status: str) -> str:
"""Get user-friendly description for a status."""
return self.STATUS_DESCRIPTIONS.get(status, status)
def open_browser(self, url: str) -> None:
"""Open URL in the default browser."""
@@ -1082,6 +1296,7 @@ class JobMonitor:
self.logger.info(f"Monitoring job: {job_id}")
self.logger.info(f"Service URL: {self.config.service_url}")
self.logger.info(f"Polling every {self.config.poll_interval} seconds...")
self.logger.info("")
while True:
@@ -1092,16 +1307,40 @@ class JobMonitor:
artist = job_data.get('artist', '')
title = job_data.get('title', '')
# Track whether we got any new updates this poll
had_updates = False
prev_timeline_index = self._last_timeline_index
prev_log_index = self._last_log_index
# Log timeline updates (shows status changes and progress)
self.log_timeline_updates(job_data)
if self._last_timeline_index > prev_timeline_index:
had_updates = True
# Log worker logs (shows detailed worker output for debugging)
self.log_worker_logs(job_id)
if self._last_log_index > prev_log_index:
had_updates = True
# Log status changes
# Log status changes with user-friendly descriptions
if status != last_status:
self.logger.info(f"Status changed: {last_status} -> {status}")
description = self._get_status_description(status)
if last_status:
self.logger.info(f"Status: {status} - {description}")
else:
self.logger.info(f"Current status: {status} - {description}")
last_status = status
had_updates = True
# Heartbeat: if no updates for a while, show we're still alive
if had_updates:
self._polls_without_updates = 0
else:
self._polls_without_updates += 1
if self._polls_without_updates >= self._heartbeat_interval:
description = self._get_status_description(status)
self.logger.info(f" [Still processing: {description}]")
self._polls_without_updates = 0
# Handle human interaction points
if status in ['awaiting_review', 'in_review']:
@@ -1388,6 +1627,7 @@ def main():
logger.info("")
logger.info(f"Total: {len(jobs)} jobs")
logger.info("")
logger.info("To retry a failed job: karaoke-gen-remote --retry <JOB_ID>")
logger.info("To delete a job: karaoke-gen-remote --delete <JOB_ID>")
logger.info("To bulk delete: karaoke-gen-remote --bulk-delete --filter-environment=test")
logger.info("To cancel a job: karaoke-gen-remote --cancel <JOB_ID>")
@@ -1403,24 +1643,24 @@ def main():
logger.info("Karaoke Generator (Remote) - Cancel Job")
logger.info("=" * 60)
logger.info(f"Job ID: {args.cancel}")
try:
# Get job info first
job_data = client.get_job(args.cancel)
artist = job_data.get('artist', 'Unknown')
title = job_data.get('title', 'Unknown')
status = job_data.get('status', 'unknown')
logger.info(f"Artist: {artist}")
logger.info(f"Title: {title}")
logger.info(f"Current status: {status}")
logger.info("")
# Cancel the job
result = client.cancel_job(args.cancel)
logger.info(f"✓ Job cancelled successfully")
return 0
except ValueError as e:
logger.error(str(e))
return 1
@@ -1430,7 +1670,54 @@ def main():
except Exception as e:
logger.error(f"Error cancelling job: {e}")
return 1
# Handle retry job mode
if args.retry:
logger.info("=" * 60)
logger.info("Karaoke Generator (Remote) - Retry Failed Job")
logger.info("=" * 60)
logger.info(f"Job ID: {args.retry}")
try:
# Get job info first
job_data = client.get_job(args.retry)
artist = job_data.get('artist', 'Unknown')
title = job_data.get('title', 'Unknown')
status = job_data.get('status', 'unknown')
error_message = job_data.get('error_message', 'No error message')
logger.info(f"Artist: {artist}")
logger.info(f"Title: {title}")
logger.info(f"Current status: {status}")
if status == 'failed':
logger.info(f"Error: {error_message}")
logger.info("")
if status != 'failed':
logger.error(f"Only failed jobs can be retried (current status: {status})")
return 1
# Retry the job
result = client.retry_job(args.retry)
retry_stage = result.get('retry_stage', 'unknown')
logger.info(f"✓ Job retry started from stage: {retry_stage}")
logger.info("")
logger.info(f"Monitoring job progress...")
logger.info("")
# Monitor the retried job
return monitor.monitor(args.retry)
except ValueError as e:
logger.error(str(e))
return 1
except RuntimeError as e:
logger.error(str(e))
return 1
except Exception as e:
logger.error(f"Error retrying job: {e}")
return 1
# Handle delete job mode
if args.delete:
logger.info("=" * 60)
@@ -1492,8 +1779,6 @@ def main():
ignored_features.append("--skip-transcription")
if args.lyrics_only:
ignored_features.append("--lyrics-only")
if args.existing_instrumental:
ignored_features.append("--existing_instrumental")
if args.background_video:
ignored_features.append("--background_video")
if getattr(args, 'auto_download', False):
@@ -1588,6 +1873,24 @@ def main():
logger.info(f"Dropbox (rclone): {args.organised_dir_rclone_root}")
if args.discord_webhook_url:
logger.info(f"Discord: enabled")
# Lyrics configuration
if getattr(args, 'lyrics_artist', None):
logger.info(f"Lyrics Artist Override: {args.lyrics_artist}")
if getattr(args, 'lyrics_title', None):
logger.info(f"Lyrics Title Override: {args.lyrics_title}")
if getattr(args, 'lyrics_file', None):
logger.info(f"Lyrics File: {args.lyrics_file}")
if getattr(args, 'subtitle_offset_ms', 0):
logger.info(f"Subtitle Offset: {args.subtitle_offset_ms}ms")
# Audio model configuration
if getattr(args, 'clean_instrumental_model', None):
logger.info(f"Clean Instrumental Model: {args.clean_instrumental_model}")
if getattr(args, 'backing_vocals_models', None):
logger.info(f"Backing Vocals Models: {args.backing_vocals_models}")
if getattr(args, 'other_stems_models', None):
logger.info(f"Other Stems Models: {args.other_stems_models}")
if getattr(args, 'existing_instrumental', None):
logger.info(f"Existing Instrumental: {args.existing_instrumental}")
logger.info(f"Service URL: {config.service_url}")
logger.info(f"Review UI: {config.review_ui_url}")
if config.non_interactive:
@@ -1621,6 +1924,17 @@ def main():
# Native API distribution (preferred for remote CLI)
dropbox_path=getattr(args, 'dropbox_path', None),
gdrive_folder_id=getattr(args, 'gdrive_folder_id', None),
# Lyrics configuration
lyrics_artist=getattr(args, 'lyrics_artist', None),
lyrics_title=getattr(args, 'lyrics_title', None),
lyrics_file=getattr(args, 'lyrics_file', None),
subtitle_offset_ms=getattr(args, 'subtitle_offset_ms', 0) or 0,
# Audio separation model configuration
clean_instrumental_model=getattr(args, 'clean_instrumental_model', None),
backing_vocals_models=getattr(args, 'backing_vocals_models', None),
other_stems_models=getattr(args, 'other_stems_models', None),
# Existing instrumental (Batch 3)
existing_instrumental=getattr(args, 'existing_instrumental', None),
)
job_id = result.get('job_id')
style_assets = result.get('style_assets_uploaded', [])
@@ -194,9 +194,9 @@ class AnchorSequenceFinder:
min_sources: int,
) -> List[AnchorSequence]:
"""Process a single n-gram length to find matching sequences with timeout and early termination."""
self.logger.info(f"🔍 N-GRAM {n}: Starting processing with {len(trans_words)} transcription words")
self.logger.info(f"🔍 N-GRAM {n}: Reference sources: {list(ref_texts_clean.keys())}")
self.logger.info(f"🔍 N-GRAM {n}: Max iterations limit: {self.max_iterations_per_ngram}")
self.logger.debug(f"🔍 N-GRAM {n}: Starting processing with {len(trans_words)} transcription words")
self.logger.debug(f"🔍 N-GRAM {n}: Reference sources: {list(ref_texts_clean.keys())}")
self.logger.debug(f"🔍 N-GRAM {n}: Max iterations limit: {self.max_iterations_per_ngram}")
candidate_anchors = []
used_positions = {source: set() for source in ref_texts_clean.keys()}
@@ -211,7 +211,7 @@ class AnchorSequenceFinder:
# Generate n-grams from transcribed text once
trans_ngrams = self._find_ngrams(trans_words, n)
self.logger.info(f"🔍 N-GRAM {n}: Generated {len(trans_ngrams)} n-grams for processing")
self.logger.debug(f"🔍 N-GRAM {n}: Generated {len(trans_ngrams)} n-grams for processing")
# Process all n-grams efficiently in multiple passes
found_new_match = True
@@ -231,7 +231,7 @@ class AnchorSequenceFinder:
stagnation_count += 1
self.logger.debug(f"🔍 N-GRAM {n}: Stagnation check {stagnation_count}/3 at iteration {iteration_count}")
if stagnation_count >= 3: # No progress for 3 consecutive checks
self.logger.info(f"🔍 N-GRAM {n}: ⏹️ Early termination due to stagnation after {iteration_count} iterations")
self.logger.debug(f"🔍 N-GRAM {n}: ⏹️ Early termination due to stagnation after {iteration_count} iterations")
break
else:
stagnation_count = 0 # Reset stagnation counter
@@ -301,13 +301,13 @@ class AnchorSequenceFinder:
# Early termination if we've found enough anchors or processed all positions
if len(used_trans_positions) >= len(trans_ngrams) or len(candidate_anchors) >= len(trans_ngrams):
self.logger.info(f"🔍 N-GRAM {n}: ⏹️ Early termination - processed all positions after {iteration_count} iterations")
self.logger.debug(f"🔍 N-GRAM {n}: ⏹️ Early termination - processed all positions after {iteration_count} iterations")
break
if iteration_count >= self.max_iterations_per_ngram:
self.logger.warning(f"🔍 N-GRAM {n}: ⏰ Processing terminated after reaching max iterations ({self.max_iterations_per_ngram})")
self.logger.debug(f"🔍 N-GRAM {n}: ⏰ Processing terminated after reaching max iterations ({self.max_iterations_per_ngram})")
self.logger.info(f"🔍 N-GRAM {n}: ✅ Completed processing after {iteration_count} iterations, found {len(candidate_anchors)} anchors")
self.logger.debug(f"🔍 N-GRAM {n}: ✅ Completed processing after {iteration_count} iterations, found {len(candidate_anchors)} anchors")
return candidate_anchors
def find_anchors(
@@ -320,18 +320,17 @@ class AnchorSequenceFinder:
start_time = time.time()
try:
self.logger.info(f"🔍 ANCHOR SEARCH: Starting find_anchors with timeout {self.timeout_seconds}s")
self.logger.info(f"🔍 ANCHOR SEARCH: Transcribed text length: {len(transcribed)}")
self.logger.info(f"🔍 ANCHOR SEARCH: Reference sources: {list(references.keys())}")
self.logger.info(f"🔍 ANCHOR SEARCH: Starting anchor search (timeout: {self.timeout_seconds}s, sources: {list(references.keys())})")
self.logger.debug(f"🔍 ANCHOR SEARCH: Transcribed text length: {len(transcribed)}")
cache_key = self._get_cache_key(transcribed, references, transcription_result)
cache_path = self.cache_dir / f"anchors_{cache_key}.json"
self.logger.info(f"🔍 ANCHOR SEARCH: Cache key: {cache_key}")
self.logger.debug(f"🔍 ANCHOR SEARCH: Cache key: {cache_key}")
# Try to load from cache
self.logger.info(f"🔍 ANCHOR SEARCH: Checking cache at {cache_path}")
self.logger.debug(f"🔍 ANCHOR SEARCH: Checking cache at {cache_path}")
if cached_data := self._load_from_cache(cache_path):
self.logger.info("🔍 ANCHOR SEARCH: ✅ Cache hit! Loading anchors from cache")
self.logger.info("🔍 ANCHOR SEARCH: ✅ Cache hit - loading anchors from cache")
try:
# Convert cached_data to dictionary before logging
if cached_data:
@@ -347,26 +346,26 @@ class AnchorSequenceFinder:
self.logger.error("Could not serialize first cached anchor for logging")
# If not in cache or cache format invalid, perform the computation
self.logger.info(f"🔍 ANCHOR SEARCH: ❌ Cache miss - computing anchors with timeout {self.timeout_seconds}s")
self.logger.info(f"🔍 ANCHOR SEARCH: Finding anchor sequences for transcription with length {len(transcribed)}")
self.logger.info(f"🔍 ANCHOR SEARCH: Cache miss - computing anchors")
self.logger.debug(f"🔍 ANCHOR SEARCH: Finding anchor sequences for transcription with length {len(transcribed)}")
# Check timeout before starting computation
self._check_timeout(start_time, "anchor computation initialization")
self.logger.info(f"🔍 ANCHOR SEARCH: ✅ Timeout check passed - initialization")
self.logger.debug(f"🔍 ANCHOR SEARCH: ✅ Timeout check passed - initialization")
# Get all words from transcription
self.logger.info(f"🔍 ANCHOR SEARCH: Extracting words from transcription result...")
self.logger.debug(f"🔍 ANCHOR SEARCH: Extracting words from transcription result...")
all_words = []
for segment in transcription_result.result.segments:
all_words.extend(segment.words)
self.logger.info(f"🔍 ANCHOR SEARCH: ✅ Extracted {len(all_words)} words from transcription")
self.logger.debug(f"🔍 ANCHOR SEARCH: ✅ Extracted {len(all_words)} words from transcription")
# Clean and split texts
self.logger.info(f"🔍 ANCHOR SEARCH: Cleaning transcription words...")
self.logger.debug(f"🔍 ANCHOR SEARCH: Cleaning transcription words...")
trans_words = [w.text.lower().strip('.,?!"\n') for w in all_words]
self.logger.info(f"🔍 ANCHOR SEARCH: ✅ Cleaned {len(trans_words)} transcription words")
self.logger.debug(f"🔍 ANCHOR SEARCH: ✅ Cleaned {len(trans_words)} transcription words")
self.logger.info(f"🔍 ANCHOR SEARCH: Processing reference sources...")
self.logger.debug(f"🔍 ANCHOR SEARCH: Processing reference sources...")
ref_texts_clean = {
source: self._clean_text(" ".join(w.text for s in lyrics.segments for w in s.words)).split()
for source, lyrics in references.items()
@@ -374,14 +373,14 @@ class AnchorSequenceFinder:
ref_words = {source: [w for s in lyrics.segments for w in s.words] for source, lyrics in references.items()}
for source, words in ref_texts_clean.items():
self.logger.info(f"🔍 ANCHOR SEARCH: Reference '{source}': {len(words)} words")
self.logger.debug(f"🔍 ANCHOR SEARCH: Reference '{source}': {len(words)} words")
# Check timeout after preprocessing
self._check_timeout(start_time, "anchor computation preprocessing")
self.logger.info(f"🔍 ANCHOR SEARCH: ✅ Timeout check passed - preprocessing")
self.logger.debug(f"🔍 ANCHOR SEARCH: ✅ Timeout check passed - preprocessing")
# Filter out very short reference sources for n-gram length calculation
self.logger.info(f"🔍 ANCHOR SEARCH: Calculating n-gram lengths...")
self.logger.debug(f"🔍 ANCHOR SEARCH: Calculating n-gram lengths...")
valid_ref_lengths = [
len(words) for words in ref_texts_clean.values()
if len(words) >= self.min_sequence_length
@@ -394,10 +393,10 @@ class AnchorSequenceFinder:
# Calculate max length using only valid reference sources
max_length = min(len(trans_words), min(valid_ref_lengths))
n_gram_lengths = range(max_length, self.min_sequence_length - 1, -1)
self.logger.info(f"🔍 ANCHOR SEARCH: N-gram lengths to process: {list(n_gram_lengths)} (max_length: {max_length})")
self.logger.debug(f"🔍 ANCHOR SEARCH: N-gram lengths to process: {list(n_gram_lengths)} (max_length: {max_length})")
# Process n-gram lengths in parallel with timeout
self.logger.info(f"🔍 ANCHOR SEARCH: Setting up parallel processing...")
self.logger.debug(f"🔍 ANCHOR SEARCH: Setting up parallel processing...")
process_length_partial = partial(
self._process_ngram_length,
trans_words=trans_words,
@@ -413,24 +412,25 @@ class AnchorSequenceFinder:
# Check timeout before parallel processing
self._check_timeout(start_time, "parallel processing start")
self.logger.info(f"🔍 ANCHOR SEARCH: ✅ Timeout check passed - about to start parallel processing")
self.logger.debug(f"🔍 ANCHOR SEARCH: ✅ Timeout check passed - about to start parallel processing")
pool = None
try:
self.logger.info(f"🔍 ANCHOR SEARCH: 🚀 Starting parallel processing with {max(cpu_count() - 1, 1)} processes, pool timeout: {pool_timeout}s")
pool = Pool(processes=max(cpu_count() - 1, 1))
num_processes = max(cpu_count() - 1, 1)
self.logger.info(f"🔍 ANCHOR SEARCH: 🚀 Starting parallel processing ({num_processes} processes, {len(n_gram_lengths)} n-gram lengths)")
pool = Pool(processes=num_processes)
self.logger.debug(f"🔍 ANCHOR SEARCH: Pool created successfully")
results = []
# Submit all jobs first
self.logger.info(f"🔍 ANCHOR SEARCH: Submitting {len(n_gram_lengths)} n-gram processing jobs...")
self.logger.debug(f"🔍 ANCHOR SEARCH: Submitting {len(n_gram_lengths)} n-gram processing jobs...")
async_results = []
for i, n in enumerate(n_gram_lengths):
self.logger.debug(f"🔍 ANCHOR SEARCH: Submitting job {i+1}/{len(n_gram_lengths)} for n-gram length {n}")
async_result = pool.apply_async(process_length_partial, (n,))
async_results.append(async_result)
self.logger.info(f"🔍 ANCHOR SEARCH: ✅ All {len(async_results)} jobs submitted")
self.logger.debug(f"🔍 ANCHOR SEARCH: ✅ All {len(async_results)} jobs submitted")
# Collect results with individual timeouts
batch_results = []
@@ -454,12 +454,12 @@ class AnchorSequenceFinder:
# Batch logging - collect info for batched logging
batch_results.append((n_gram_length, len(result)))
# Log progress every batch_size results or on the last result
# Log progress every batch_size results or on the last result (at DEBUG level)
if (i + 1) % batch_size == 0 or (i + 1) == len(async_results):
total_anchors_in_batch = sum(anchor_count for _, anchor_count in batch_results)
n_gram_ranges = [str(ng) for ng, _ in batch_results]
range_str = f"{n_gram_ranges[0]}-{n_gram_ranges[-1]}" if len(n_gram_ranges) > 1 else n_gram_ranges[0]
self.logger.info(f"🔍 ANCHOR SEARCH: ✅ Completed n-gram lengths {range_str} ({i+1-len(batch_results)+1}-{i+1}/{len(async_results)}) - found {total_anchors_in_batch} anchors total")
self.logger.debug(f"🔍 ANCHOR SEARCH: Completed n-gram lengths {range_str} ({i+1-len(batch_results)+1}-{i+1}/{len(async_results)}) - found {total_anchors_in_batch} anchors")
batch_results = [] # Reset batch
except Exception as e:
@@ -475,15 +475,15 @@ class AnchorSequenceFinder:
# Raise exception to trigger fallback to sequential processing
raise Exception("Parallel processing timeout, triggering fallback")
self.logger.info(f"🔍 ANCHOR SEARCH: ✅ Parallel processing completed, combining results...")
self.logger.debug(f"🔍 ANCHOR SEARCH: Parallel processing completed, combining results...")
for anchors in results:
candidate_anchors.extend(anchors)
# Explicitly cleanup pool to avoid hangs in containerized environments
self.logger.info(f"🔍 ANCHOR SEARCH: 🧹 Cleaning up pool...")
self.logger.debug(f"🔍 ANCHOR SEARCH: 🧹 Cleaning up pool...")
pool.close()
pool.terminate()
self.logger.info(f"🔍 ANCHOR SEARCH: ✅ Pool cleanup completed")
self.logger.debug(f"🔍 ANCHOR SEARCH: ✅ Pool cleanup completed")
except AnchorSequenceTimeoutError:
self.logger.error(f"🔍 ANCHOR SEARCH: ❌ Parallel processing timed out")
@@ -492,7 +492,7 @@ class AnchorSequenceFinder:
except Exception as e:
self.logger.error(f"🔍 ANCHOR SEARCH: ❌ Parallel processing failed: {str(e)}")
# Fall back to sequential processing with timeout checks
self.logger.info("🔍 ANCHOR SEARCH: 🔄 Falling back to sequential processing")
self.logger.info("🔍 ANCHOR SEARCH: Falling back to sequential processing")
for n in n_gram_lengths:
try:
# Check timeout more leniently during sequential processing
@@ -503,13 +503,13 @@ class AnchorSequenceFinder:
self.logger.warning(f"🔍 ANCHOR SEARCH: ⏰ Sequential processing timeout for n-gram {n}")
break
self.logger.info(f"🔍 ANCHOR SEARCH: 🔄 Sequential processing n-gram length {n}")
self.logger.debug(f"🔍 ANCHOR SEARCH: Sequential processing n-gram length {n}")
anchors = self._process_ngram_length(
n, trans_words, all_words, ref_texts_clean, ref_words, self.min_sources
)
candidate_anchors.extend(anchors)
self.logger.info(f"🔍 ANCHOR SEARCH: ✅ Sequential n-gram {n} completed - found {len(anchors)} anchors")
self.logger.debug(f"🔍 ANCHOR SEARCH: Sequential n-gram {n} completed - found {len(anchors)} anchors")
except Exception as e:
self.logger.warning(f"🔍 ANCHOR SEARCH: ⚠️ Sequential processing failed for n-gram length {n}: {str(e)}")
continue
@@ -517,28 +517,28 @@ class AnchorSequenceFinder:
# Always ensure pool is cleaned up to avoid hangs in containerized environments
if pool is not None:
try:
self.logger.info(f"🔍 ANCHOR SEARCH: 🧹 Final pool cleanup...")
self.logger.debug(f"🔍 ANCHOR SEARCH: 🧹 Final pool cleanup...")
pool.terminate()
pool.join(timeout=5) # Wait max 5 seconds for workers to terminate
self.logger.info(f"🔍 ANCHOR SEARCH: ✅ Final pool cleanup completed")
self.logger.debug(f"🔍 ANCHOR SEARCH: ✅ Final pool cleanup completed")
except Exception as cleanup_error:
self.logger.warning(f"🔍 ANCHOR SEARCH: ⚠️ Pool cleanup error (ignored): {cleanup_error}")
self.logger.debug(f"🔍 ANCHOR SEARCH: ⚠️ Pool cleanup error (ignored): {cleanup_error}")
self.logger.info(f"🔍 ANCHOR SEARCH: ✅ Found {len(candidate_anchors)} candidate anchors in {time.time() - start_time:.1f}s")
self.logger.debug(f"🔍 ANCHOR SEARCH: Found {len(candidate_anchors)} candidate anchors in {time.time() - start_time:.1f}s")
# Check timeout before expensive filtering operation
self._check_timeout(start_time, "overlap filtering start")
self.logger.info(f"🔍 ANCHOR SEARCH: 🔄 Starting overlap filtering...")
self.logger.debug(f"🔍 ANCHOR SEARCH: Starting overlap filtering...")
filtered_anchors = self._remove_overlapping_sequences(candidate_anchors, transcribed, transcription_result)
self.logger.info(f"🔍 ANCHOR SEARCH: ✅ Filtering completed - {len(filtered_anchors)} final anchors")
self.logger.debug(f"🔍 ANCHOR SEARCH: Filtering completed - {len(filtered_anchors)} final anchors")
# Save to cache
self.logger.info(f"🔍 ANCHOR SEARCH: 💾 Saving results to cache...")
self.logger.debug(f"🔍 ANCHOR SEARCH: Saving results to cache...")
self._save_to_cache(cache_path, filtered_anchors)
total_time = time.time() - start_time
self.logger.info(f"🔍 ANCHOR SEARCH: 🎉 Anchor sequence computation completed successfully in {total_time:.1f}s")
self.logger.info(f"🔍 ANCHOR SEARCH: ✅ Completed in {total_time:.1f}s - found {len(filtered_anchors)} anchors")
return filtered_anchors
@@ -618,13 +618,13 @@ class AnchorSequenceFinder:
transcription_result: TranscriptionResult,
) -> List[ScoredAnchor]:
"""Remove overlapping sequences using phrase analysis with timeout protection."""
self.logger.info(f"🔍 FILTERING: Starting overlap removal for {len(anchors)} anchors")
self.logger.debug(f"🔍 FILTERING: Starting overlap removal for {len(anchors)} anchors")
if not anchors:
self.logger.info(f"🔍 FILTERING: No anchors to process")
self.logger.debug(f"🔍 FILTERING: No anchors to process")
return []
self.logger.info(f"🔍 FILTERING: Scoring {len(anchors)} anchors")
self.logger.debug(f"🔍 FILTERING: Scoring {len(anchors)} anchors")
# Create word map for scoring
word_map = {w.id: w for s in transcription_result.result.segments for w in s.words}
@@ -682,27 +682,27 @@ class AnchorSequenceFinder:
scoring_pool = None
try:
self.logger.info(f"🔍 FILTERING: 🚀 Starting parallel scoring with timeout {pool_timeout}s")
self.logger.debug(f"🔍 FILTERING: Starting parallel scoring with timeout {pool_timeout}s")
scoring_pool = Pool(processes=num_processes)
# Submit scoring jobs with timeout
async_results = []
batch_size = 50
self.logger.info(f"🔍 FILTERING: Splitting {len(anchors)} anchors into batches of {batch_size}")
self.logger.debug(f"🔍 FILTERING: Splitting {len(anchors)} anchors into batches of {batch_size}")
for i in range(0, len(anchors), batch_size):
batch = anchors[i:i + batch_size]
async_result = scoring_pool.apply_async(self._score_batch_static, (batch, context))
async_results.append(async_result)
self.logger.info(f"🔍 FILTERING: Submitted {len(async_results)} scoring batches")
self.logger.debug(f"🔍 FILTERING: Submitted {len(async_results)} scoring batches")
# Collect results with timeout
for i, async_result in enumerate(async_results):
try:
self.logger.debug(f"🔍 FILTERING: ⏳ Collecting batch {i+1}/{len(async_results)}")
self.logger.debug(f"🔍 FILTERING: Collecting batch {i+1}/{len(async_results)}")
batch_results = async_result.get(timeout=pool_timeout)
scored_anchors.extend(batch_results)
self.logger.debug(f"🔍 FILTERING: ✅ Completed scoring batch {i+1}/{len(async_results)}")
self.logger.debug(f"🔍 FILTERING: Completed scoring batch {i+1}/{len(async_results)}")
except Exception as e:
self.logger.warning(f"🔍 FILTERING: ⚠️ Scoring batch {i+1} failed or timed out: {str(e)}")
# Add basic scores for failed batch
@@ -721,10 +721,10 @@ class AnchorSequenceFinder:
continue
# Explicitly cleanup pool to avoid hangs in containerized environments
self.logger.info(f"🔍 FILTERING: 🧹 Cleaning up scoring pool...")
scoring_pool.close()
scoring_pool.terminate()
self.logger.info(f"🔍 FILTERING: ✅ Scoring pool cleanup completed")
self.logger.debug(f"🔍 FILTERING: Cleaning up scoring pool...")
scoring_pool.close()
scoring_pool.terminate()
self.logger.debug(f"🔍 FILTERING: Scoring pool cleanup completed")
except Exception as e:
self.logger.warning(f"🔍 FILTERING: ❌ Parallel scoring failed: {str(e)}, falling back to basic scoring")
@@ -743,22 +743,22 @@ class AnchorSequenceFinder:
# Always ensure scoring pool is cleaned up to avoid hangs
if scoring_pool is not None:
try:
self.logger.info(f"🔍 FILTERING: 🧹 Final scoring pool cleanup...")
self.logger.debug(f"🔍 FILTERING: Final scoring pool cleanup...")
scoring_pool.terminate()
scoring_pool.join(timeout=5) # Wait max 5 seconds for workers to terminate
self.logger.info(f"🔍 FILTERING: ✅ Final scoring pool cleanup completed")
self.logger.debug(f"🔍 FILTERING: Final scoring pool cleanup completed")
except Exception as cleanup_error:
self.logger.warning(f"🔍 FILTERING: ⚠️ Scoring pool cleanup error (ignored): {cleanup_error}")
self.logger.debug(f"🔍 FILTERING: Scoring pool cleanup error (ignored): {cleanup_error}")
parallel_time = time.time() - start_time
self.logger.info(f"🔍 FILTERING: ✅ Parallel scoring completed in {parallel_time:.2f}s, scored {len(scored_anchors)} anchors")
self.logger.debug(f"🔍 FILTERING: Parallel scoring completed in {parallel_time:.2f}s, scored {len(scored_anchors)} anchors")
# Sort and filter as before
self.logger.info(f"🔍 FILTERING: 🔄 Sorting anchors by priority...")
self.logger.debug(f"🔍 FILTERING: Sorting anchors by priority...")
scored_anchors.sort(key=self._get_sequence_priority, reverse=True)
self.logger.info(f"🔍 FILTERING: ✅ Sorting completed")
self.logger.debug(f"🔍 FILTERING: Sorting completed")
self.logger.info(f"🔍 FILTERING: 🔄 Filtering {len(scored_anchors)} overlapping sequences")
self.logger.debug(f"🔍 FILTERING: Filtering {len(scored_anchors)} overlapping sequences")
filtered_scored = []
for i, scored_anchor in enumerate(scored_anchors):
@@ -783,7 +783,7 @@ class AnchorSequenceFinder:
if not overlaps:
filtered_scored.append(scored_anchor)
self.logger.info(f"🔍 FILTERING: ✅ Filtering completed - kept {len(filtered_scored)} non-overlapping anchors out of {len(scored_anchors)}")
self.logger.debug(f"🔍 FILTERING: Filtering completed - kept {len(filtered_scored)} non-overlapping anchors out of {len(scored_anchors)}")
return filtered_scored
@staticmethod
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.71.16"
version = "0.71.26"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"
+1 -1
View File
@@ -112,7 +112,7 @@ echo -e "${YELLOW}---BEGIN SERVICE ACCOUNT KEY---${NC}"
cat "$KEY_FILE"
echo -e "${YELLOW}---END SERVICE ACCOUNT KEY---${NC}"
echo ""
echo "3. After adding secrets, push to 'replace-modal-with-google-cloud' branch"
echo "3. After adding secrets, push to 'main' branch"
echo " to trigger an automated deployment!"
echo ""
echo -e "${RED}⚠️ IMPORTANT SECURITY NOTES:${NC}"
@@ -47,6 +47,42 @@ def mock_gmail_service():
# --- Discord Notification Tests ---
def test_discord_webhook_url_strips_whitespace(mock_logger):
"""Test that Discord webhook URL validation strips trailing whitespace/newlines."""
# This tests the fix for the %0A issue where webhook URLs have trailing newlines
config = MINIMAL_CONFIG.copy()
config.update({
# URL with trailing newline (simulating env var issue)
"discord_webhook_url": "https://discord.com/api/webhooks/123/abc\n",
})
with patch.object(KaraokeFinalise, 'detect_best_aac_codec', return_value='aac'):
finaliser = KaraokeFinalise(logger=mock_logger, **config)
# Call validate_input_parameters_for_features to trigger the strip
with patch('os.getcwd', return_value='/tmp'):
finaliser.validate_input_parameters_for_features()
# The URL should have been stripped
assert finaliser.discord_webhook_url == "https://discord.com/api/webhooks/123/abc"
assert finaliser.discord_notication_enabled is True
def test_discord_webhook_url_strips_whitespace_and_validates(mock_logger):
"""Test that invalid Discord URLs are rejected even after stripping."""
config = MINIMAL_CONFIG.copy()
config.update({
# Invalid URL that starts correctly but is malformed
"discord_webhook_url": "https://discord.com/invalid\n",
})
with patch.object(KaraokeFinalise, 'detect_best_aac_codec', return_value='aac'):
finaliser = KaraokeFinalise(logger=mock_logger, **config)
# Should raise because URL doesn't start with correct prefix after strip
with patch('os.getcwd', return_value='/tmp'):
with pytest.raises(Exception, match="Discord webhook URL is not valid"):
finaliser.validate_input_parameters_for_features()
@patch('requests.post')
def test_post_discord_message_success(mock_post, finaliser_for_notify):
"""Test successful posting to Discord."""
@@ -171,6 +171,40 @@ def test_execute_optional_features_youtube_fails(mock_input, mock_discord, mock_
assert finaliser_for_process.youtube_url == f"https://www.youtube.com/watch?v=manual_video_id"
mock_discord.assert_called_once() # Discord should still be called after manual ID entry
@patch.object(KaraokeFinalise, 'upload_final_mp4_to_youtube_with_title_thumbnail')
@patch.object(KaraokeFinalise, 'post_discord_notification')
@patch.object(KaraokeFinalise, 'get_next_brand_code', return_value=f"{BRAND_PREFIX}-0001")
@patch.object(KaraokeFinalise, 'move_files_to_brand_code_folder')
@patch.object(KaraokeFinalise, 'copy_final_files_to_public_share_dirs')
@patch.object(KaraokeFinalise, 'sync_public_share_dir_to_rclone_destination')
@patch.object(KaraokeFinalise, 'generate_organised_folder_sharing_link')
def test_execute_optional_features_discord_failure_continues(
mock_gen_link, mock_sync, mock_copy, mock_move, mock_get_next,
mock_discord, mock_youtube, finaliser_for_process):
"""Test that Discord notification failure doesn't crash the job."""
# Simulate Discord notification failure
mock_discord.side_effect = Exception("401 Unauthorized: Invalid webhook URL")
finaliser_for_process.keep_brand_code = False
finaliser_for_process.new_brand_code_dir_path = os.path.join(ORGANISED_DIR, f"{BRAND_PREFIX}-0001 - {ARTIST} - {TITLE}")
# Should not raise an exception - should continue with other features
finaliser_for_process.execute_optional_features(ARTIST, TITLE, BASE_NAME, ALL_INPUT_FILES, ALL_OUTPUT_FILES, False)
# Discord was called (and failed)
mock_discord.assert_called_once()
# But other features should still run
mock_youtube.assert_called_once()
mock_get_next.assert_called_once()
mock_move.assert_called_once()
mock_copy.assert_called_once()
mock_sync.assert_called_once()
mock_gen_link.assert_called_once()
# Logger should have logged the error (warning)
finaliser_for_process.logger.error.assert_called()
finaliser_for_process.logger.warning.assert_called()
# --- process Method Tests ---
@patch.object(KaraokeFinalise, 'validate_input_parameters_for_features')
+593 -41
View File
@@ -426,10 +426,51 @@ class TestRemoteKaraokeClient:
mock_response = MagicMock()
mock_response.status_code = 404
mock_request.return_value = mock_response
with pytest.raises(ValueError, match="Job not found"):
client.delete_job("nonexistent-job")
@patch.object(RemoteKaraokeClient, '_request')
def test_retry_job_success(self, mock_request, client):
"""Test retrying a failed job successfully."""
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json.return_value = {
"status": "success",
"job_status": "instrumental_selected",
"retry_stage": "video_generation"
}
mock_request.return_value = mock_response
result = client.retry_job("job-123")
assert result["status"] == "success"
assert result["retry_stage"] == "video_generation"
mock_request.assert_called_once_with('POST', '/api/jobs/job-123/retry')
@patch.object(RemoteKaraokeClient, '_request')
def test_retry_job_not_found(self, mock_request, client):
"""Test retrying non-existent job."""
mock_response = MagicMock()
mock_response.status_code = 404
mock_request.return_value = mock_response
with pytest.raises(ValueError, match="Job not found"):
client.retry_job("nonexistent-job")
@patch.object(RemoteKaraokeClient, '_request')
def test_retry_job_not_failed(self, mock_request, client):
"""Test retrying a job that isn't in failed state."""
mock_response = MagicMock()
mock_response.status_code = 400
mock_response.json.return_value = {
"detail": "Only failed jobs can be retried"
}
mock_request.return_value = mock_response
with pytest.raises(RuntimeError, match="Cannot retry job"):
client.retry_job("job-123")
@patch.object(RemoteKaraokeClient, '_request')
def test_get_instrumental_options(self, mock_request, client):
"""Test getting instrumental options."""
@@ -508,44 +549,94 @@ class TestRemoteKaraokeClient:
client.submit_job(str(test_file), "Artist", "Title")
@patch.object(RemoteKaraokeClient, '_request')
def test_submit_job_success(self, mock_request, client, tmp_path):
"""Test successful job submission."""
@patch.object(RemoteKaraokeClient, '_upload_file_to_signed_url')
def test_submit_job_success(self, mock_upload, mock_request, client, tmp_path):
"""Test successful job submission via signed URL flow."""
# Create test audio file
audio_file = tmp_path / "test.mp3"
audio_file.write_bytes(b"audio data")
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json.return_value = {
# Mock create job response (first API call)
create_response = MagicMock()
create_response.status_code = 200
create_response.json.return_value = {
"status": "success",
"job_id": "new-job-123"
"job_id": "new-job-123",
"upload_urls": [
{
"file_type": "audio",
"gcs_path": "uploads/new-job-123/audio/test.mp3",
"upload_url": "https://storage.googleapis.com/signed-url",
"content_type": "audio/mpeg"
}
]
}
mock_request.return_value = mock_response
# Mock uploads complete response (second API call)
complete_response = MagicMock()
complete_response.status_code = 200
complete_response.json.return_value = {
"status": "success",
"job_id": "new-job-123",
"message": "Processing started"
}
mock_request.side_effect = [create_response, complete_response]
mock_upload.return_value = True
result = client.submit_job(str(audio_file), "Test Artist", "Test Title")
assert result["status"] == "success"
assert result["job_id"] == "new-job-123"
# Verify the signed URL upload was called
mock_upload.assert_called_once()
@patch.object(RemoteKaraokeClient, '_upload_file_to_signed_url')
@patch.object(RemoteKaraokeClient, '_request')
def test_submit_job_with_style_params(self, mock_request, client, tmp_path):
"""Test job submission with style params."""
def test_submit_job_with_style_params(self, mock_request, mock_upload, client, tmp_path):
"""Test job submission with style params via signed URL flow."""
# Create test files
audio_file = tmp_path / "test.mp3"
audio_file.write_bytes(b"audio data")
style_file = tmp_path / "style_params.json"
style_file.write_text(json.dumps({"intro": {}}))
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json.return_value = {
# Mock create job response (first API call)
create_response = MagicMock()
create_response.status_code = 200
create_response.json.return_value = {
"status": "success",
"job_id": "new-job-456",
"style_assets_uploaded": []
"upload_urls": [
{
"file_type": "audio",
"gcs_path": "uploads/new-job-456/audio/test.mp3",
"upload_url": "https://storage.googleapis.com/signed-url-1",
"content_type": "audio/mpeg"
},
{
"file_type": "style_params",
"gcs_path": "uploads/new-job-456/style/style_params.json",
"upload_url": "https://storage.googleapis.com/signed-url-2",
"content_type": "application/json"
}
]
}
mock_request.return_value = mock_response
# Mock uploads complete response (second API call)
complete_response = MagicMock()
complete_response.status_code = 200
complete_response.json.return_value = {
"status": "success",
"job_id": "new-job-456",
"message": "Processing started",
"style_assets": ["style_params"]
}
mock_request.side_effect = [create_response, complete_response]
mock_upload.return_value = True
result = client.submit_job(
str(audio_file),
"Test Artist",
@@ -556,21 +647,128 @@ class TestRemoteKaraokeClient:
brand_prefix="TEST",
discord_webhook_url="https://discord.webhook/url"
)
assert result["status"] == "success"
# Verify uploads were called for both files
assert mock_upload.call_count == 2
@patch.object(RemoteKaraokeClient, '_upload_file_to_signed_url')
@patch.object(RemoteKaraokeClient, '_request')
def test_submit_job_api_error(self, mock_request, client, tmp_path):
"""Test handling API error during job submission."""
def test_submit_job_with_existing_instrumental(self, mock_request, mock_upload, client, tmp_path):
"""Test job submission with existing instrumental via signed URL flow (Batch 3)."""
# Create test files
audio_file = tmp_path / "test.mp3"
audio_file.write_bytes(b"audio data")
instrumental_file = tmp_path / "instrumental.flac"
instrumental_file.write_bytes(b"instrumental data")
# Mock create job response (first API call)
create_response = MagicMock()
create_response.status_code = 200
create_response.json.return_value = {
"status": "success",
"job_id": "job-with-instrumental-123",
"upload_urls": [
{
"file_type": "audio",
"gcs_path": "uploads/job-with-instrumental-123/audio/test.mp3",
"upload_url": "https://storage.googleapis.com/signed-url-audio",
"content_type": "audio/mpeg"
},
{
"file_type": "existing_instrumental",
"gcs_path": "uploads/job-with-instrumental-123/audio/existing_instrumental.flac",
"upload_url": "https://storage.googleapis.com/signed-url-instrumental",
"content_type": "audio/flac"
}
]
}
# Mock uploads complete response (second API call)
complete_response = MagicMock()
complete_response.status_code = 200
complete_response.json.return_value = {
"status": "success",
"job_id": "job-with-instrumental-123",
"message": "Processing started"
}
mock_request.side_effect = [create_response, complete_response]
mock_upload.return_value = True
result = client.submit_job(
str(audio_file),
"Test Artist",
"Test Title",
existing_instrumental=str(instrumental_file)
)
assert result["status"] == "success"
assert result["job_id"] == "job-with-instrumental-123"
# Verify uploads were called for both audio and instrumental
assert mock_upload.call_count == 2
@patch.object(RemoteKaraokeClient, '_upload_file_to_signed_url')
@patch.object(RemoteKaraokeClient, '_request')
def test_submit_job_existing_instrumental_nonexistent_file(self, mock_request, mock_upload, client, tmp_path):
"""Test that nonexistent instrumental file is silently ignored."""
# Create test audio file
audio_file = tmp_path / "test.mp3"
audio_file.write_bytes(b"audio data")
# Mock create job response (instrumental not included since file doesn't exist)
create_response = MagicMock()
create_response.status_code = 200
create_response.json.return_value = {
"status": "success",
"job_id": "job-no-instrumental-456",
"upload_urls": [
{
"file_type": "audio",
"gcs_path": "uploads/job-no-instrumental-456/audio/test.mp3",
"upload_url": "https://storage.googleapis.com/signed-url-audio",
"content_type": "audio/mpeg"
}
]
}
# Mock uploads complete response
complete_response = MagicMock()
complete_response.status_code = 200
complete_response.json.return_value = {
"status": "success",
"job_id": "job-no-instrumental-456",
"message": "Processing started"
}
mock_request.side_effect = [create_response, complete_response]
mock_upload.return_value = True
# Pass nonexistent instrumental path - should be silently ignored
result = client.submit_job(
str(audio_file),
"Test Artist",
"Test Title",
existing_instrumental="/nonexistent/instrumental.flac"
)
assert result["status"] == "success"
# Only audio should be uploaded (instrumental file doesn't exist)
assert mock_upload.call_count == 1
@patch.object(RemoteKaraokeClient, '_request')
def test_submit_job_api_error(self, mock_request, client, tmp_path):
"""Test handling API error during job creation."""
audio_file = tmp_path / "test.mp3"
audio_file.write_bytes(b"audio data")
mock_response = MagicMock()
mock_response.status_code = 500
mock_response.json.return_value = {"error": "Server error"}
mock_request.return_value = mock_response
with pytest.raises(RuntimeError, match="Error submitting job"):
with pytest.raises(RuntimeError, match="Error creating job"):
client.submit_job(str(audio_file), "Artist", "Title")
@@ -779,6 +977,7 @@ class TestMain:
mock_args.resume = None
mock_args.list_jobs = False
mock_args.cancel = None
mock_args.retry = None
mock_args.delete = None
mock_args.bulk_delete = False
mock_args.filter_environment = None
@@ -788,11 +987,11 @@ class TestMain:
mock_parser.parse_args.return_value = mock_args
mock_create_parser.return_value = mock_parser
mock_auth.return_value = "token"
result = main()
assert result == 1
@patch('karaoke_gen.utils.remote_cli.create_parser')
@patch('karaoke_gen.utils.remote_cli.get_auth_token')
@patch('karaoke_gen.utils.remote_cli.check_prerequisites')
@@ -810,6 +1009,7 @@ class TestMain:
mock_args.resume = None
mock_args.list_jobs = False
mock_args.cancel = None
mock_args.retry = None
mock_args.delete = None
mock_args.bulk_delete = False
mock_args.filter_environment = None
@@ -819,11 +1019,11 @@ class TestMain:
mock_parser.parse_args.return_value = mock_args
mock_create_parser.return_value = mock_parser
mock_auth.return_value = "token"
result = main()
assert result == 1
@patch('karaoke_gen.utils.remote_cli.create_parser')
@patch('karaoke_gen.utils.remote_cli.get_auth_token')
@patch('karaoke_gen.utils.remote_cli.check_prerequisites')
@@ -841,6 +1041,7 @@ class TestMain:
mock_args.resume = None
mock_args.list_jobs = False
mock_args.cancel = None
mock_args.retry = None
mock_args.delete = None
mock_args.bulk_delete = False
mock_args.filter_environment = None
@@ -850,11 +1051,11 @@ class TestMain:
mock_parser.parse_args.return_value = mock_args
mock_create_parser.return_value = mock_parser
mock_auth.return_value = "token"
result = main()
assert result == 1
@patch('karaoke_gen.utils.remote_cli.create_parser')
@patch('karaoke_gen.utils.remote_cli.get_auth_token')
@patch('karaoke_gen.utils.remote_cli.check_prerequisites')
@@ -872,6 +1073,7 @@ class TestMain:
mock_args.resume = None
mock_args.list_jobs = False
mock_args.cancel = None
mock_args.retry = None # Added for retry feature
mock_args.delete = None
mock_args.bulk_delete = False # New attribute for bulk delete mode
mock_args.filter_environment = None # New attribute for filtering
@@ -880,9 +1082,9 @@ class TestMain:
mock_parser.parse_args.return_value = mock_args
mock_create_parser.return_value = mock_parser
mock_auth.return_value = "token"
result = main()
assert result == 1
mock_parser.print_help.assert_called_once()
@@ -952,6 +1154,7 @@ class TestMain:
mock_args.resume = None
mock_args.list_jobs = True
mock_args.cancel = None
mock_args.retry = None
mock_args.delete = None
mock_args.bulk_delete = False # New attribute for bulk delete mode
mock_args.filter_environment = None # New attribute for filtering
@@ -960,7 +1163,7 @@ class TestMain:
mock_args.client_id = "" # Job tracking
mock_parser.parse_args.return_value = mock_args
mock_create_parser.return_value = mock_parser
mock_client = MagicMock()
mock_client.list_jobs.return_value = [
{"job_id": "job-1", "status": "complete", "artist": "Artist 1", "title": "Title 1", "request_metadata": {}},
@@ -993,6 +1196,7 @@ class TestMain:
mock_args.resume = None
mock_args.list_jobs = True
mock_args.cancel = None
mock_args.retry = None
mock_args.delete = None
mock_args.bulk_delete = False
mock_args.filter_environment = None
@@ -1001,7 +1205,7 @@ class TestMain:
mock_args.client_id = ""
mock_parser.parse_args.return_value = mock_args
mock_create_parser.return_value = mock_parser
mock_client = MagicMock()
mock_client.list_jobs.return_value = []
mock_client_class.return_value = mock_client
@@ -1052,7 +1256,187 @@ class TestMain:
assert result == 0
mock_client.cancel_job.assert_called_once_with("job-123")
@patch('karaoke_gen.utils.remote_cli.JobMonitor')
@patch('karaoke_gen.utils.remote_cli.create_parser')
@patch('karaoke_gen.utils.remote_cli.check_prerequisites')
@patch('karaoke_gen.utils.remote_cli.RemoteKaraokeClient')
def test_main_retry_job_mode(
self, mock_client_class, mock_check, mock_create_parser, mock_monitor_class
):
"""Test main in retry job mode with a failed job."""
mock_parser = MagicMock()
mock_args = MagicMock()
mock_args.service_url = "https://api.example.com"
mock_args.review_ui_url = "https://review.example.com"
mock_args.poll_interval = 5
mock_args.output_dir = "/tmp"
mock_args.log_level = "info"
mock_args.finalise_only = False
mock_args.edit_lyrics = False
mock_args.test_email_template = False
mock_args.resume = None
mock_args.list_jobs = False
mock_args.cancel = None
mock_args.retry = "job-123"
mock_args.delete = None
mock_args.bulk_delete = False
mock_args.filter_environment = None
mock_args.filter_client_id = None
mock_args.environment = ""
mock_args.client_id = ""
mock_parser.parse_args.return_value = mock_args
mock_create_parser.return_value = mock_parser
mock_client = MagicMock()
mock_client.get_job.return_value = {
"artist": "Artist",
"title": "Title",
"status": "failed",
"error_message": "Discord webhook failed"
}
mock_client.retry_job.return_value = {
"status": "success",
"retry_stage": "video_generation"
}
mock_client_class.return_value = mock_client
mock_monitor = MagicMock()
mock_monitor.monitor.return_value = 0
mock_monitor_class.return_value = mock_monitor
result = main()
assert result == 0
mock_client.retry_job.assert_called_once_with("job-123")
mock_monitor.monitor.assert_called_once_with("job-123")
@patch('karaoke_gen.utils.remote_cli.create_parser')
@patch('karaoke_gen.utils.remote_cli.check_prerequisites')
@patch('karaoke_gen.utils.remote_cli.RemoteKaraokeClient')
def test_main_retry_job_not_failed(
self, mock_client_class, mock_check, mock_create_parser
):
"""Test main retry job when job is not in failed state."""
mock_parser = MagicMock()
mock_args = MagicMock()
mock_args.service_url = "https://api.example.com"
mock_args.review_ui_url = "https://review.example.com"
mock_args.poll_interval = 5
mock_args.output_dir = "/tmp"
mock_args.log_level = "info"
mock_args.finalise_only = False
mock_args.edit_lyrics = False
mock_args.test_email_template = False
mock_args.resume = None
mock_args.list_jobs = False
mock_args.cancel = None
mock_args.retry = "job-123"
mock_args.delete = None
mock_args.bulk_delete = False
mock_args.filter_environment = None
mock_args.filter_client_id = None
mock_args.environment = ""
mock_args.client_id = ""
mock_parser.parse_args.return_value = mock_args
mock_create_parser.return_value = mock_parser
mock_client = MagicMock()
mock_client.get_job.return_value = {
"artist": "Artist",
"title": "Title",
"status": "complete" # Not failed
}
mock_client_class.return_value = mock_client
result = main()
assert result == 1 # Should fail because job is not in failed state
mock_client.retry_job.assert_not_called()
@patch('karaoke_gen.utils.remote_cli.create_parser')
@patch('karaoke_gen.utils.remote_cli.check_prerequisites')
@patch('karaoke_gen.utils.remote_cli.RemoteKaraokeClient')
def test_main_retry_job_not_found(
self, mock_client_class, mock_check, mock_create_parser
):
"""Test main retry job when job not found."""
mock_parser = MagicMock()
mock_args = MagicMock()
mock_args.service_url = "https://api.example.com"
mock_args.review_ui_url = "https://review.example.com"
mock_args.poll_interval = 5
mock_args.output_dir = "/tmp"
mock_args.log_level = "info"
mock_args.finalise_only = False
mock_args.edit_lyrics = False
mock_args.test_email_template = False
mock_args.resume = None
mock_args.list_jobs = False
mock_args.cancel = None
mock_args.retry = "nonexistent-job"
mock_args.delete = None
mock_args.bulk_delete = False
mock_args.filter_environment = None
mock_args.filter_client_id = None
mock_args.environment = ""
mock_args.client_id = ""
mock_parser.parse_args.return_value = mock_args
mock_create_parser.return_value = mock_parser
mock_client = MagicMock()
mock_client.get_job.side_effect = ValueError("Job not found")
mock_client_class.return_value = mock_client
result = main()
assert result == 1
mock_client.retry_job.assert_not_called()
@patch('karaoke_gen.utils.remote_cli.create_parser')
@patch('karaoke_gen.utils.remote_cli.check_prerequisites')
@patch('karaoke_gen.utils.remote_cli.RemoteKaraokeClient')
def test_main_retry_job_api_error(
self, mock_client_class, mock_check, mock_create_parser
):
"""Test main retry job when API returns an error."""
mock_parser = MagicMock()
mock_args = MagicMock()
mock_args.service_url = "https://api.example.com"
mock_args.review_ui_url = "https://review.example.com"
mock_args.poll_interval = 5
mock_args.output_dir = "/tmp"
mock_args.log_level = "info"
mock_args.finalise_only = False
mock_args.edit_lyrics = False
mock_args.test_email_template = False
mock_args.resume = None
mock_args.list_jobs = False
mock_args.cancel = None
mock_args.retry = "job-123"
mock_args.delete = None
mock_args.bulk_delete = False
mock_args.filter_environment = None
mock_args.filter_client_id = None
mock_args.environment = ""
mock_args.client_id = ""
mock_parser.parse_args.return_value = mock_args
mock_create_parser.return_value = mock_parser
mock_client = MagicMock()
mock_client.get_job.return_value = {
"artist": "Artist",
"title": "Title",
"status": "failed",
"error_message": "Some error"
}
mock_client.retry_job.side_effect = RuntimeError("Cannot retry job: No safe checkpoint found")
mock_client_class.return_value = mock_client
result = main()
assert result == 1
@patch('karaoke_gen.utils.remote_cli.create_parser')
@patch('karaoke_gen.utils.remote_cli.check_prerequisites')
@patch('karaoke_gen.utils.remote_cli.RemoteKaraokeClient')
@@ -1073,6 +1457,7 @@ class TestMain:
mock_args.resume = None
mock_args.list_jobs = False
mock_args.cancel = "nonexistent"
mock_args.retry = None
mock_args.delete = None
mock_args.bulk_delete = False
mock_args.filter_environment = None
@@ -1111,6 +1496,7 @@ class TestMain:
mock_args.resume = None
mock_args.list_jobs = False
mock_args.cancel = None
mock_args.retry = None
mock_args.delete = "job-123"
mock_args.bulk_delete = False
mock_args.filter_environment = None
@@ -1156,6 +1542,7 @@ class TestMain:
mock_args.resume = None
mock_args.list_jobs = False
mock_args.cancel = None
mock_args.retry = None
mock_args.delete = "job-123"
mock_args.bulk_delete = False
mock_args.filter_environment = None
@@ -1199,6 +1586,7 @@ class TestMain:
mock_args.resume = None
mock_args.list_jobs = False
mock_args.cancel = None
mock_args.retry = None
mock_args.delete = "job-123"
mock_args.bulk_delete = False
mock_args.filter_environment = None
@@ -1208,7 +1596,7 @@ class TestMain:
mock_args.yes = True # Non-interactive mode
mock_parser.parse_args.return_value = mock_args
mock_create_parser.return_value = mock_parser
mock_client = MagicMock()
mock_client.get_job.return_value = {
"artist": "Artist",
@@ -1245,6 +1633,7 @@ class TestMain:
mock_args.resume = None
mock_args.list_jobs = False
mock_args.cancel = None
mock_args.retry = None
mock_args.delete = None
mock_args.bulk_delete = False
mock_args.filter_environment = None
@@ -1288,6 +1677,7 @@ class TestMain:
mock_args.resume = None
mock_args.list_jobs = False
mock_args.cancel = None
mock_args.retry = None
mock_args.delete = None
mock_args.bulk_delete = False
mock_args.filter_environment = None
@@ -1332,6 +1722,7 @@ class TestMain:
mock_args.resume = None
mock_args.list_jobs = False
mock_args.cancel = None
mock_args.retry = None
mock_args.delete = None
mock_args.bulk_delete = False
mock_args.filter_environment = None
@@ -1483,3 +1874,164 @@ class TestJobMonitorHandleReview:
mock_open_ui.assert_called_once_with("job-123")
assert mock_get_job.call_count == 2
class TestSignedUrlUploadFlow:
"""Tests for the signed URL upload flow."""
@pytest.fixture
def config(self):
return Config(
service_url="https://api.example.com",
review_ui_url="https://review.example.com",
poll_interval=5,
output_dir="/tmp/output"
)
@pytest.fixture
def logger(self):
return logging.getLogger("test")
@pytest.fixture
def client(self, config, logger):
return RemoteKaraokeClient(config, logger)
def test_get_content_type_audio(self, client):
"""Test content type detection for audio files."""
assert client._get_content_type("song.flac") == "audio/flac"
assert client._get_content_type("song.mp3") == "audio/mpeg"
assert client._get_content_type("song.wav") == "audio/wav"
assert client._get_content_type("song.m4a") == "audio/mp4"
assert client._get_content_type("song.ogg") == "audio/ogg"
assert client._get_content_type("song.aac") == "audio/aac"
def test_get_content_type_images(self, client):
"""Test content type detection for image files."""
assert client._get_content_type("bg.png") == "image/png"
assert client._get_content_type("bg.jpg") == "image/jpeg"
assert client._get_content_type("bg.jpeg") == "image/jpeg"
assert client._get_content_type("bg.gif") == "image/gif"
assert client._get_content_type("bg.webp") == "image/webp"
def test_get_content_type_fonts(self, client):
"""Test content type detection for font files."""
assert client._get_content_type("font.ttf") == "font/ttf"
assert client._get_content_type("font.otf") == "font/otf"
assert client._get_content_type("font.woff") == "font/woff"
assert client._get_content_type("font.woff2") == "font/woff2"
def test_get_content_type_other(self, client):
"""Test content type detection for other files."""
assert client._get_content_type("style.json") == "application/json"
assert client._get_content_type("lyrics.txt") == "text/plain"
assert client._get_content_type("unknown.xyz") == "application/octet-stream"
@patch('requests.put')
def test_upload_file_to_signed_url_success(self, mock_put, client):
"""Test successful upload to signed URL."""
mock_put.return_value = MagicMock(status_code=200)
with tempfile.NamedTemporaryFile(delete=False, suffix=".flac") as f:
f.write(b"fake audio data")
temp_path = f.name
try:
result = client._upload_file_to_signed_url(
"https://storage.googleapis.com/signed-url",
temp_path,
"audio/flac"
)
assert result is True
mock_put.assert_called_once()
finally:
os.unlink(temp_path)
@patch('requests.put')
def test_upload_file_to_signed_url_failure(self, mock_put, client):
"""Test failed upload to signed URL."""
mock_put.return_value = MagicMock(status_code=403, text="Forbidden")
with tempfile.NamedTemporaryFile(delete=False, suffix=".flac") as f:
f.write(b"fake audio data")
temp_path = f.name
try:
result = client._upload_file_to_signed_url(
"https://storage.googleapis.com/signed-url",
temp_path,
"audio/flac"
)
assert result is False
finally:
os.unlink(temp_path)
@patch.object(RemoteKaraokeClient, '_upload_file_to_signed_url')
@patch.object(RemoteKaraokeClient, '_request')
def test_submit_job_uses_signed_url_flow(self, mock_request, mock_upload, client):
"""Test that submit_job uses the signed URL upload flow."""
# Mock create job response
create_response = MagicMock()
create_response.status_code = 200
create_response.json.return_value = {
"status": "success",
"job_id": "test-job-123",
"upload_urls": [
{
"file_type": "audio",
"gcs_path": "uploads/test-job-123/audio/test.flac",
"upload_url": "https://storage.googleapis.com/signed-url-1",
"content_type": "audio/flac"
}
]
}
# Mock uploads complete response
complete_response = MagicMock()
complete_response.status_code = 200
complete_response.json.return_value = {
"status": "success",
"job_id": "test-job-123",
"message": "Processing started"
}
mock_request.side_effect = [create_response, complete_response]
mock_upload.return_value = True
with tempfile.NamedTemporaryFile(delete=False, suffix=".flac") as f:
f.write(b"fake audio data")
temp_path = f.name
try:
result = client.submit_job(
filepath=temp_path,
artist="Test Artist",
title="Test Song"
)
# Verify the flow: create -> upload -> complete
assert mock_request.call_count == 2
# First call should be to create-with-upload-urls
first_call = mock_request.call_args_list[0]
assert first_call[0][0] == 'POST'
assert 'create-with-upload-urls' in first_call[0][1]
# Second call should be to uploads-complete
second_call = mock_request.call_args_list[1]
assert second_call[0][0] == 'POST'
assert 'uploads-complete' in second_call[0][1]
# Upload should have been called for the audio file
mock_upload.assert_called_once()
assert result["status"] == "success"
assert result["job_id"] == "test-job-123"
finally:
os.unlink(temp_path)
def test_client_has_signed_url_methods(self, client):
"""Test that RemoteKaraokeClient has the required signed URL methods."""
assert hasattr(client, '_upload_file_to_signed_url')
assert hasattr(client, '_get_content_type')
assert callable(client._upload_file_to_signed_url)
assert callable(client._get_content_type)