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.
Improves test coverage from ~62% to ~65%:
- Add tests for download_from_url function and URL-based job workflow
- Add tests for /api/jobs/create-from-url endpoint models
- Add tests for _validate_url with all supported domains
- Add tests for backend/validate.py (import, syntax, config checks)
- Add tests for worker_logging.py (JobLogger, JobLogHandler, job_logging_context)
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.
When multiple jobs run concurrently on the same Cloud Run instance,
logs from third-party libraries (karaoke_gen, lyrics_transcriber) were
being captured by all job handlers, causing log mixing between jobs.
This fix:
- Adds contextvars-based job ID tracking to worker_logging.py
- Adds job_logging_context() context manager for setting active job
- Filters log records in JobLogHandler.emit() by current context
- Wraps all worker processing in job_logging_context for isolation
Each job's logs now correctly stay isolated even when workers share
global Python loggers.
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
- 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
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.
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
- 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.
Use sanitize_filename for reference files and uncorrected transcription
filename construction, matching the fix applied to corrections filename.
Bump version to 0.71.16
- Make rclone cleanup() idempotent by always resetting state and clearing RCLONE_CONFIG env var
- Sanitize artist/title in lyrics_worker to prevent path injection when constructing correction filenames
Bump version to 0.71.15
- 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
- Update CI to use poetry instead of pip with frozen requirements
- Upgrade CI from Python 3.12 to 3.13 (matches pyproject.toml and dev env)
- Simplify Dockerfile.base to use pip install -e . directly
- Remove requirements-frozen.txt (caused Python version mismatches)
- Update documentation to reflect simpler setup
- Bundle lyrics-transcriber directly via pyproject.toml packages directive
instead of PyPI dependency, allowing rapid iteration without publishing
- Add all lyrics-transcriber dependencies to karaoke-gen's deps
- Optimize Docker builds: base image now contains only dependencies (no code),
app image adds code on top for fast ~1-2 min rebuilds
- Generate requirements-frozen.txt from poetry.lock for reproducible builds
- Update CI to use frozen requirements
- Add comprehensive documentation in docs/01-reference/VENDORED-LYRICS-TRANSCRIBER.md
with un-vendoring instructions for when changes are pushed upstream
- Fix temp file leak in review.py: Use BackgroundTask to clean up temp
files after FileResponse completes (affects audio streaming and
preview video endpoints)
- Fix event loop blocking in lyrics_worker.py: Wrap sync transcribe_lyrics()
call with asyncio.to_thread() since it runs for 1-2 minutes
- Remove unused variables: settings = get_settings() and temp_dir parameter
from create_lyrics_processor()
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.
- list_jobs() now supports environment, client_id, and date filters
- delete_jobs_by_filter() handles both Firestore and GCS cleanup
- Enables bulk cleanup of test jobs or jobs by client
Enables operational management by:
- list_jobs() now accepts environment, client_id, and date filters
- New delete_jobs_by_filter() for bulk cleanup operations
- Supports filtering test vs production jobs
- Supports cleanup of jobs by client ID or date range
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
This marks the first successful end-to-end run of karaoke-gen-remote with
the Google Cloud backend. All core features are now working:
- README.md completely rewritten with comprehensive documentation:
- Both CLI tools (karaoke-gen, karaoke-gen-remote) fully documented
- API reference for backend endpoints
- Infrastructure deployment guide with Pulumi
- Style configuration examples
- Output file structure
- BACKEND-FEATURE-PARITY-PLAN.md updated to reflect:
- All core processing features complete
- All distribution features working (YouTube, Dropbox, GDrive, Discord)
- Future architecture plans for shared pipeline refactor
- Comprehensive testing/deployment sections
- Job model enhanced with request_metadata field for operational tracking
The video worker was creating empty placeholder files for title_jpg/end_jpg
instead of downloading the actual images uploaded by the screens worker.
This caused YouTube thumbnail upload to fail silently (empty file).
Now downloads the real JPG files from GCS so YouTube thumbnail works.
Bump version to 0.70.35
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
- _save_credentials_to_secret now creates the secret if it doesn't exist
- Added comprehensive logging throughout device auth flow
- Return error if credential save fails (don't claim success)
- Added secretVersionManager IAM role in Pulumi for write access
- Added infrastructure-changes cursor rule
Version bump to 0.70.28
Cloud Run is stateless - in-memory _pending_device_auths dict was lost
between requests when hitting different instances. Now poll_device_auth
fetches client credentials directly from Secret Manager and calls Google
directly, no stored state needed.
Version bump to 0.70.27
- 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
Google's device auth API may return either key name depending on the endpoint version.
Added logging to help debug future issues.
Version bump to 0.70.25
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
- Add comprehensive tests for DropboxService methods (upload, shared links)
- Add comprehensive tests for GoogleDriveService methods (folder ops, uploads)
- Add tests for video worker native distribution handling
- Add tests for RemoteExecutor session and job status methods
- Add tests for PipelineContext cleanup and logging methods
- Fix test imports and mock paths
- Version bump to 0.70.23
Coverage now at 70.88% for karaoke_gen (required: 70%)
- Add unit tests for DropboxService (brand code calculation, configuration)
- Add unit tests for GoogleDriveService (configuration, singleton pattern)
- Add tests for Job model distribution fields (dropbox_path, gdrive_folder_id)
- Add tests for file upload endpoint distribution parameters
- Add pipeline tests for base classes, context, stages, and executors
- Add remote CLI tests for distribution parameter handling
- Version bump to 0.70.22