Compare commits

...
Author SHA1 Message Date
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
11 changed files with 1118 additions and 105 deletions

No files matched your search

+40
View File
@@ -126,6 +126,11 @@ 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)"),
):
"""
Upload an audio file and create a karaoke generation job with full style configuration.
@@ -182,6 +187,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
@@ -247,6 +262,10 @@ 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,
# Request metadata for tracking and filtering
request_metadata=request_metadata,
)
@@ -308,6 +327,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 +368,16 @@ 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
job_manager.update_job(job_id, update_data)
# Verify the update
+12
View File
@@ -211,6 +211,12 @@ 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)
# Processing state
track_output_dir: Optional[str] = None # Local output directory (temp)
audio_hash: Optional[str] = None # Hash for deduplication
@@ -373,6 +379,12 @@ 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)
# 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',
]
+161
View File
@@ -266,6 +266,167 @@ 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
if __name__ == "__main__":
pytest.main([__file__, "-v"])
+167
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."""
+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}")
@@ -1,10 +1,32 @@
# Backend Feature Parity Plan
**Last Updated:** 2024-12-10
**Status:** ✅ Core Feature Parity Achieved (v0.71.0)
**Status:** ✅ Core Feature Parity Achieved (v0.71.0) | Batch 1 Complete ✅
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 | 0 | 4 | **0%** | AP1-3, AP5 are HIGH priority |
| 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,490 @@ 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.). Skips audio separation entirely. |
| AP6 | `--instrumental_format` | 🗑️ | N/A | **REMOVE FROM LOCAL CLI.** FLAC is always fine, no need for format option. |
**Remote Implementation Plan:**
- **AP1-AP3 Model selection**: HIGH PRIORITY. All model options must work remotely! The Modal-hosted audio-separator API can download any model on demand and caches them. Just pass model name to API. Use case: A/B testing models, using newer models as they release.
- **AP4 `--model_file_dir`**: N/A for remote - Modal API handles model caching internally.
- **AP5 `--existing_instrumental`**: HIGH PRIORITY. User uploads instrumental file with job. Backend STILL runs separation (for consistent stem outputs in download folder), but uses provided instrumental for karaoke remux and final video. **VALIDATION REQUIRED**: At job start, validate provided instrumental duration matches input audio duration (within 0.5 seconds tolerance) to ensure sync before proceeding.
- **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)
**Parameters:** AP1 `--clean_instrumental_model`, AP2 `--backing_vocals_models`, AP3 `--other_stems_models`
**Scope:**
- Remote CLI: Add 3 form fields to `submit_job()`
- Backend: Add 3 Form parameters to upload endpoint
- Backend: Store in job, pass to audio worker
- Backend: Audio worker passes model names to Modal API (already supports any model)
**Files to modify:**
- `karaoke_gen/utils/remote_cli.py` - add to submit_job()
- `backend/api/routes/file_upload.py` - add Form fields
- `backend/workers/audio_worker.py` - pass model names to Modal API
**Complexity:** Low (Modal API already supports dynamic model selection)
---
### Batch 3: Existing Instrumental Support (HIGH)
**Parameters:** AP5 `--existing_instrumental`
**Scope:**
- Remote CLI: Upload instrumental file alongside audio file
- Backend: Accept instrumental file upload
- Backend: Validate duration matches input audio (±0.5s) at job start
- Backend: Still run separation for stems, but use provided instrumental for final video
- Backend: Store instrumental path, render worker uses it instead of separated instrumental
**Files to modify:**
- `karaoke_gen/utils/remote_cli.py` - upload instrumental file
- `backend/api/routes/file_upload.py` - accept instrumental upload, add validation
- `backend/workers/audio_worker.py` - mark instrumental source in outputs
- `backend/workers/render_worker.py` - use provided instrumental if present
**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 | ⏳ Pending |
| 3 | AP5 (existing instrumental) | HIGH | Medium | ⏳ Pending |
| 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 +611,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 |
|---------|---------|-----|-------|
| Lyrics override params | v0.71.22 | #8 | `--lyrics_artist`, `--lyrics_title`, `--lyrics_file`, `--subtitle_offset_ms` |
### ⏳ Not Yet Implemented
| Feature | Priority | Notes |
|---------|----------|-------|
| Audio model selection | HIGH | `--clean_instrumental_model`, `--backing_vocals_models`, `--other_stems_models` |
| Existing instrumental | HIGH | `--existing_instrumental` for re-processing |
| 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 +874,17 @@ DEFAULT_DISCORD_WEBHOOK_URL=https://discord.com/...
## Recent Changes Log
### 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 +930,43 @@ 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 - NEXT)
- Add `--clean_instrumental_model`, `--backing_vocals_models`, `--other_stems_models` support
- Files: `remote_cli.py`, `file_upload.py`, `audio_worker.py`
- Enables: A/B testing models, using newer models as they release
3. **Existing Instrumental** (Batch 3)
- Add `--existing_instrumental` upload support
- Files: `remote_cli.py`, `file_upload.py`, `audio_worker.py`, `render_worker.py`
- Enables: Re-processing with better instrumentals
4. **YouTube URL Input** (Batch 4)
- 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
+38
View File
@@ -199,6 +199,11 @@ 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,
) -> Dict[str, Any]:
"""
Submit a new karaoke generation job with optional style configuration.
@@ -217,6 +222,10 @@ 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
"""
file_path = Path(filepath)
@@ -270,6 +279,13 @@ class RemoteKaraokeClient:
files_to_upload[asset_key] = (Path(asset_path).name, asset_file, content_type)
self.logger.info(f" Will upload {asset_key}: {asset_path}")
# Upload lyrics file if provided
if lyrics_file and os.path.isfile(lyrics_file):
self.logger.info(f"Uploading lyrics file: {lyrics_file}")
lyrics_file_handle = open(lyrics_file, 'rb')
files_to_close.append(lyrics_file_handle)
files_to_upload['lyrics_file'] = (Path(lyrics_file).name, lyrics_file_handle, 'text/plain')
# Prepare form data
data = {
'artist': artist,
@@ -297,6 +313,14 @@ class RemoteKaraokeClient:
if organised_dir_rclone_root:
data['organised_dir_rclone_root'] = organised_dir_rclone_root
# Lyrics configuration
if lyrics_artist:
data['lyrics_artist'] = lyrics_artist
if lyrics_title:
data['lyrics_title'] = lyrics_title
if subtitle_offset_ms != 0:
data['subtitle_offset_ms'] = str(subtitle_offset_ms)
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)
@@ -1714,6 +1738,15 @@ 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")
logger.info(f"Service URL: {config.service_url}")
logger.info(f"Review UI: {config.review_ui_url}")
if config.non_interactive:
@@ -1747,6 +1780,11 @@ 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,
)
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.19"
version = "0.71.23"
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"