CodeRabbit fixes:
- Chain exceptions with 'from e' in jobs.py for proper tracebacks
- Use logger.exception() for automatic stack traces
- Add end_seconds validation warning in audio_editing_service.py
- Handle recommended_selection='with_backing' explicitly in frontend
- Sync audio player state with actual audio element via event listeners
- Fix muted duration stats overcounting by clamping to audio duration
- Add num_points validation (1-10000) in server waveform endpoint
- Improve exception handling in server endpoints
Test coverage improvements:
- Add comprehensive tests for InstrumentalReviewServer
- Test request/response models
- Test server initialization and configuration
- Test FastAPI endpoints with TestClient
- Coverage: karaoke_gen 73.05% (above 70% minimum)
Version bump: 0.71.39 → 0.71.40
Adds a comprehensive instrumental selection workflow with:
- Audio analysis to detect backing vocals (>-40dB threshold)
- Waveform visualization with segment highlighting
- Interactive web UI for audio playback and region selection
- Custom instrumental creation by muting selected regions
- Smart recommendations based on analysis results
- Feature parity between local (karaoke-gen) and remote (karaoke-gen-remote) CLIs
Key components:
- Shared core module (karaoke_gen/instrumental_review/) with AudioAnalyzer,
AudioEditor, WaveformGenerator, and InstrumentalReviewServer
- Backend services wrapping core module with GCS integration
- New API endpoints for analysis, audio streaming, and custom creation
- React frontend components for waveform display, audio playback, region selection
- Local HTTP server for browser-based review in local CLI workflow
- 1280 tests passing with comprehensive coverage
Closes the need for manual Audacity editing when selecting instrumentals.
1. _validate_url now handles None and non-string inputs safely
- Added early guard: if url is None or not isinstance(url, str)
- Updated function signature to accept Optional[str]
2. Fixed cookie tempfile leak in file_handler.py
- Use context manager pattern to safely write cookies
- Track cookie_file_path instead of cookie_file object
- Guaranteed cleanup in finally block
3. Removed unused style_params_path from submit_job_from_url
- URL-based jobs don't support custom styles (would need signed URL upload)
- Added warning when user provides --style_params_json with URL input
- Updated docstring to clarify limitation
Also merged latest main which added job_logging_context for log isolation.
Add support for searching and downloading audio by artist+title in remote mode,
enabling the same functionality as the local CLI's flacfetch integration.
New features:
- `karaoke-gen-remote "Artist" "Title"` - search for audio without providing a file
- `--auto-download` flag for automatic best-quality selection
- `-y` flag also triggers auto-download mode
- Interactive mode displays search results for user selection
Backend changes:
- New AudioSearchService integrating flacfetch library
- New API endpoints: POST /api/audio-search/search, GET /api/audio-search/{job_id}/results, POST /api/audio-search/{job_id}/select
- New job statuses: searching_audio, awaiting_audio_selection, downloading_audio
- Job model extended with audio_search_artist, audio_search_title, auto_download fields
Remote CLI changes:
- Detects artist+title input without file path
- Displays search results interactively
- Handles audio source selection flow
- Supports both interactive and auto-download modes
Tests:
- 20+ unit tests for AudioSearchService and Job model fields
- Tests for state transitions and API response handling
Documentation:
- Updated BACKEND-FEATURE-PARITY-PLAN.md with batch 5 status
Version bump: 0.71.26 -> 0.71.28
Resolves merge conflicts between Batch 4 (YouTube URL input) and Batch 3
(existing instrumental) which was merged while this branch was in progress.
Combined changes:
- Both Batch 3 and Batch 4 are now marked complete in documentation
- Remote CLI now supports both URL input AND existing_instrumental parameter
- Tests include both existing instrumental tests and URL input tests
- Updated poetry.lock with yt-dlp dependency
Implements YouTube URL input (P2 parameter) for the remote CLI and backend:
- Remote CLI: Detect URL input via is_url(), route to new submit_job_from_url() method
- Backend: New /api/jobs/create-from-url endpoint accepts URL with optional artist/title
- Backend: Audio worker downloads from URL using yt-dlp, auto-detects artist/title from metadata
- FileHandler: Added download_video() and extract_metadata_from_url() methods
- Dependencies: Added yt-dlp to pyproject.toml
Features:
- URL detection in remote CLI positional arguments
- Auto-detection of artist/title from YouTube video metadata
- Support for YouTube, Vimeo, SoundCloud, and other yt-dlp supported platforms
- Metadata cleanup (removes common suffixes like "Official Video")
- Cookie support for authenticated downloads (YOUTUBE_COOKIES env var)
Tests: 20+ unit tests covering URL validation, request/response models, Job URL field
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.
- Remove unused `settings` variable in mark_uploads_complete endpoint
- Rename duplicate TestGCSPathGeneration class to TestSignedUrlGCSPathGeneration
to avoid shadowing the original test class
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)
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
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
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.
- 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.
- Fix state_data_updates not being persisted in job transitions
- Fix double-close of file descriptor in rclone config setup
- Fix single-file category download URL generation
- Fix preview generation to raise HTTPException instead of returning error dict
- Fix tracer alias to use proper proxy class instead of broken property()
- Fix early return leaking log handlers in lyrics_worker
- Rename misleading test and add proper assertions
Bump version to 0.71.14
Created job_logging.py with:
- JobLogHandler: Custom logging handler that forwards Python logs to Firestore
- job_log_context: Context manager to capture all logs within a block
- JobLogger: Direct logging utility for job-specific messages
Updated review.py to use job_log_context for:
- add-lyrics endpoint: Captures LyricsTranscriber anchor search, correction logs
- preview-video endpoint: Captures video generation logs
This allows the CLI to see detailed processing logs in real-time when
polling /api/jobs/{job_id}/logs, including all the LyricsTranscriber
internal logs like "Anchor search processing" that were previously
only visible in Cloud Run stderr.
Bump version to 0.71.6
Address CodeRabbit PR review feedback:
- Add admin auth to internal worker endpoints and bulk delete
- Add request timeouts to all HTTP calls (credential_manager, tests)
- Fix async sleep in lyrics worker to not block event loop
- Fix background task garbage collection in review routes
- Fix exception chaining and f-string issues
- Remove duplicate emulators_running() function
- Update tests to include auth headers and test 401 responses
- Update remote CLI to actually use KARAOKE_GEN_AUTH_TOKEN env var
- Document authentication in README
The admin token is read from ADMIN_TOKENS env var (comma-separated).
WorkerService now includes the token when calling internal endpoints.
The add-lyrics endpoint was returning a stub "not yet implemented" message
even though the functionality exists in CorrectionOperations. This fix
implements the full endpoint that:
- Downloads current corrections.json from GCS
- Adds the new lyrics source using CorrectionOperations.add_lyrics_source()
- Uploads the updated corrections back to GCS
- Returns the updated correction data to the frontend
DELETE /api/jobs with filters:
- environment: Delete test/production jobs
- client_id: Delete by customer
- status: Delete failed/cancelled jobs
- created_before: Delete old jobs
Safety features:
- Requires at least one filter
- Requires confirm=true to execute
- Without confirm, returns preview of jobs to delete
GET /api/jobs now supports:
- environment: Filter by test/production/development
- client_id: Filter by customer identifier
- created_after/created_before: Date range filtering
Enables operational management via API.
Completes the request metadata tracking feature by:
- Adding Request parameter to upload_and_create_job
- Calling extract_request_metadata() to capture client info
- Passing metadata to JobCreate for storage
Implements request metadata capture to help with:
- Distinguishing test vs production jobs
- Tracking jobs by customer/client ID
- Debugging issues with specific clients
- Bulk cleanup of test jobs
Metadata captured includes:
- Client IP (with X-Forwarded-For support)
- User-Agent header
- Environment from X-Environment header
- Client ID from X-Client-ID header
- All custom X-* headers
- Server version at job creation
Bug: The update_data dictionary was using the original request values
(dropbox_path, gdrive_folder_id, discord_webhook_url) instead of the
effective values that include defaults from environment variables.
This caused distribution to not run even when defaults were configured,
because the job document was overwritten with null values.
Now uses effective_dropbox_path, effective_gdrive_folder_id, and
effective_discord_webhook_url when updating the job after file upload.
- Add backend/version.py to avoid circular imports
- Return server_version and distribution_services from /api/jobs/upload
- Display distribution service status (Dropbox, GDrive, YouTube, Discord) in remote CLI after job submission
- Show which services are enabled, using defaults, and have valid credentials
- Added DEFAULT_DROPBOX_PATH, DEFAULT_GDRIVE_FOLDER_ID, DEFAULT_DISCORD_WEBHOOK_URL
- Backend applies these defaults when not provided in request
- Simplifies remote CLI usage - no need to pass paths every time
- Discord webhook stored as secret (sensitive)
Version bump to 0.70.29
- Device auth endpoints now read client_id/client_secret from Secret Manager
- New secrets: youtube-client-credentials, gdrive-client-credentials
- Passing credentials in request body is now optional (for backwards compat)
- Simpler API: just POST to /api/auth/youtube/device with empty body
- Updated documentation
Version bump to 0.70.26
Implements comprehensive OAuth credential management for the backend:
1. CredentialManager service:
- Validates YouTube, Google Drive, and Dropbox credentials
- Automatically refreshes expired tokens
- Device Authorization Flow for re-authentication
- Discord alerts when credentials need attention
2. API endpoints (/api/auth/*):
- GET /status - Check all credential statuses
- POST /validate - Validate specific services before job submission
- POST /youtube/device - Start YouTube device auth flow
- GET /youtube/device/{code} - Poll for auth completion
- Similar endpoints for Google Drive
3. Pre-job validation:
- Jobs requiring YouTube/Dropbox/GDrive are rejected if credentials invalid
- Clear error messages with auth_url for re-authorization
4. Startup validation:
- Validates all credentials on backend startup
- Sends Discord alert if any credentials need attention
5. Documentation:
- docs/00-current-plan/OAUTH-CREDENTIAL-MANAGEMENT.md
- Covers credential setup, device flow, troubleshooting
Version bump to 0.70.24
Phase 1: Native API Distribution Services
- Add dropbox_service.py with native Dropbox SDK for folder listing, upload, and sharing links
- Add gdrive_service.py with native Google Drive API for folder uploads and public share
- Add dropbox_path and gdrive_folder_id fields to Job model and JobCreate
- Update file_upload.py API to accept new distribution parameters
- Update video_worker.py to use native services for distribution
- Add --dropbox_path and --gdrive_folder_id CLI arguments to remote CLI
- Add dropbox>=11.0.0 dependency to backend requirements
Phase 2: Shared Pipeline Architecture
- Create karaoke_gen/pipeline/ module with base classes and context
- Implement PipelineStage protocol and StageResult for consistent stage execution
- Add PipelineContext dataclass for passing state through stages
- Create SeparationStage wrapping AudioProcessor
- Create TranscriptionStage wrapping LyricsProcessor
- Create ScreensStage for title/end screen generation
- Create RenderStage for video rendering with lyrics
- Create FinalizeStage wrapping KaraokeFinalise
- Add LocalExecutor for in-process stage execution
- Add RemoteExecutor for backend API stage execution
This enables:
- Remote CLI to use native Dropbox/GDrive APIs instead of rclone
- Same output locations and brand codes as local CLI
- Foundation for unified pipeline that works in both local and cloud contexts
- Replace signed URL approach with streaming download endpoint
- Backend proxies files from GCS, no client auth needed
- /api/jobs/{job_id}/download/{category}/{file_key} endpoint
- CLI now downloads via HTTP through the backend
- Simpler architecture that works for both CLI and future web UI
Version bump to 0.70.19
- Add /api/jobs/{job_id}/download-urls endpoint that generates signed
URLs for all job output files (valid for 2 hours)
- Update remote CLI to fetch signed URLs and download via HTTP
- Fall back to gsutil if signed URLs fail
- This fixes the download failures when gcloud auth is not configured
Version bump to 0.70.18
Phase 1 of Backend Feature Parity Plan:
Dropbox Upload (rclone):
- Add organised_dir_rclone_root field to Job model
- Create backend/services/rclone_service.py to load rclone.conf from Secret Manager
- Wire through from API to video_worker and KaraokeFinalise
YouTube Upload:
- Create backend/services/youtube_service.py for OAuth credential management
- Load credentials from Secret Manager (youtube-oauth-credentials secret)
- Add --enable_youtube_upload flag to CLI
- Update video_worker to pass credentials to KaraokeFinalise
Other changes:
- Update remote_cli.py to support new distribution parameters
- Update BACKEND-FEATURE-PARITY-PLAN.md with implementation status
- Bump version to 0.70.12
This refactor addresses code duplication where style loading was implemented
separately in 5 different places, which led to bugs (like the preview video
not loading custom background images that was fixed in the previous commit).
New module: karaoke_gen/style_loader.py
- Single source of truth for DEFAULT_STYLE_PARAMS and ASSET_KEY_MAPPINGS
- load_styles_from_gcs() for backend workers to download/update styles
- update_asset_paths() to replace GCS paths with local downloaded files
- Helper functions: get_intro_format(), get_end_format(), get_karaoke_format()
Updated files to use the unified module:
- karaoke_gen/config.py: delegates to style_loader functions
- backend/workers/style_helper.py: StyleConfig now wraps style_loader
- backend/workers/render_video_worker.py: uses load_styles_from_gcs()
- backend/api/routes/review.py: uses load_styles_from_gcs()
Benefits:
- Asset key mappings defined once (was duplicated in 4+ places)
- Default styles defined once (was duplicated with slight variations)
- Future style changes only need to be made in one place
- Tests verify the unified module directly
Bump version to 0.70.6
When jobs had custom styles configured via --style_params_json, the preview
video in the review UI was showing a black background instead of the custom
background image. This was because the generate_preview_video endpoint in
review.py was creating "minimal styles" without loading the job's uploaded
style assets from GCS.
The fix adds _get_or_create_styles() to review.py (mirroring the logic in
render_video_worker.py) which:
- Checks if job has style_params_gcs_path configured
- Downloads style_params.json and all style assets from GCS
- Updates paths in the JSON to point to downloaded local files
- Falls back to minimal styles if no custom styles are configured
Also fixes several pre-existing test issues:
- test_style_upload.py: Fixed test using same directory for source and dest
- test_workers.py: Added required corrections.json to 3 tests
Bump version to 0.70.5
- Fix style loading to use job.style_params_gcs_path instead of
incorrect state_data['styles_gcs_path'] lookup
- Add job logging to render_video_worker for remote debugging
- Fix parallel worker execution using asyncio.gather() instead of
sequential BackgroundTasks (audio+lyrics now start simultaneously)
- Add emulator tests validating both fixes
- Bump version to 0.70.4
- Add LogEntry model and worker_logs field to Job for storing worker logs
- Create worker_logging.py with JobLogger class for dual logging (stdout + Firestore)
- Add /api/jobs/{job_id}/logs endpoint for fetching worker logs
- Update lyrics_worker and screens_worker to use JobLogger for remote debugging
- Update remote_cli to poll and display worker logs during job monitoring
- Add detailed logging of style configuration in screens_worker
- Log reference lyrics source (Genius, Spotify, Musixmatch, LRCLib) in lyrics_worker
This enables the karaoke-gen-remote CLI to show detailed worker logs
for debugging issues like missing styles or lyrics.
The file upload endpoint was awaiting audio worker completion before
starting the lyrics worker, defeating the parallel processing design.
Now both workers are triggered as separate background tasks, matching
the behavior of the URL submission endpoint.
- Accept 'test' as valid environment in config tests (pytest sets ENVIRONMENT=test)
- Add job status validation to preview-video endpoint (must be in review state)
- Update emulator integration test to expect 400 for non-review jobs
This commit implements the complete human review workflow for lyrics
correction, integrating the LyricsTranscriber React frontend with the
cloud backend.
Key changes:
- Add review.py router with endpoints compatible with LyricsTranscriber UI
- Add render_video_worker.py for post-review video generation
- Add RENDERING_VIDEO status and update state transitions
- Add fail_job() method to JobManager for proper error handling
- Fix lyrics_worker to upload corrections.json with correct filename
- Fix screens_worker to transition to AWAITING_REVIEW (not instrumental)
- Add storage_service methods: upload_json(), download_json()
The complete workflow now works:
1. Upload → parallel audio separation + lyrics transcription
2. Screen generation (title/end)
3. Human review via LyricsTranscriber UI (localhost:5173)
4. Preview video generation during review
5. Post-review video render with corrected lyrics
6. Instrumental selection (clean vs with_backing)
7. Final video encoding (4 formats: lossless mp4/mkv, lossy mp4, 720p)
8. Job completion
Tested end-to-end with local GCP emulators.