Compare commits

...
4 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.6 1c0eb8bf52 fix: prevent style_params.json lifecycle deletion, CDG font fallback, video worker state guard (#530)
## Summary
- Fix GCS lifecycle rule silently deleting `style_params.json` after 7
days by moving style files from `uploads/` to `jobs/` prefix
- Improve CDG font fallback chain to try bundled fonts by filename
before failing, preventing opaque `KeyError: 'font'` errors
- Add video worker state guard (matching audio/lyrics/render worker
pattern) to prevent cascading retry errors on failed jobs

## Changes
- **Style path prefix**: Changed all `uploads/{job_id}/style/`
references to `jobs/{job_id}/style/` in `theme_service.py`,
`file_upload.py`, `audio_search.py` and 7 test files
- **CDG font fallback**: Enhanced `_validate_and_setup_font()` with
5-step resolution (exact → bundled full path → bundled by filename →
arial.ttf → None), added None guard in `_create_toml_data()`,
absolutized all resolved paths
- **Video worker guard**: Added `validate_worker_can_run()` to both
orchestrated and legacy video pipelines, added terminal state check
(`failed`, `cancelled`, `complete`, `prep_complete`, `error`) to
`_check_worker_idempotency()`
- **Docs**: Added GCS lifecycle gotcha to LESSONS-LEARNED.md

## Context
Triggered by investigation of two production job failures:
- Job `2d4a7bab` (Mar 5): `style_params.json` 404 after 10 days — GCS
lifecycle rule deleted it
- Job `27054772` (Mar 14): CDG generation failed with `KeyError: 'font'`
when font couldn't be resolved, then Cloud Tasks retries produced
cascading `Invalid state transition: failed -> GENERATING_VIDEO` errors

## Testing
- [x] 2551 backend tests pass
- [x] 139 remote CLI tests pass
- [x] 10 new tests added (5 font fallback, 5 state guard/idempotency)

## Review
- [x] Local CodeRabbit review completed (3 findings, 2 fixed, 1 skipped
as nitpick)

@coderabbitai ignore

---
🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-15 16:19:59 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 c69b129893 fix: add lyrics_dir to transcribe_lyrics() for metadata storage (#529)
## Summary

- **Bug fix**: `transcribe_lyrics()` didn't include `lyrics_dir` in its
return dict, so `_store_lyrics_processing_metadata()` could never find
`corrections.json`. AudioShake IDs and correction stats were silently
lost in production (v0.142.0) because the metadata storage is wrapped in
try/except.
- **One-line fix**: Add `"lyrics_dir": lyrics_dir` to the
`transcriber_outputs` dict in `lyrics_processor.py`
- **Docs improvement**: Added "Test the Contract Between Caller and
Callee" guidance to `TESTING.md` and `/test-review` skill to prevent
this class of bug in future

## Why testing didn't catch it

The test for `_store_lyrics_processing_metadata` hand-crafted its input:
`transcription_result={"lyrics_dir": str(lyrics_dir)}`. This tested the
function in isolation — proving it works *if given correct input* — but
never verified the actual caller (`transcribe_lyrics()`) produces that
key. The mock was "too helpful."

This is especially dangerous with non-fatal code paths: the function is
designed to never crash (try/except), so the broken input silently did
nothing, and the test still passed.

## Test plan

- [x] 3 new tests: contract test (transcribe_lyrics returns lyrics_dir),
integration test (lyrics_dir points to corrections.json location),
regression test (pre-fix behavior: only duration stored without
lyrics_dir)
- [x] All 27 processing metadata tests pass
- [x] Verify in production: new jobs should show AudioShake IDs in
`processing_metadata.transcription`

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 11:16:20 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 694a7ff04e feat: add audio source details modal to admin panel (#528)
## Summary

- **Fix source detection**: `getJobSource` now checks
`audio_source_type` field first, correctly identifying audio search jobs
even when `audio_search_artist`/`audio_search_title` are null (was
showing upload icon for RED audio search jobs)
- **Add source details modal**: Clicking the source text opens a dialog
showing all available source metadata (type, provider, source ID,
filename, target file, download URL, etc.)
- **Add source fields to API**: Backend now includes
`audio_source_type`, `source_name`, `source_id`, `target_file`,
`download_url` in the summary field projection

## Test plan

- [x] Backend: Regression test asserting all source fields are in
`SUMMARY_FIELD_PATHS` (11 tests pass)
- [x] E2E regression: 3 new tests for source modal (audio search,
YouTube, file upload)
- [x] E2E regression: Updated existing YouTube source test for new modal
behavior
- [x] Full admin-job-detail E2E suite: 24/24 passing

<!-- @coderabbitai ignore -->

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 02:55:29 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 deb870a980 feat: store processing metadata permanently for all workers (#527)
## Summary

- Add `processing_metadata` field to Job model — immutable provenance
data written by each worker during processing, separate from
`state_data` (mutable workflow state)
- **Critical fix**: Persist AudioShake `task_id` and `asset_id` which
were previously lost after processing, requiring costly log/API recovery
for data exports
- Each worker writes its own section: transcription (AudioShake IDs),
separation (models, timing), rendering, encoding, distribution, audio
source (ffprobe), and worker timing
- All metadata writes are non-fatal (try/except wrapped) — never fails
jobs
- Stores auth context (`auth_method`, `user_type`,
`credits_at_creation`) and search query metadata at job creation
- Uses Firestore dot-notation for atomic section updates without
overwriting other workers' data

## Changes

- **Model**: `processing_metadata` field on Job,
`update_processing_metadata` helper on JobManager
- **Workers**: lyrics, audio, screens, render_video, video — each writes
timing + worker-specific metadata
- **AudioShake**: `asset_id` now stored in `TranscriptionData.metadata`,
flows through `corrections.json`
- **API routes**: `extract_request_metadata()` accepts optional
`auth_result` for auth context; audio search stores search query
- **Firestore**: `processing_metadata` added to `SUMMARY_FIELD_PATHS`
- **Tests**: 24 tests covering model, helpers, all worker functions,
error handling, SUMMARY_FIELD_PATHS regression guard

## Test plan

- [x] 24 new unit tests all passing
- [x] All 2512 existing tests pass
- [x] CodeRabbit review — fixed timing overwrite bug (deep dot-notation)
- [ ] Deploy and verify metadata appears on new jobs via Firestore
console

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 01:16:43 -04:00
37 changed files with 2210 additions and 117 deletions

No files matched your search

+22 -10
View File
@@ -240,24 +240,24 @@ class AudioSelectResponse(BaseModel):
selected_provider: str
def extract_request_metadata(request: Request, created_from: str = "audio_search") -> Dict[str, Any]:
def extract_request_metadata(request: Request, created_from: str = "audio_search", auth_result=None) -> Dict[str, Any]:
"""Extract metadata from request for job tracking."""
headers = dict(request.headers)
client_ip = headers.get('x-forwarded-for', '').split(',')[0].strip()
if not client_ip and request.client:
client_ip = request.client.host
user_agent = headers.get('user-agent', '')
environment = headers.get('x-environment', '')
client_id = headers.get('x-client-id', '')
custom_headers = {}
for key, value in headers.items():
if key.lower().startswith('x-') and key.lower() not in ('x-forwarded-for', 'x-forwarded-proto', 'x-forwarded-host'):
custom_headers[key] = value
return {
metadata = {
'client_ip': client_ip,
'user_agent': user_agent,
'environment': environment,
@@ -267,6 +267,17 @@ def extract_request_metadata(request: Request, created_from: str = "audio_search
'custom_headers': custom_headers,
}
# Add auth context for abuse investigation and analytics
if auth_result is not None:
metadata['auth_method'] = getattr(auth_result, 'auth_method', None)
user_type = getattr(auth_result, 'user_type', None)
metadata['user_type'] = user_type.value if hasattr(user_type, 'value') else str(user_type) if user_type else None
remaining = getattr(auth_result, 'remaining_uses', None)
if remaining is not None:
metadata['credits_at_creation'] = remaining
return metadata
def _extract_gcs_path(filepath: str) -> str:
"""
@@ -633,8 +644,9 @@ async def search_audio(
}
)
# Extract request metadata
request_metadata = extract_request_metadata(request, created_from="audio_search")
# Extract request metadata (includes auth context + search query info)
request_metadata = extract_request_metadata(request, created_from="audio_search", auth_result=auth_result)
request_metadata['search_query'] = {'artist': body.artist, 'title': body.title}
# Apply default theme if none specified
# This ensures all karaoke videos use the Nomad theme by default
@@ -754,11 +766,11 @@ async def search_audio(
# Generate GCS path
if file_info.file_type == 'style_params':
gcs_path = f"uploads/{job_id}/style/style_params.json"
gcs_path = f"jobs/{job_id}/style/style_params.json"
else:
# style_intro_background -> intro_background, etc.
asset_key = file_info.file_type.replace('style_', '')
gcs_path = f"uploads/{job_id}/style/{asset_key}{ext}"
gcs_path = f"jobs/{job_id}/style/{asset_key}{ext}"
# Generate signed upload URL
signed_url = storage_service.generate_signed_upload_url(
+37 -24
View File
@@ -268,10 +268,10 @@ storage_service = StorageService()
worker_service = get_worker_service()
def extract_request_metadata(request: Request, created_from: str = "upload") -> Dict[str, Any]:
def extract_request_metadata(request: Request, created_from: str = "upload", auth_result=None) -> Dict[str, Any]:
"""
Extract metadata from a FastAPI Request for job tracking.
Captures:
- Client IP address (handles X-Forwarded-For for proxies)
- User-Agent header
@@ -280,34 +280,36 @@ def extract_request_metadata(request: Request, created_from: str = "upload") ->
- All custom X-* headers
- Server version
- Creation source (upload/url)
- Auth context (method, user type) if auth_result provided
Args:
request: FastAPI Request object
created_from: How the job was created ("upload" or "url")
auth_result: Optional AuthResult from authentication
Returns:
Dict with metadata fields for storage in job.request_metadata
"""
headers = dict(request.headers)
# Extract client IP (check X-Forwarded-For for proxy scenarios)
client_ip = headers.get('x-forwarded-for', '').split(',')[0].strip()
if not client_ip and request.client:
client_ip = request.client.host
# Extract standard headers
user_agent = headers.get('user-agent', '')
environment = headers.get('x-environment', '') # test, production, development
client_id = headers.get('x-client-id', '') # Customer/user identifier
# Collect all X-* custom headers (excluding standard ones we already captured)
custom_headers = {}
for key, value in headers.items():
if key.lower().startswith('x-') and key.lower() not in ('x-forwarded-for', 'x-forwarded-proto', 'x-forwarded-host'):
# Normalize header name to original casing if possible
custom_headers[key] = value
return {
metadata = {
'client_ip': client_ip,
'user_agent': user_agent,
'environment': environment,
@@ -317,6 +319,17 @@ def extract_request_metadata(request: Request, created_from: str = "upload") ->
'custom_headers': custom_headers,
}
# Add auth context for abuse investigation and analytics
if auth_result is not None:
metadata['auth_method'] = getattr(auth_result, 'auth_method', None)
user_type = getattr(auth_result, 'user_type', None)
metadata['user_type'] = user_type.value if hasattr(user_type, 'value') else str(user_type) if user_type else None
remaining = getattr(auth_result, 'remaining_uses', None)
if remaining is not None:
metadata['credits_at_creation'] = remaining
return metadata
# File extension validation
ALLOWED_AUDIO_EXTENSIONS = {'.mp3', '.wav', '.flac', '.m4a', '.ogg', '.aac'}
@@ -564,7 +577,7 @@ async def upload_and_create_job(
)
# Extract request metadata for tracking and filtering
request_metadata = extract_request_metadata(request, created_from="upload")
request_metadata = extract_request_metadata(request, created_from="upload", auth_result=auth_result)
# Parse color_overrides from JSON if provided
parsed_color_overrides: Dict[str, str] = {}
@@ -709,7 +722,7 @@ async def upload_and_create_job(
# Upload style files if provided
if style_params:
style_gcs_path = f"uploads/{job_id}/style/style_params.json"
style_gcs_path = f"jobs/{job_id}/style/style_params.json"
logger.info(f"Uploading style params to GCS: {style_gcs_path}")
storage_service.upload_fileobj(
style_params.file,
@@ -728,7 +741,7 @@ async def upload_and_create_job(
(style_cdg_outro_background, "cdg_outro_background"),
]:
if img_file:
gcs_path = f"uploads/{job_id}/style/{asset_key}{Path(img_file.filename).suffix.lower()}"
gcs_path = f"jobs/{job_id}/style/{asset_key}{Path(img_file.filename).suffix.lower()}"
logger.info(f"Uploading {asset_key} to GCS: {gcs_path}")
storage_service.upload_fileobj(
img_file.file,
@@ -739,7 +752,7 @@ async def upload_and_create_job(
# Upload font file
if style_font:
font_gcs_path = f"uploads/{job_id}/style/font{Path(style_font.filename).suffix.lower()}"
font_gcs_path = f"jobs/{job_id}/style/font{Path(style_font.filename).suffix.lower()}"
logger.info(f"Uploading font to GCS: {font_gcs_path}")
storage_service.upload_fileobj(
style_font.file,
@@ -1063,11 +1076,11 @@ def _get_gcs_path_for_file(job_id: str, file_type: str, filename: str) -> str:
if file_type == 'audio':
return f"uploads/{job_id}/audio/{filename}"
elif file_type == 'style_params':
return f"uploads/{job_id}/style/style_params.json"
return f"jobs/{job_id}/style/style_params.json"
elif file_type.startswith('style_'):
# Map style_intro_background -> intro_background, etc.
asset_key = file_type.replace('style_', '')
return f"uploads/{job_id}/style/{asset_key}{ext}"
return f"jobs/{job_id}/style/{asset_key}{ext}"
elif file_type == 'lyrics_file':
return f"uploads/{job_id}/lyrics/user_lyrics{ext}"
elif file_type == 'existing_instrumental':
@@ -1195,7 +1208,7 @@ async def create_job_with_upload_urls(
)
# Extract request metadata for tracking
request_metadata = extract_request_metadata(request, created_from="signed_url_upload")
request_metadata = extract_request_metadata(request, created_from="signed_url_upload", auth_result=auth_result)
# Get original audio filename
audio_file = audio_files[0]
@@ -1360,10 +1373,10 @@ async def mark_uploads_complete(
if file_type == 'audio':
prefix = f"uploads/{job_id}/audio/"
elif file_type == 'style_params':
prefix = f"uploads/{job_id}/style/style_params"
prefix = f"jobs/{job_id}/style/style_params"
elif file_type.startswith('style_'):
asset_key = file_type.replace('style_', '')
prefix = f"uploads/{job_id}/style/{asset_key}"
prefix = f"jobs/{job_id}/style/{asset_key}"
elif file_type == 'lyrics_file':
prefix = f"uploads/{job_id}/lyrics/user_lyrics"
elif file_type == 'existing_instrumental':
@@ -1663,7 +1676,7 @@ async def create_job_from_url(
)
# Extract request metadata for tracking
request_metadata = extract_request_metadata(request, created_from="url")
request_metadata = extract_request_metadata(request, created_from="url", auth_result=auth_result)
# Use provided artist/title or leave as None (will be auto-detected by audio worker)
artist = body.artist
@@ -1857,7 +1870,7 @@ def _get_gcs_path_for_finalise_file(job_id: str, file_type: str, filename: str)
elif file_type == 'corrections':
return f"jobs/{job_id}/lyrics/corrections.json"
elif file_type == 'style_params':
return f"uploads/{job_id}/style/style_params.json"
return f"jobs/{job_id}/style/style_params.json"
else:
return f"uploads/{job_id}/other/{filename}"
@@ -1983,7 +1996,7 @@ async def create_finalise_only_job(
)
# Extract request metadata
request_metadata = extract_request_metadata(request, created_from="finalise_only_upload")
request_metadata = extract_request_metadata(request, created_from="finalise_only_upload", auth_result=auth_result)
# Apply default theme if none specified
# This ensures all karaoke videos use the Nomad theme by default
@@ -2189,7 +2202,7 @@ async def mark_finalise_uploads_complete(
elif file_type == 'corrections':
prefix = f"jobs/{job_id}/lyrics/corrections"
elif file_type == 'style_params':
prefix = f"uploads/{job_id}/style/style_params"
prefix = f"jobs/{job_id}/style/style_params"
else:
continue
@@ -2442,7 +2455,7 @@ async def complete_style_uploads(
continue
asset_key = file_type.replace('style_', '')
prefix = f"uploads/{job_id}/style/{asset_key}"
prefix = f"jobs/{job_id}/style/{asset_key}"
files = storage_service.list_files(prefix)
if not files:
raise HTTPException(
@@ -2483,7 +2496,7 @@ async def complete_style_uploads(
style_params["end"]["background_image"] = gcs_uri
# Upload updated style_params.json
style_params_path = f"uploads/{job_id}/style/style_params.json"
style_params_path = f"jobs/{job_id}/style/style_params.json"
storage_service.upload_json(style_params_path, style_params)
update_data["style_params_gcs_path"] = style_params_path
+12
View File
@@ -76,6 +76,18 @@ def _check_worker_idempotency(job_id: str, worker_name: str) -> Optional[WorkerR
message=f"Job {job_id} not found"
)
# Reject workers for jobs in terminal states (failed, cancelled, complete)
# This prevents Cloud Tasks retries from triggering workers on dead jobs
terminal_statuses = {'failed', 'cancelled', 'complete', 'prep_complete', 'error'}
job_status = job.status.value if hasattr(job.status, 'value') else str(job.status)
if job_status in terminal_statuses:
logger.info(f"[job:{job_id}] Job in terminal state '{job_status}', skipping {worker_name} worker")
return WorkerResponse(
status="skipped",
job_id=job_id,
message=f"Job is in terminal state '{job_status}', {worker_name} worker not needed"
)
# Check worker-specific progress in state_data
progress_key = f"{worker_name}_progress"
worker_progress = job.state_data.get(progress_key, {})
+37
View File
@@ -421,6 +421,43 @@ class Job(BaseModel):
}
"""
# Processing metadata (immutable provenance data written by workers during processing)
processing_metadata: Dict[str, Any] = Field(default_factory=dict)
"""
Immutable processing provenance data. Written once by each worker during processing.
Never modified after initial write. Used for analytics, debugging, and data export.
Structure:
{
"transcription": {
"provider": "audioshake",
"audioshake_task_id": "...",
"audioshake_asset_id": "...",
"language_detected": "en",
"word_count": 358,
"segment_count": 42,
},
"correction": {
"handlers_applied": [...],
"corrections_made": 12,
"correction_ratio": 0.034,
"reference_sources_found": ["genius", "spotify"],
"agentic_routing": "rule-based",
"duration_seconds": 33.2,
},
"separation": {
"provider": "modal",
"clean_model": "...",
"duration_seconds": 420.5,
},
"timing": {
"lyrics_worker_seconds": 125.3,
"audio_worker_seconds": 420.5,
...
},
}
"""
# Request metadata (captured at job creation for tracking and filtering)
request_metadata: Dict[str, Any] = Field(default_factory=dict)
"""
+3
View File
@@ -182,11 +182,14 @@ class FirestoreService:
SUMMARY_FIELD_PATHS = [
'job_id', 'status', 'progress', 'created_at', 'artist', 'title',
'error_message', 'non_interactive', 'outputs_deleted_at', 'user_email', 'is_private',
'url', 'filename', 'audio_search_artist', 'audio_search_title',
'audio_source_type', 'source_name', 'source_id', 'target_file', 'download_url',
'state_data.brand_code', 'state_data.youtube_url', 'state_data.dropbox_link',
'state_data.audio_progress', 'state_data.lyrics_progress',
'state_data.audio_complete', 'state_data.lyrics_complete',
'state_data.backing_vocals_analysis', 'state_data.visibility_change_in_progress',
'file_urls.finals', 'file_urls.videos', 'file_urls.packages',
'processing_metadata',
]
def list_jobs_summary(
+25
View File
@@ -748,6 +748,31 @@ class JobManager:
self.update_job(job_id, {'state_data': state_data})
logger.debug(f"Job {job_id} state_data updated: {key} = {value}")
def update_processing_metadata(self, job_id: str, section: str, data) -> None:
"""
Write data into processing_metadata[section] using Firestore dot-notation.
Each worker writes its own section once. This uses Firestore's nested
field update to avoid overwriting other workers' sections.
The section can use dot-notation for deeper nesting, e.g.
'timing.lyrics_worker_seconds' writes to processing_metadata.timing.lyrics_worker_seconds
without overwriting other timing entries.
Args:
job_id: Job ID
section: Metadata section path (e.g., 'transcription', 'timing.audio_worker_seconds')
data: Value to store (dict for sections, scalar for individual fields)
"""
try:
self.firestore.update_job(job_id, {
f"processing_metadata.{section}": data,
})
logger.debug(f"Job {job_id} processing_metadata.{section} updated")
except Exception as e:
# Log but don't raise - metadata storage should never fail a job
logger.warning(f"Job {job_id}: Failed to update processing_metadata.{section}: {e}")
def delete_state_data_key(self, job_id: str, key: str) -> bool:
"""
Delete a specific key from the job's state_data field.
+2 -1
View File
@@ -334,7 +334,8 @@ class ThemeService:
style_params = self._update_asset_paths_in_style(theme_id, style_params)
# Upload modified style_params.json to job's style folder
job_style_path = f"uploads/{job_id}/style/style_params.json"
# Uses jobs/ prefix (not uploads/) to avoid GCS lifecycle deletion rule
job_style_path = f"jobs/{job_id}/style/style_params.json"
self.storage.upload_json(job_style_path, style_params)
logger.info(f"Prepared job {job_id} style from theme {theme_id}")
@@ -150,15 +150,15 @@ class TestStyleLoadingFix:
}
# Upload style JSON to GCS (the CORRECT location)
style_gcs_path = f"uploads/{job_id}/style/style_params.json"
style_gcs_path = f"jobs/{job_id}/style/style_params.json"
self.storage.upload_string(json.dumps(style_json), style_gcs_path)
# Upload mock assets
assets = {
"intro_background": f"uploads/{job_id}/style/intro_background.png",
"karaoke_background": f"uploads/{job_id}/style/karaoke_background.png",
"end_background": f"uploads/{job_id}/style/end_background.png",
"font": f"uploads/{job_id}/style/font.ttf",
"intro_background": f"jobs/{job_id}/style/intro_background.png",
"karaoke_background": f"jobs/{job_id}/style/karaoke_background.png",
"end_background": f"jobs/{job_id}/style/end_background.png",
"font": f"jobs/{job_id}/style/font.ttf",
}
for asset_key, gcs_path in assets.items():
@@ -255,7 +255,7 @@ class TestStyleLoadingFix:
job_id = f"test-bug-{int(time.time() * 1000)}"
# Upload style to CORRECT location
style_gcs_path = f"uploads/{job_id}/style/style_params.json"
style_gcs_path = f"jobs/{job_id}/style/style_params.json"
self.storage.upload_string('{"karaoke": {"font_size": 100}}', style_gcs_path)
# Create job with styles in CORRECT location
+76
View File
@@ -7,6 +7,8 @@ Tests cover:
- Timestamp adjustment for instrumental audio sync
"""
import os
import pytest
from karaoke_gen.lyrics_transcriber.output.cdg import CDGGenerator
@@ -247,3 +249,77 @@ class TestCDGGenerateFromLRCWithCountdown:
# Verify _remove_countdown_from_lyrics was NOT called
mock_remove.assert_not_called()
class TestCDGFontFallback:
"""Test font resolution and fallback behavior in _validate_and_setup_font."""
@pytest.fixture
def generator(self, tmp_path):
return CDGGenerator(output_dir=str(tmp_path))
def test_absolute_path_that_exists_is_unchanged(self, generator, tmp_path):
"""An absolute path to an existing font is used as-is."""
font_file = tmp_path / "myfont.ttf"
font_file.write_bytes(b"fake font")
cdg_styles = {"font_path": str(font_file)}
generator._validate_and_setup_font(cdg_styles)
assert cdg_styles["font_path"] == str(font_file)
def test_nonexistent_path_falls_back_to_bundled_by_filename(self, generator):
"""A path like 'themes/nomad/assets/AvenirNext-Bold.ttf' should resolve
to the bundled AvenirNext-Bold.ttf by filename."""
cdg_styles = {"font_path": "themes/nomad/assets/AvenirNext-Bold.ttf"}
generator._validate_and_setup_font(cdg_styles)
assert cdg_styles["font_path"] is not None
assert cdg_styles["font_path"].endswith("AvenirNext-Bold.ttf")
assert os.path.isfile(cdg_styles["font_path"])
def test_totally_unknown_font_falls_back_to_arial(self, generator):
"""A completely unknown font name falls back to bundled arial.ttf."""
cdg_styles = {"font_path": "nonexistent/path/SuperRareFont.ttf"}
generator._validate_and_setup_font(cdg_styles)
assert cdg_styles["font_path"] is not None
assert cdg_styles["font_path"].endswith("arial.ttf")
assert os.path.isfile(cdg_styles["font_path"])
def test_none_font_path_is_left_alone(self, generator):
"""If font_path is already None, _validate_and_setup_font returns early."""
cdg_styles = {"font_path": None}
generator._validate_and_setup_font(cdg_styles)
assert cdg_styles["font_path"] is None
def test_create_toml_data_raises_on_none_font(self, generator):
"""_create_toml_data raises RuntimeError if font_path is None."""
cdg_styles = {
"font_path": None,
"clear_mode": "eager",
"sync_offset": 0,
"background_color": "#000000",
"border_color": "#000000",
"font_size": 18,
"stroke_width": 0,
"stroke_style": "octagon",
"active_fill": "#ffffff",
"active_stroke": "#000000",
"inactive_fill": "#888888",
"inactive_stroke": "#000000",
"title_color": "#ffffff",
"artist_color": "#ffffff",
"title_screen_background": "/tmp/fake.png",
"title_screen_transition": "centertexttoplogobottomtext",
"row": 4,
"line_tile_height": 3,
"lines_per_page": 4,
}
with pytest.raises(RuntimeError, match="CDG font_path is None"):
generator._create_toml_data(
title="Test",
artist="Artist",
audio_file="/tmp/audio.flac",
output_name="output",
sync_times=[100, 200],
instrumentals=[],
formatted_lyrics=["HELLO", "WORLD"],
cdg_styles=cdg_styles,
)
+3 -3
View File
@@ -698,21 +698,21 @@ class TestSignedUrlGCSPathGeneration:
from backend.api.routes.file_upload import _get_gcs_path_for_file
path = _get_gcs_path_for_file("test123", "style_params", "style.json")
assert path == "uploads/test123/style/style_params.json"
assert path == "jobs/test123/style/style_params.json"
def test_style_background_gcs_path(self):
"""Test GCS path generation for style background images."""
from backend.api.routes.file_upload import _get_gcs_path_for_file
path = _get_gcs_path_for_file("test123", "style_intro_background", "bg.png")
assert path == "uploads/test123/style/intro_background.png"
assert path == "jobs/test123/style/intro_background.png"
def test_style_font_gcs_path(self):
"""Test GCS path generation for font file."""
from backend.api.routes.file_upload import _get_gcs_path_for_file
path = _get_gcs_path_for_file("test123", "style_font", "font.ttf")
assert path == "uploads/test123/style/font.ttf"
assert path == "jobs/test123/style/font.ttf"
def test_lyrics_file_gcs_path(self):
"""Test GCS path generation for lyrics file."""
+781
View File
@@ -0,0 +1,781 @@
"""
Tests for processing_metadata field and related functionality.
Covers:
- Job model has processing_metadata field
- processing_metadata is in SUMMARY_FIELD_PATHS (regression test)
- update_processing_metadata helper works correctly
- AudioShake transcriber stores asset_id in metadata
- Corrector passes through transcription metadata
- extract_request_metadata includes auth context when provided
"""
import pytest
from unittest.mock import MagicMock, patch
from datetime import datetime
from backend.models.job import Job, JobStatus
class TestProcessingMetadataField:
"""Test the processing_metadata field on the Job model."""
def test_job_has_processing_metadata_field(self):
"""processing_metadata should exist and default to empty dict."""
job = Job(
job_id="test-123",
status=JobStatus.PENDING,
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
)
assert hasattr(job, 'processing_metadata')
assert job.processing_metadata == {}
def test_processing_metadata_serializes(self):
"""processing_metadata should serialize to JSON correctly."""
job = Job(
job_id="test-123",
status=JobStatus.PENDING,
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
processing_metadata={
"transcription": {
"provider": "audioshake",
"audioshake_task_id": "task-abc",
"audioshake_asset_id": "asset-xyz",
},
},
)
data = job.model_dump(mode='json')
assert data['processing_metadata']['transcription']['audioshake_task_id'] == "task-abc"
assert data['processing_metadata']['transcription']['audioshake_asset_id'] == "asset-xyz"
def test_processing_metadata_deserializes(self):
"""processing_metadata should deserialize from dict correctly."""
data = {
"job_id": "test-123",
"status": "pending",
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow(),
"processing_metadata": {
"separation": {
"provider": "modal",
"duration_seconds": 420.5,
},
},
}
job = Job(**data)
assert job.processing_metadata["separation"]["provider"] == "modal"
assert job.processing_metadata["separation"]["duration_seconds"] == 420.5
class TestSummaryFieldPaths:
"""Regression tests for SUMMARY_FIELD_PATHS."""
def test_processing_metadata_in_summary_field_paths(self):
"""processing_metadata must be in SUMMARY_FIELD_PATHS for dashboard queries."""
from backend.services.firestore_service import FirestoreService
assert 'processing_metadata' in FirestoreService.SUMMARY_FIELD_PATHS
class TestUpdateProcessingMetadata:
"""Test the JobManager.update_processing_metadata helper."""
@patch('backend.services.job_manager.FirestoreService')
@patch('backend.services.job_manager.StorageService')
def test_update_processing_metadata_uses_dot_notation(self, mock_storage_cls, mock_firestore_cls):
"""update_processing_metadata should use Firestore dot-notation for nested updates."""
from backend.services.job_manager import JobManager
mock_firestore = MagicMock()
mock_firestore_cls.return_value = mock_firestore
jm = JobManager()
jm.update_processing_metadata("job-123", "transcription", {
"provider": "audioshake",
"audioshake_task_id": "task-abc",
})
# Should call update_job with dot-notation key
mock_firestore.update_job.assert_called_once()
call_args = mock_firestore.update_job.call_args
assert call_args[0][0] == "job-123"
updates = call_args[0][1]
assert "processing_metadata.transcription" in updates
assert updates["processing_metadata.transcription"]["provider"] == "audioshake"
@patch('backend.services.job_manager.FirestoreService')
@patch('backend.services.job_manager.StorageService')
def test_update_processing_metadata_deep_dot_notation(self, mock_storage_cls, mock_firestore_cls):
"""Deeper dot-notation paths (e.g. timing.worker_seconds) avoid overwriting sibling fields."""
from backend.services.job_manager import JobManager
mock_firestore = MagicMock()
mock_firestore_cls.return_value = mock_firestore
jm = JobManager()
jm.update_processing_metadata("job-123", "timing.lyrics_worker_seconds", 42.5)
call_args = mock_firestore.update_job.call_args
updates = call_args[0][1]
assert "processing_metadata.timing.lyrics_worker_seconds" in updates
assert updates["processing_metadata.timing.lyrics_worker_seconds"] == 42.5
@patch('backend.services.job_manager.FirestoreService')
@patch('backend.services.job_manager.StorageService')
def test_update_processing_metadata_swallows_errors(self, mock_storage_cls, mock_firestore_cls):
"""update_processing_metadata should not raise on failure."""
from backend.services.job_manager import JobManager
mock_firestore = MagicMock()
mock_firestore.update_job.side_effect = Exception("Firestore error")
mock_firestore_cls.return_value = mock_firestore
jm = JobManager()
# Should not raise
jm.update_processing_metadata("job-123", "timing", {"foo": 1})
class TestAudioShakeAssetId:
"""Test that AudioShake transcriber stores asset_id in metadata."""
def test_convert_result_format_includes_asset_id(self):
"""_convert_result_format should include asset_id from task_data.assetId."""
from karaoke_gen.lyrics_transcriber.transcribers.audioshake import AudioShakeTranscriber
# Create a minimal transcriber instance
transcriber = AudioShakeTranscriber.__new__(AudioShakeTranscriber)
transcriber.logger = MagicMock()
transcriber._last_asset_id = "fallback-asset-id"
raw_data = {
"task_data": {
"id": "task-123",
"assetId": "asset-456",
"duration": 120.5,
"targets": [],
},
"transcription": {
"text": "hello world",
"lines": [
{
"text": "hello world",
"words": [
{"text": "hello", "start": 0.0, "end": 0.5},
{"text": "world", "start": 0.6, "end": 1.0},
],
}
],
"metadata": {"language": "en"},
},
}
result = transcriber._convert_result_format(raw_data)
assert result.metadata["task_id"] == "task-123"
assert result.metadata["asset_id"] == "asset-456"
assert result.metadata["language"] == "en"
def test_convert_result_format_fallback_asset_id(self):
"""asset_id should fall back to _last_asset_id if not in task_data."""
from karaoke_gen.lyrics_transcriber.transcribers.audioshake import AudioShakeTranscriber
transcriber = AudioShakeTranscriber.__new__(AudioShakeTranscriber)
transcriber.logger = MagicMock()
transcriber._last_asset_id = "fallback-asset-id"
raw_data = {
"task_data": {
"id": "task-123",
# No assetId in task_data
"targets": [],
},
"transcription": {
"text": "hello",
"lines": [
{
"text": "hello",
"words": [{"text": "hello", "start": 0.0, "end": 0.5}],
}
],
"metadata": {},
},
}
result = transcriber._convert_result_format(raw_data)
assert result.metadata["asset_id"] == "fallback-asset-id"
class TestCorrectorMetadataPassthrough:
"""Test that corrector passes through transcription metadata."""
def test_correction_result_includes_transcription_metadata(self):
"""CorrectionResult.metadata should include transcription_metadata from primary transcription."""
from karaoke_gen.lyrics_transcriber.correction.corrector import LyricsCorrector
from karaoke_gen.lyrics_transcriber.types import (
TranscriptionResult, TranscriptionData, LyricsSegment, Word
)
# Create a minimal corrector
corrector = LyricsCorrector(cache_dir="/tmp", enabled_handlers=[])
# Create transcription result with metadata
word = Word(id="w1", text="hello", start_time=0.0, end_time=0.5)
segment = LyricsSegment(id="s1", text="hello", words=[word], start_time=0.0, end_time=0.5)
transcription_data = TranscriptionData(
text="hello",
words=[word],
segments=[segment],
source="AudioShake",
metadata={
"task_id": "task-123",
"asset_id": "asset-456",
"language": "en",
},
)
transcription_result = TranscriptionResult(
name="AudioShake",
priority=1,
result=transcription_data,
)
# Run corrector with no reference lyrics (will skip correction but still build result)
result = corrector.run(
transcription_results=[transcription_result],
lyrics_results={},
)
# Check that transcription_metadata is passed through
assert "transcription_metadata" in result.metadata
assert result.metadata["transcription_metadata"]["task_id"] == "task-123"
assert result.metadata["transcription_metadata"]["asset_id"] == "asset-456"
class TestExtractRequestMetadataAuthContext:
"""Test that extract_request_metadata includes auth context."""
def _make_request(self):
"""Create a minimal mock request."""
request = MagicMock()
request.headers = {
"user-agent": "test-agent",
"x-forwarded-for": "1.2.3.4",
}
request.client = MagicMock()
request.client.host = "127.0.0.1"
return request
def test_auth_context_included_when_provided(self):
"""Auth context should be in metadata when auth_result is provided."""
from backend.api.routes.file_upload import extract_request_metadata
auth_result = MagicMock()
auth_result.auth_method = "session"
auth_result.user_type = MagicMock()
auth_result.user_type.value = "unlimited"
auth_result.remaining_uses = 42
metadata = extract_request_metadata(self._make_request(), auth_result=auth_result)
assert metadata['auth_method'] == "session"
assert metadata['user_type'] == "unlimited"
assert metadata['credits_at_creation'] == 42
def test_no_auth_context_without_auth_result(self):
"""No auth context should be added when auth_result is None."""
from backend.api.routes.file_upload import extract_request_metadata
metadata = extract_request_metadata(self._make_request())
assert 'auth_method' not in metadata
assert 'user_type' not in metadata
assert 'credits_at_creation' not in metadata
def test_audio_search_extract_includes_auth(self):
"""audio_search extract_request_metadata should also support auth_result."""
from backend.api.routes.audio_search import extract_request_metadata
auth_result = MagicMock()
auth_result.auth_method = "api_key"
auth_result.user_type = MagicMock()
auth_result.user_type.value = "limited"
auth_result.remaining_uses = 5
metadata = extract_request_metadata(self._make_request(), auth_result=auth_result)
assert metadata['auth_method'] == "api_key"
assert metadata['user_type'] == "limited"
assert metadata['credits_at_creation'] == 5
def test_auth_without_remaining_uses(self):
"""Should handle auth_result with no remaining_uses (e.g., admin)."""
from backend.api.routes.file_upload import extract_request_metadata
auth_result = MagicMock(spec=['auth_method', 'user_type'])
auth_result.auth_method = "admin_token"
auth_result.user_type = MagicMock()
auth_result.user_type.value = "admin"
metadata = extract_request_metadata(self._make_request(), auth_result=auth_result)
assert metadata['auth_method'] == "admin_token"
assert metadata['user_type'] == "admin"
assert 'credits_at_creation' not in metadata
def test_auth_with_none_user_type(self):
"""Should handle auth_result where user_type is None."""
from backend.api.routes.file_upload import extract_request_metadata
auth_result = MagicMock()
auth_result.auth_method = "session"
auth_result.user_type = None
auth_result.remaining_uses = 10
metadata = extract_request_metadata(self._make_request(), auth_result=auth_result)
assert metadata['auth_method'] == "session"
assert metadata['user_type'] is None
assert metadata['credits_at_creation'] == 10
class TestStoreLyricsProcessingMetadata:
"""Test the _store_lyrics_processing_metadata helper function."""
def test_extracts_audioshake_ids_from_corrections(self, tmp_path):
"""Should extract task_id and asset_id from corrections.json metadata."""
import json
from backend.workers.lyrics_worker import _store_lyrics_processing_metadata
# Create a mock corrections file
lyrics_dir = tmp_path / "lyrics"
lyrics_dir.mkdir()
corrections_file = lyrics_dir / "Artist - Title (Lyrics Corrections).json"
corrections_data = {
"metadata": {
"transcription_metadata": {
"task_id": "task-abc",
"asset_id": "asset-xyz",
"language": "en",
},
"enabled_handlers": ["anchor_sequence", "gap_word_count"],
"correction_ratio": 0.95,
"total_words": 100,
"agentic_routing": "rule-based",
"anchor_sequences_count": 5,
"gap_sequences_count": 3,
},
"corrections_made": 5,
"corrected_segments": [
{"words": [{"text": "w1"}, {"text": "w2"}]},
{"words": [{"text": "w3"}]},
],
"reference_lyrics": {"genius": {}, "spotify": {}},
}
corrections_file.write_text(json.dumps(corrections_data))
job_manager = MagicMock()
job_log = MagicMock()
_store_lyrics_processing_metadata(
job_manager=job_manager,
job_id="test-job",
transcription_result={"lyrics_dir": str(lyrics_dir)},
transcription_duration=45.6,
cache_stats={"downloaded": 2, "not_found": 1},
job_log=job_log,
)
# Check transcription metadata was stored
transcription_call = [
c for c in job_manager.update_processing_metadata.call_args_list
if c[0][1] == "transcription"
]
assert len(transcription_call) == 1
trans_data = transcription_call[0][0][2]
assert trans_data["provider"] == "audioshake"
assert trans_data["audioshake_task_id"] == "task-abc"
assert trans_data["audioshake_asset_id"] == "asset-xyz"
assert trans_data["segment_count"] == 2
assert trans_data["word_count"] == 3
assert trans_data["duration_seconds"] == 45.6
# Check correction metadata was stored
correction_call = [
c for c in job_manager.update_processing_metadata.call_args_list
if c[0][1] == "correction"
]
assert len(correction_call) == 1
corr_data = correction_call[0][0][2]
assert corr_data["corrections_made"] == 5
assert corr_data["handlers_applied"] == ["anchor_sequence", "gap_word_count"]
assert corr_data["reference_sources_found"] == ["genius", "spotify"]
# Check cache stats were stored
cache_call = [
c for c in job_manager.update_processing_metadata.call_args_list
if c[0][1] == "cache"
]
assert len(cache_call) == 1
cache_data = cache_call[0][0][2]
assert cache_data["transcription_cache_downloaded"] == 2
assert cache_data["transcription_cache_not_found"] == 1
def test_handles_missing_corrections_file(self):
"""Should not raise when corrections file is not found."""
from backend.workers.lyrics_worker import _store_lyrics_processing_metadata
job_manager = MagicMock()
job_log = MagicMock()
_store_lyrics_processing_metadata(
job_manager=job_manager,
job_id="test-job",
transcription_result={"lyrics_dir": "/nonexistent/path"},
transcription_duration=30.0,
cache_stats=None,
job_log=job_log,
)
# Should still store duration even without corrections file
transcription_call = [
c for c in job_manager.update_processing_metadata.call_args_list
if c[0][1] == "transcription"
]
assert len(transcription_call) == 1
assert transcription_call[0][0][2]["duration_seconds"] == 30.0
def test_swallows_exceptions(self):
"""Should not raise on unexpected errors."""
from backend.workers.lyrics_worker import _store_lyrics_processing_metadata
job_manager = MagicMock()
job_manager.update_processing_metadata.side_effect = Exception("boom")
job_log = MagicMock()
# Should not raise
_store_lyrics_processing_metadata(
job_manager=job_manager,
job_id="test-job",
transcription_result={"lyrics_dir": ""},
transcription_duration=10.0,
cache_stats=None,
job_log=job_log,
)
job_log.warning.assert_called()
def test_no_audioshake_ids_when_lyrics_dir_missing(self):
"""Without lyrics_dir, corrections.json can't be found — only duration is stored.
This is the exact bug that shipped in v0.142.0: transcribe_lyrics() didn't
include lyrics_dir in its return dict, so _store_lyrics_processing_metadata
could never find the corrections file and AudioShake IDs were silently lost.
"""
from backend.workers.lyrics_worker import _store_lyrics_processing_metadata
job_manager = MagicMock()
job_log = MagicMock()
# Simulate the pre-fix result dict — no lyrics_dir key at all
_store_lyrics_processing_metadata(
job_manager=job_manager,
job_id="test-job",
transcription_result={"lrc_filepath": "/tmp/output.lrc"}, # no lyrics_dir!
transcription_duration=45.0,
cache_stats=None,
job_log=job_log,
)
# Only duration should be stored — no AudioShake IDs, no correction stats
transcription_call = [
c for c in job_manager.update_processing_metadata.call_args_list
if c[0][1] == "transcription"
]
assert len(transcription_call) == 1
trans_data = transcription_call[0][0][2]
assert trans_data["duration_seconds"] == 45.0
assert "audioshake_task_id" not in trans_data
assert "provider" not in trans_data
# No correction metadata should be stored
correction_calls = [
c for c in job_manager.update_processing_metadata.call_args_list
if c[0][1] == "correction"
]
assert len(correction_calls) == 0
class TestTranscribeLyricsReturnsLyricsDir:
"""Contract test: transcribe_lyrics() must include lyrics_dir in its return dict.
This is the test that would have caught the v0.142.0 bug. The previous test suite
only tested _store_lyrics_processing_metadata in isolation with a hand-crafted input
that included lyrics_dir — it never verified the actual caller provides that key.
Testing lesson: When function A calls function B, don't just test B with ideal inputs.
Also verify A actually produces those inputs. Test the contract between caller and callee.
"""
@patch('karaoke_gen.lyrics_processor.LyricsTranscriber')
@patch('karaoke_gen.lyrics_processor.load_dotenv')
def test_transcribe_lyrics_returns_lyrics_dir(self, mock_dotenv, mock_transcriber_cls, tmp_path):
"""transcribe_lyrics() result must contain lyrics_dir pointing to the lyrics subdirectory."""
from karaoke_gen.lyrics_processor import LyricsProcessor
# Set up mock transcriber result
mock_results = MagicMock()
mock_results.lrc_filepath = str(tmp_path / "lyrics" / "output.lrc")
mock_results.ass_filepath = str(tmp_path / "lyrics" / "output.ass")
mock_results.video_filepath = str(tmp_path / "lyrics" / "output.mkv")
mock_results.transcription_corrected = None # skip correction output
mock_results.countdown_padding_added = False
mock_results.countdown_padding_seconds = 0.0
mock_results.padded_audio_filepath = None
mock_transcriber_cls.return_value.process.return_value = mock_results
# Create necessary dirs and a dummy audio file
lyrics_dir = tmp_path / "lyrics"
lyrics_dir.mkdir(exist_ok=True)
(tmp_path / "lyrics" / "output.lrc").write_text("[00:00.00] test")
(tmp_path / "lyrics" / "output.mkv").write_bytes(b"fake")
lrc_dest = tmp_path / "Artist - Title (Karaoke).lrc"
mkv_dest = tmp_path / "Artist - Title (With Vocals).mkv"
processor = LyricsProcessor.__new__(LyricsProcessor)
processor.logger = MagicMock()
processor.lyrics_file = None
processor.render_video = False
processor.skip_transcription = False
processor.skip_transcription_review = True
processor.style_params_json = None
processor.subtitle_offset_ms = 0
with patch.dict('os.environ', {
'AUDIOSHAKE_API_TOKEN': 'fake-token',
}):
result = processor.transcribe_lyrics(
input_audio_wav=str(tmp_path / "audio.wav"),
artist="Artist",
title="Title",
track_output_dir=str(tmp_path),
)
# THE KEY ASSERTION: lyrics_dir must be in the result
assert "lyrics_dir" in result, (
"transcribe_lyrics() must return lyrics_dir so _store_lyrics_processing_metadata "
"can find corrections.json. This was the v0.142.0 bug."
)
assert result["lyrics_dir"] == str(tmp_path / "lyrics")
def test_lyrics_dir_matches_corrections_file_location(self, tmp_path):
"""The lyrics_dir returned by transcribe_lyrics must be where corrections.json lives.
This verifies the contract: _store_lyrics_processing_metadata looks for corrections
files in result['lyrics_dir'], and transcribe_lyrics writes them to {track_output_dir}/lyrics.
"""
import json
from backend.workers.lyrics_worker import _store_lyrics_processing_metadata
# Simulate a result dict with lyrics_dir set correctly
lyrics_dir = tmp_path / "lyrics"
lyrics_dir.mkdir()
# Write a corrections file in the same location transcribe_lyrics would
corrections_file = lyrics_dir / "Artist - Title (Lyrics Corrections).json"
corrections_file.write_text(json.dumps({
"metadata": {
"transcription_metadata": {"task_id": "t1", "asset_id": "a1"},
"enabled_handlers": [],
},
"corrections_made": 0,
"corrected_segments": [],
}))
job_manager = MagicMock()
job_log = MagicMock()
# Use the result dict shape that transcribe_lyrics now produces
_store_lyrics_processing_metadata(
job_manager=job_manager,
job_id="test-job",
transcription_result={
"lyrics_dir": str(lyrics_dir),
"lrc_filepath": str(tmp_path / "output.lrc"),
},
transcription_duration=30.0,
cache_stats=None,
job_log=job_log,
)
# AudioShake IDs should be extracted successfully
transcription_call = [
c for c in job_manager.update_processing_metadata.call_args_list
if c[0][1] == "transcription"
]
assert len(transcription_call) == 1
trans_data = transcription_call[0][0][2]
assert trans_data["provider"] == "audioshake"
assert trans_data["audioshake_task_id"] == "t1"
assert trans_data["audioshake_asset_id"] == "a1"
class TestStoreAudioSourceMetadata:
"""Test the _store_audio_source_metadata helper function."""
@patch('subprocess.run')
def test_parses_ffprobe_output(self, mock_run):
"""Should parse ffprobe JSON output and store audio properties."""
import json
from backend.workers.audio_worker import _store_audio_source_metadata
mock_run.return_value = MagicMock(
returncode=0,
stdout=json.dumps({
"format": {
"format_name": "flac",
"duration": "210.4",
"size": "26541900",
"bit_rate": "1008000",
},
"streams": [
{
"codec_type": "audio",
"codec_name": "flac",
"sample_rate": "44100",
"channels": 2,
"bits_per_raw_sample": "16",
}
],
}),
)
job_manager = MagicMock()
job_log = MagicMock()
_store_audio_source_metadata(job_manager, "job-123", "/fake/audio.flac", job_log)
job_manager.update_processing_metadata.assert_called_once()
call_args = job_manager.update_processing_metadata.call_args
assert call_args[0][1] == "audio_source"
data = call_args[0][2]
assert data["input_format"] == "flac"
assert data["input_codec"] == "flac"
assert data["input_sample_rate"] == 44100
assert data["input_channels"] == 2
assert data["input_bit_depth"] == 16
assert data["input_duration_seconds"] == 210.4
assert data["input_file_size_bytes"] == 26541900
assert data["input_bitrate_kbps"] == 1008
@patch('subprocess.run')
def test_handles_ffprobe_failure(self, mock_run):
"""Should not raise when ffprobe fails."""
from backend.workers.audio_worker import _store_audio_source_metadata
mock_run.return_value = MagicMock(returncode=1, stderr="No such file")
job_manager = MagicMock()
job_log = MagicMock()
_store_audio_source_metadata(job_manager, "job-123", "/bad/path", job_log)
job_manager.update_processing_metadata.assert_not_called()
job_log.warning.assert_called()
@patch('subprocess.run')
def test_handles_missing_audio_stream(self, mock_run):
"""Should handle files with no audio stream gracefully."""
import json
from backend.workers.audio_worker import _store_audio_source_metadata
mock_run.return_value = MagicMock(
returncode=0,
stdout=json.dumps({
"format": {"format_name": "mp4", "duration": "30.0", "size": "1000"},
"streams": [{"codec_type": "video", "codec_name": "h264"}],
}),
)
job_manager = MagicMock()
job_log = MagicMock()
_store_audio_source_metadata(job_manager, "job-123", "/fake/video.mp4", job_log)
job_manager.update_processing_metadata.assert_called_once()
data = job_manager.update_processing_metadata.call_args[0][2]
# Should have format-level data but no audio stream data
assert data["input_format"] == "mp4"
assert "input_codec" not in data
class TestStoreVideoProcessingMetadata:
"""Test the _store_video_processing_metadata helper function."""
def test_stores_encoding_and_distribution_metadata(self, tmp_path):
"""Should store encoding time, formats, and distribution info."""
from backend.workers.video_worker import _store_video_processing_metadata
# Create mock result with some files existing
result = MagicMock()
result.encoding_time_seconds = 180.5
result.youtube_url = "https://youtube.com/watch?v=abc"
result.youtube_upload_queued = False
result.dropbox_link = "https://dropbox.com/s/xxx"
result.gdrive_files = {"4k": "file-id-1"}
result.brand_code = "NOMAD0001"
# Create a temp file to simulate output
lossless = tmp_path / "output.mp4"
lossless.write_bytes(b"x" * 1000)
result.final_video = str(lossless)
result.final_video_mkv = None
result.final_video_lossy = None
result.final_video_720p = None
job_manager = MagicMock()
_store_video_processing_metadata(job_manager, "job-123", result, 300.0)
calls = {c[0][1]: c[0][2] for c in job_manager.update_processing_metadata.call_args_list}
# Check encoding
assert "encoding" in calls
assert calls["encoding"]["encoding_time_seconds"] == 180.5
assert "lossless_4k_mp4" in calls["encoding"]["output_formats"]
assert calls["encoding"]["output_sizes_bytes"]["lossless_4k_mp4"] == 1000
# Check distribution
assert "distribution" in calls
assert calls["distribution"]["youtube_video_url"] == "https://youtube.com/watch?v=abc"
assert calls["distribution"]["brand_code"] == "NOMAD0001"
assert calls["distribution"]["gdrive_file_count"] == 1
# Check timing (uses deep dot-notation to avoid overwriting other workers' timing)
assert "timing.video_worker_seconds" in calls
assert calls["timing.video_worker_seconds"] == 300.0
def test_swallows_exceptions(self):
"""Should not raise on errors."""
from backend.workers.video_worker import _store_video_processing_metadata
job_manager = MagicMock()
job_manager.update_processing_metadata.side_effect = Exception("boom")
result = MagicMock()
result.encoding_time_seconds = None
# Should not raise
_store_video_processing_metadata(job_manager, "job-123", result, 100.0)
class TestAudioShakeStartTranscriptionAssetId:
"""Test that start_transcription stores _last_asset_id."""
def test_start_transcription_stores_last_asset_id(self):
"""start_transcription should store _last_asset_id for metadata fallback."""
from karaoke_gen.lyrics_transcriber.transcribers.audioshake import AudioShakeTranscriber
transcriber = AudioShakeTranscriber.__new__(AudioShakeTranscriber)
transcriber.logger = MagicMock()
# Mock the API and upload optimizer
transcriber.api = MagicMock()
transcriber.api.upload_file.return_value = "asset-from-upload"
transcriber.api.create_task.return_value = "task-from-create"
transcriber.upload_optimizer = MagicMock()
transcriber.upload_optimizer.prepare_for_upload.return_value = ("/fake/path", None)
task_id = transcriber.start_transcription("/fake/audio.flac")
assert task_id == "task-from-create"
assert transcriber._last_asset_id == "asset-from-upload"
+14
View File
@@ -446,6 +446,20 @@ class TestSummaryEndpoint:
assert _prune_state_data({}) == {}
assert _prune_state_data({'state_data': None}) == {'state_data': None}
def test_summary_projection_includes_source_fields(self):
"""Verify SUMMARY_FIELD_PATHS includes audio source tracking fields.
These fields are required for the Source column in the admin dashboard
and the source details modal. Without them, the dashboard incorrectly
shows audio search jobs as file uploads when audio_search_artist/title
are null.
"""
from backend.services.firestore_service import FirestoreService
paths = FirestoreService.SUMMARY_FIELD_PATHS
for field in ['url', 'filename', 'audio_search_artist', 'audio_search_title',
'audio_source_type', 'source_name', 'source_id', 'target_file', 'download_url']:
assert field in paths, f"{field} must be in summary projection for source details modal"
def test_prune_file_urls_keeps_allowed_keys(self):
"""Verify _prune_file_urls keeps only dashboard-required keys."""
from backend.api.routes.jobs import _prune_file_urls
+4 -4
View File
@@ -328,13 +328,13 @@ class TestPreviewStyleLoading:
# Call the unified style loader function
style_assets = {
"style_params": "uploads/test123/style/style_params.json",
"karaoke_background": "uploads/test123/style/karaoke_background.png",
"font": "uploads/test123/style/font.ttf",
"style_params": "jobs/test123/style/style_params.json",
"karaoke_background": "jobs/test123/style/karaoke_background.png",
"font": "jobs/test123/style/font.ttf",
}
styles_path, result_styles = load_styles_from_gcs(
style_params_gcs_path="uploads/test123/style/style_params.json",
style_params_gcs_path="jobs/test123/style/style_params.json",
style_assets=style_assets,
temp_dir=str(tmp_path / "workdir"),
download_func=mock_download,
+2 -2
View File
@@ -180,8 +180,8 @@ class TestStyleHelper:
# Mock job with style assets
job = Mock()
job.job_id = "test-123"
job.style_assets = {"style_params": "uploads/test/style_params.json"}
job.style_params_gcs_path = "uploads/test/style_params.json"
job.style_assets = {"style_params": "jobs/test/style_params.json"}
job.style_params_gcs_path = "jobs/test/style_params.json"
# Mock storage to "download" the file
storage = Mock()
+2 -2
View File
@@ -251,7 +251,7 @@ class TestCompleteStyleUploads:
self, mock_job_manager, mock_storage_service, admin_auth, pending_job
):
mock_job_manager.get_job.return_value = pending_job
mock_storage_service.list_files.return_value = ["uploads/job-abc/style/karaoke_background.png"]
mock_storage_service.list_files.return_value = ["jobs/job-abc/style/karaoke_background.png"]
# Mock theme service
with patch('backend.api.routes.file_upload.get_theme_service') as mock_get_ts:
@@ -287,7 +287,7 @@ class TestCompleteStyleUploads:
self, mock_job_manager, mock_storage_service, admin_auth, pending_job
):
mock_job_manager.get_job.return_value = pending_job
mock_storage_service.list_files.return_value = ["uploads/job-abc/style/intro_background.png"]
mock_storage_service.list_files.return_value = ["jobs/job-abc/style/intro_background.png"]
with patch('backend.api.routes.file_upload.get_theme_service') as mock_get_ts:
mock_ts = Mock()
+2 -2
View File
@@ -336,7 +336,7 @@ class TestThemeService:
# Should upload modified style_params.json
mock_storage.upload_json.assert_called_once()
assert style_path == "uploads/job123/style/style_params.json"
assert style_path == "jobs/job123/style/style_params.json"
def test_prepare_job_style_with_overrides(self, mock_storage, sample_metadata, sample_style_params):
"""Test prepare_job_style applies color overrides."""
@@ -355,7 +355,7 @@ class TestThemeService:
uploaded_path = call_args[0][0] # First positional arg is the path
uploaded_style = call_args[0][1] # Second positional arg is the data
assert uploaded_path == "uploads/job123/style/style_params.json"
assert uploaded_path == "jobs/job123/style/style_params.json"
# Check that artist_color override was applied
assert uploaded_style["intro"]["artist_color"] == "#FF0000"
assert uploaded_style["end"]["artist_color"] == "#FF0000"
+100
View File
@@ -1395,3 +1395,103 @@ class TestLyricsWorkerCountdownState:
assert lyrics_metadata['has_countdown_padding'] is True
assert lyrics_metadata['countdown_padding_seconds'] == 3.0
class TestVideoWorkerStateGuard:
"""Tests for video worker state validation."""
@pytest.fixture
def failed_job(self):
return Job(
job_id="test-failed",
status=JobStatus.FAILED,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test",
title="Song",
state_data={"instrumental_selection": "clean"},
file_urls={
"stems": {"instrumental_clean": "gs://test"},
"screens": {"title": "gs://t", "end": "gs://e"},
"videos": {"with_vocals": "gs://v"},
"lyrics": {"lrc": "gs://lrc"},
},
)
def test_validate_worker_can_run_rejects_failed_job(self, failed_job):
"""validate_worker_can_run returns error for failed jobs."""
from backend.services.job_health_service import validate_worker_can_run
result = validate_worker_can_run("video_worker", failed_job)
assert result is not None
assert "failed" in result.lower()
def test_validate_worker_can_run_accepts_instrumental_selected(self):
"""validate_worker_can_run allows instrumental_selected jobs."""
from backend.services.job_health_service import validate_worker_can_run
job = Job(
job_id="test-ok",
status=JobStatus.INSTRUMENTAL_SELECTED,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test",
title="Song",
)
result = validate_worker_can_run("video_worker", job)
assert result is None
class TestWorkerIdempotencyTerminalState:
"""Tests for _check_worker_idempotency terminal state handling."""
def test_idempotency_rejects_failed_job(self):
"""Idempotency check returns skip response for failed jobs."""
from backend.api.routes.internal import _check_worker_idempotency
failed_job = Job(
job_id="test-failed",
status=JobStatus.FAILED,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test",
title="Song",
)
with patch("backend.api.routes.internal.JobManager") as MockJM:
MockJM.return_value.get_job.return_value = failed_job
result = _check_worker_idempotency("test-failed", "video")
assert result is not None
assert result.status == "skipped"
assert "terminal state" in result.message.lower()
def test_idempotency_rejects_cancelled_job(self):
"""Idempotency check returns skip response for cancelled jobs."""
from backend.api.routes.internal import _check_worker_idempotency
cancelled_job = Job(
job_id="test-cancelled",
status=JobStatus.CANCELLED,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test",
title="Song",
)
with patch("backend.api.routes.internal.JobManager") as MockJM:
MockJM.return_value.get_job.return_value = cancelled_job
result = _check_worker_idempotency("test-cancelled", "video")
assert result is not None
assert result.status == "skipped"
def test_idempotency_allows_instrumental_selected_job(self):
"""Idempotency check allows jobs in non-terminal states."""
from backend.api.routes.internal import _check_worker_idempotency
job = Job(
job_id="test-ok",
status=JobStatus.INSTRUMENTAL_SELECTED,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test",
title="Song",
)
with patch("backend.api.routes.internal.JobManager") as MockJM:
mock_jm = MockJM.return_value
mock_jm.get_job.return_value = job
mock_jm.update_state_data.return_value = None
result = _check_worker_idempotency("test-ok", "video")
assert result is None
+77 -2
View File
@@ -330,6 +330,9 @@ async def process_audio_separation(job_id: str) -> bool:
download_span.set_attribute("audio_file", os.path.basename(audio_path))
download_span.set_attribute("source", "url" if job.url else "gcs")
# Capture input audio properties via ffprobe (before any processing)
_store_audio_source_metadata(job_manager, job_id, audio_path, job_log)
# Update progress using state_data (don't change status during parallel processing)
# The status is managed at a higher level - workers just track their progress
job_manager.update_state_data(job_id, 'audio_progress', {
@@ -414,11 +417,22 @@ async def process_audio_separation(job_id: str) -> bool:
logger.info(f"[job:{job_id}] All stems uploaded successfully")
# Store processing metadata for separation provenance
duration = time.time() - start_time
job_manager.update_processing_metadata(job_id, "separation", {
"provider": "modal",
"clean_model": effective_model_names['clean_instrumental_model'],
"backing_models": effective_model_names['backing_vocals_models'],
"other_models": effective_model_names['other_stems_models'],
"stems_generated": list(separation_result.keys()),
"duration_seconds": round(sep_duration, 1),
})
job_manager.update_processing_metadata(job_id, "timing.audio_worker_seconds", round(duration, 1))
# Mark audio processing complete
# This will check if lyrics are also complete and transition to next stage if so
job_manager.mark_audio_complete(job_id)
duration = time.time() - start_time
root_span.set_attribute("duration_seconds", duration)
logger.info(f"[job:{job_id}] WORKER_END worker=audio status=success duration={duration:.1f}s")
return True
@@ -668,6 +682,67 @@ async def upload_separation_results(
logger.info(f"Job {job_id}: Stored instrumental options: {list(instrumental_options.keys())}")
def _store_audio_source_metadata(
job_manager: JobManager,
job_id: str,
audio_path: str,
job_log,
) -> None:
"""Run ffprobe on input audio and store properties in processing_metadata.
Captures format, codec, sample rate, channels, duration, file size, and bitrate.
Non-fatal: failures are logged but don't stop the job.
"""
import subprocess
import json as _json
try:
result = subprocess.run(
[
"ffprobe", "-v", "quiet", "-print_format", "json",
"-show_format", "-show_streams", audio_path,
],
capture_output=True, text=True, timeout=30,
)
if result.returncode != 0:
job_log.warning(f"ffprobe failed (rc={result.returncode}): {result.stderr[:200]}")
return
probe = _json.loads(result.stdout)
fmt = probe.get("format", {})
# Find audio stream
audio_stream = None
for stream in probe.get("streams", []):
if stream.get("codec_type") == "audio":
audio_stream = stream
break
metadata = {
"input_format": fmt.get("format_name", "").split(",")[0],
"input_duration_seconds": round(float(fmt.get("duration", 0)), 1),
"input_file_size_bytes": int(fmt.get("size", 0)),
"input_bitrate_kbps": round(int(fmt.get("bit_rate", 0)) / 1000) if fmt.get("bit_rate") else None,
}
if audio_stream:
metadata.update({
"input_codec": audio_stream.get("codec_name"),
"input_sample_rate": int(audio_stream.get("sample_rate", 0)) or None,
"input_channels": audio_stream.get("channels"),
"input_bit_depth": int(audio_stream.get("bits_per_raw_sample", 0)) or None,
})
job_manager.update_processing_metadata(job_id, "audio_source", metadata)
job_log.info(f"Audio source: {metadata.get('input_codec', '?')} "
f"{metadata.get('input_sample_rate', '?')}Hz "
f"{metadata.get('input_channels', '?')}ch "
f"{metadata.get('input_duration_seconds', '?')}s")
except Exception as e:
job_log.warning(f"Failed to capture audio source metadata (non-fatal): {e}")
logger.warning(f"Job {job_id}: ffprobe metadata capture failed: {e}")
# ==================== CLI Entry Point for Cloud Run Jobs ====================
# This allows the audio worker to be run as a standalone Cloud Run Job.
# Usage: python -m backend.workers.audio_worker --job-id <job_id>
+106
View File
@@ -420,6 +420,12 @@ async def process_lyrics_transcription(job_id: str) -> bool:
job_log.info("Transcription processing complete")
logger.info(f"[job:{job_id}] Transcription complete, uploading results")
# Store processing metadata for transcription + correction provenance
_store_lyrics_processing_metadata(
job_manager, job_id, result, trans_duration,
cache_stats if 'cache_stats' in locals() else None, job_log
)
# Upload lyrics results to GCS
with job_span("upload-lyrics-results", job_id):
@@ -458,6 +464,8 @@ async def process_lyrics_transcription(job_id: str) -> bool:
job_manager.mark_lyrics_complete(job_id)
duration = time.time() - start_time
# Store worker-level timing
job_manager.update_processing_metadata(job_id, "timing.lyrics_worker_seconds", round(duration, 1))
root_span.set_attribute("duration_seconds", duration)
logger.info(f"[job:{job_id}] WORKER_END worker=lyrics status=success duration={duration:.1f}s")
return True
@@ -699,6 +707,104 @@ async def upload_lyrics_results(
logger.info(f"Job {job_id}: All lyrics results uploaded successfully")
def _store_lyrics_processing_metadata(
job_manager: JobManager,
job_id: str,
transcription_result: Dict[str, Any],
transcription_duration: float,
cache_stats: Optional[Dict[str, Any]],
job_log,
) -> None:
"""Store transcription and correction provenance in processing_metadata.
Extracts AudioShake task_id/asset_id, correction stats, reference sources,
and cache hit/miss info from the transcription result and stores them
permanently for future analytics, debugging, and data export.
"""
try:
# Load the corrections.json data from the result to get metadata
# The transcription_result is the dict returned by LyricsProcessor.transcribe_lyrics()
# which contains file paths, not the corrections data directly.
# We need to find and read the corrections JSON from the output directory.
corrections_metadata = {}
transcription_metadata = {}
# Try to find corrections file in the result's output directory
lyrics_dir = transcription_result.get("lyrics_dir") or ""
corrections_file = None
# Check common paths for corrections JSON
if lyrics_dir:
for fname in os.listdir(lyrics_dir) if os.path.isdir(lyrics_dir) else []:
if fname.endswith("(Lyrics Corrections).json") or fname == "corrections.json":
corrections_file = os.path.join(lyrics_dir, fname)
break
if corrections_file and os.path.exists(corrections_file):
with open(corrections_file, 'r', encoding='utf-8') as f:
corrections_data = json.load(f)
metadata = corrections_data.get("metadata", {})
# Extract AudioShake IDs from transcription_metadata passthrough
trans_meta = metadata.get("transcription_metadata", {})
if trans_meta:
transcription_metadata = {
"provider": "audioshake",
"audioshake_task_id": trans_meta.get("task_id"),
"audioshake_asset_id": trans_meta.get("asset_id"),
"language_detected": trans_meta.get("language"),
}
# Extract correction stats
corrections_metadata = {
"handlers_applied": metadata.get("enabled_handlers", []),
"corrections_made": corrections_data.get("corrections_made", 0),
"correction_ratio": metadata.get("correction_ratio"),
"agentic_routing": metadata.get("agentic_routing"),
"total_words": metadata.get("total_words"),
"anchor_sequences_count": metadata.get("anchor_sequences_count"),
"gap_sequences_count": metadata.get("gap_sequences_count"),
}
# Count segments and words from corrected_segments
corrected_segments = corrections_data.get("corrected_segments", [])
transcription_metadata["segment_count"] = len(corrected_segments)
transcription_metadata["word_count"] = sum(
len(seg.get("words", [])) for seg in corrected_segments
)
# Determine which reference sources were found
reference_lyrics = corrections_data.get("reference_lyrics", {})
if reference_lyrics:
corrections_metadata["reference_sources_found"] = list(reference_lyrics.keys())
# Add transcription duration
transcription_metadata["duration_seconds"] = round(transcription_duration, 1)
# Store transcription metadata
if transcription_metadata:
job_manager.update_processing_metadata(job_id, "transcription", transcription_metadata)
# Store correction metadata
if corrections_metadata:
job_manager.update_processing_metadata(job_id, "correction", corrections_metadata)
# Store cache stats
if cache_stats:
job_manager.update_processing_metadata(job_id, "cache", {
"transcription_cache_downloaded": cache_stats.get("downloaded", 0),
"transcription_cache_not_found": cache_stats.get("not_found", 0),
})
job_log.info("Stored processing metadata (transcription + correction provenance)")
except Exception as e:
# Never fail a job because metadata storage failed
job_log.warning(f"Failed to store lyrics processing metadata (non-fatal): {e}")
logger.warning(f"Job {job_id}: Failed to store lyrics processing metadata: {e}")
# ==================== CLI Entry Point for Cloud Run Jobs ====================
# This allows the lyrics worker to be run as a standalone Cloud Run Job.
# Usage: python -m backend.workers.lyrics_worker --job-id <job_id>
+9
View File
@@ -319,6 +319,15 @@ async def process_render_video(job_id: str) -> bool:
job_log.info("Uploaded corrected.txt")
logger.info(f"Job {job_id}: Uploaded corrected.txt")
# Store render timing in processing metadata
render_duration = time.time() - start_time
job_manager.update_processing_metadata(job_id, "rendering", {
"render_duration_seconds": round(render_duration, 1),
"countdown_padding_added": padding_added,
"countdown_padding_seconds": padding_seconds if padding_added else 0,
})
job_manager.update_processing_metadata(job_id, "timing.render_video_worker_seconds", round(render_duration, 1))
# 13. Transition based on prep_only flag
# Note: Instrumental selection was already made during combined review
# (stored in state_data['instrumental_selection'])
+2
View File
@@ -222,6 +222,8 @@ async def generate_screens(job_id: str) -> bool:
)
duration = time.time() - start_time
# Store worker-level timing
job_manager.update_processing_metadata(job_id, "timing.screens_worker_seconds", round(duration, 1))
root_span.set_attribute("duration_seconds", duration)
logger.info(f"[job:{job_id}] WORKER_END worker=screens status=success duration={duration:.1f}s")
+73 -3
View File
@@ -226,6 +226,14 @@ async def generate_video_orchestrated(job_id: str) -> bool:
logger.error(f"[job:{job_id}] Prerequisites not met for video generation")
return False
# Validate job status is appropriate for video worker
from backend.services.job_health_service import validate_worker_can_run
status_error = validate_worker_can_run("video_worker", job)
if status_error:
logger.warning(f"[job:{job_id}] {status_error}")
job_log.warning(status_error)
return False
# Create temporary working directory
temp_dir = tempfile.mkdtemp(prefix=f"karaoke_video_{job_id}_")
original_cwd = os.getcwd()
@@ -363,8 +371,11 @@ async def generate_video_orchestrated(job_id: str) -> bool:
settings=settings,
)
# Mark job as complete (triggers completion email with youtube_url now available)
# Store video processing metadata
duration = time.time() - start_time
_store_video_processing_metadata(job_manager, job_id, result, duration)
# Mark job as complete (triggers completion email with youtube_url now available)
completion_metadata = {
"action": "completed",
"brand_code": result.brand_code,
@@ -634,11 +645,19 @@ async def generate_video_legacy(job_id: str) -> bool:
if not _validate_prerequisites(job):
logger.error(f"[job:{job_id}] Prerequisites not met for video generation")
return False
# Validate job status is appropriate for video worker
from backend.services.job_health_service import validate_worker_can_run
status_error = validate_worker_can_run("video_worker", job)
if status_error:
logger.warning(f"[job:{job_id}] {status_error}")
job_log.warning(status_error)
return False
# Create temporary working directory
temp_dir = tempfile.mkdtemp(prefix=f"karaoke_video_{job_id}_")
original_cwd = os.getcwd()
# Set up rclone config if needed for Dropbox upload
rclone_service = None
if getattr(job, 'organised_dir_rclone_root', None):
@@ -1141,6 +1160,57 @@ def _send_distribution_warning_notification(
logger.warning(f"[job:{job_id}] Failed to send Pushbullet notification: {e}")
def _store_video_processing_metadata(
job_manager: JobManager,
job_id: str,
result,
total_duration: float,
) -> None:
"""Store encoding, distribution, and output metadata in processing_metadata."""
try:
# Encoding metadata
encoding_data = {
"encoding_time_seconds": round(result.encoding_time_seconds, 1) if result.encoding_time_seconds else None,
"output_formats": [],
}
# Track which output formats were generated and their sizes
output_sizes = {}
for attr, fmt_name in [
("final_video", "lossless_4k_mp4"),
("final_video_mkv", "lossless_4k_mkv"),
("final_video_lossy", "lossy_4k_mp4"),
("final_video_720p", "lossy_720p_mp4"),
]:
path = getattr(result, attr, None)
if path and os.path.exists(path):
encoding_data["output_formats"].append(fmt_name)
output_sizes[fmt_name] = os.path.getsize(path)
if output_sizes:
encoding_data["output_sizes_bytes"] = output_sizes
job_manager.update_processing_metadata(job_id, "encoding", encoding_data)
# Distribution metadata
distribution_data = {}
if result.youtube_url:
distribution_data["youtube_video_url"] = result.youtube_url
if result.youtube_upload_queued:
distribution_data["youtube_upload_queued"] = True
if result.dropbox_link:
distribution_data["dropbox_link"] = result.dropbox_link
if result.gdrive_files:
distribution_data["gdrive_file_count"] = len(result.gdrive_files)
if result.brand_code:
distribution_data["brand_code"] = result.brand_code
if distribution_data:
job_manager.update_processing_metadata(job_id, "distribution", distribution_data)
# Worker timing
job_manager.update_processing_metadata(job_id, "timing.video_worker_seconds", round(total_duration, 1))
except Exception as e:
logger.warning(f"Job {job_id}: Failed to store video processing metadata (non-fatal): {e}")
def _validate_prerequisites(job) -> bool:
"""Validate that all prerequisites are met for video generation."""
# Validate job status is appropriate for video worker
+1 -1
View File
@@ -182,7 +182,7 @@ karaoke-gen shares a GCP project (`nomadkaraoke`) with karaoke-decide, but uses
| Collection | Purpose | Key Fields |
|------------|---------|------------|
| `gen_users` | karaoke-gen user accounts | email, credits, role, is_active |
| `jobs` | Karaoke generation jobs | job_id, user_email, status, state_data |
| `jobs` | Karaoke generation jobs | job_id, user_email, status, state_data, processing_metadata |
| `jobs/{job_id}/logs` | Worker log entries (subcollection) | timestamp, level, worker, message, ttl_expiry |
| `sessions` | Magic link auth sessions | user_email, token, expires_at |
| `magic_links` | Passwordless auth tokens | email, token, expires_at, used |
+25
View File
@@ -773,6 +773,9 @@ Firestore returns timezone-aware datetimes. Compare with `datetime.now(timezone.
### GCS Blob Paths vs URIs
Methods that accept paths typically want `bucket/path`, not `gs://bucket/path`.
### GCS Lifecycle Rules Can Delete Job Data
The GCS bucket has a lifecycle rule deleting objects under `uploads/` and `temp/` prefixes after 7 days. Style configuration (`style_params.json`) was stored under `uploads/{job_id}/style/` and silently disappeared for jobs not completed within a week. Fix: store job-scoped data under `jobs/` prefix (not subject to lifecycle rules), keeping `uploads/` only for genuinely temporary staging files.
### Library Caches Need GCS Sync
External library caches (like LyricsTranscriber) need explicit sync to GCS for persistence across Cloud Run instances.
@@ -912,3 +915,25 @@ The three-layer defense above protects against the **GCE encoding worker** being
**Key insight:** The job's Firestore document (timeline + log subcollection) should be the single source of truth for "what happened to this job." Cloud Logging has retention limits and requires knowing which service to search. Timeline metadata makes the job self-documenting — any agent or human can read the timeline and understand the full lifecycle without cross-referencing logs.
### Store Processing Metadata When You Have It (Mar 2026)
**Problem:** During a data export for AudioShake lyrics correction feedback, we discovered that AudioShake `task_id` and `asset_id` were only held in memory during processing and never persisted. Recovery required paginating the AudioShake API and cross-referencing Cloud Logging — a multi-hour effort for data that was trivially available during processing.
**Solution:** Added `processing_metadata` as a top-level dict on the Job model, separate from `state_data` (mutable workflow state). Each worker writes its own section (transcription, separation, rendering, etc.) via `job_manager.update_processing_metadata(job_id, section, data)`, which uses Firestore dot-notation to atomically update one section without overwriting others. All metadata writes are wrapped in try/except — failures are logged but never fail jobs.
**Key insight:** "Store it when you have it." The cost of persisting a few extra fields is negligible; the cost of not having them later (log spelunking, API pagination, one-off recovery scripts) is enormous. When data flows through a worker during processing, capture the provenance metadata before it's lost. See `docs/archive/2026-03-10-store-job-processing-metadata.md` for the full design.
### Test the Contract, Not Just the Function (Mar 2026)
**Problem:** The processing metadata feature shipped with a silent bug: `_store_lyrics_processing_metadata()` expected `result["lyrics_dir"]` but `transcribe_lyrics()` never included `lyrics_dir` in its return dict. AudioShake IDs and correction stats were silently lost in production. The test suite had 24 passing tests and didn't catch it.
**Root cause (testing):** The test for `_store_lyrics_processing_metadata` hand-crafted its input: `transcription_result={"lyrics_dir": str(lyrics_dir)}`. This tested the function in isolation — proving it works *if given correct input* — but never verified the actual caller provides that input. The mock was "too helpful."
**Pattern — Contract tests:** When function A calls function B with data, test both:
1. **Unit test B** with controlled input (existing approach — still valuable)
2. **Contract test** verifying A's output contains the keys B expects
For this bug, the missing test was: "does `transcribe_lyrics()` return `lyrics_dir`?" — a one-line assertion that would have caught the bug before merge.
**Broader principle:** Non-fatal code paths (try/except that swallows errors) are especially dangerous. The metadata storage was designed to never fail jobs, which is correct — but it also meant the bug was completely silent. When testing non-fatal paths, assert on the *positive outcome* (metadata was stored), not just the absence of exceptions. A test that only checks "didn't crash" provides false confidence when the code is designed to never crash.
+2
View File
@@ -93,6 +93,8 @@
- **Custom Instrumental Upload Fix** (2026-02-26): Fixed critical bug where uploaded custom instrumentals were ignored during encoding — GCE encoding worker and orchestrator had no `"custom"` case, falling back to clean instrumental instead. Upload endpoint now converts all formats to FLAC for pipeline consistency. Three fixes: (1) GCE encoding worker `find_file` now searches for `custom_instrumental*.flac` when selection is `"custom"`, (2) orchestrator config constructs correct `(Instrumental Custom).flac` path, (3) upload endpoint converts mp3/m4a/wav/etc. to FLAC before storing. Added 10 new regression tests for GCE resolution and orchestrator paths. See [API.md](API.md#upload-custom-instrumental).
- **Store Processing Metadata Permanently** (2026-03-10): Added `processing_metadata` field to the Job model — a top-level dict where each worker writes immutable provenance data during processing. Stores AudioShake task_id/asset_id (the original ask — these were previously lost after processing), worker timing, separation model names, ffprobe audio properties, correction stats, cache hit/miss data, video encoding details, and auth context at job creation. All metadata writes are non-fatal (wrapped in try/except). Includes `update_processing_metadata` helper on JobManager using Firestore dot-notation for atomic section updates. 23 tests covering model, helpers, all worker functions, and a SUMMARY_FIELD_PATHS regression guard. See [archive/2026-03-10-store-job-processing-metadata.md](archive/2026-03-10-store-job-processing-metadata.md) and [LESSONS-LEARNED.md](LESSONS-LEARNED.md#store-processing-metadata-when-you-have-it-mar-2026).
- **Custom Instrumental Upload** (2026-02-25): Added `POST /api/jobs/{job_id}/upload-instrumental` endpoint — was missing from backend, causing 404 in production when users tried to upload custom instrumental files during review. Validates uploaded audio duration matches original (±0.5s tolerance) using ffprobe on GCS signed URLs. Fixed frontend bug where "uploaded" selection type was sent to API instead of "custom" (the only value the backend accepts). Added 22 tests covering upload validation, duration checks, and frontend/backend contract. See [API.md](API.md#upload-custom-instrumental).
- **Unicode Filename Fix** (2026-02-04): Fixed FFmpeg failures (exit code 183) when processing songs with non-ASCII characters in titles. Job `1eab1172` with Russian title "я куплю тебе дом" failed because Python's `str.isalnum()` returns True for ALL Unicode alphanumeric characters (Cyrillic, Arabic, Chinese, emoji, etc.), not just ASCII. These Unicode characters in temp subtitle file paths (`temp_subtitles_zivert___я_куплю_тебе_дом_1770150285852.ass`) caused FFmpeg to fail. **Fix**: Changed filename sanitization from `c.isalnum()` to `c.isascii() and c.isalnum()` in three locations: `video.py:222` (generate_video), `video.py:282` (generate_preview_video), and `remote_cli.py:1970` (output folders). Added comprehensive test suite covering Cyrillic, Chinese, Arabic, emoji, and accented characters. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#unicode-in-file-paths-feb-2026).
+30
View File
@@ -182,6 +182,36 @@ mock_service.update_job.return_value = None # Match real API
**Before writing a mock**, check the actual method's return type. Void methods should mock `return_value = None`. Methods that raise on error (rather than returning False) should have mocks that raise exceptions for error cases. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#mocks-must-match-real-return-values-feb-2026) for a production bug caused by this.
**Critical: Test the Contract Between Caller and Callee**
When function A calls function B, it's not enough to test B with hand-crafted ideal inputs. You must also verify A actually produces those inputs. This is a "contract test."
```python
# ❌ BAD: Tests _store_metadata in isolation with hand-crafted input
# If transcribe_lyrics() never includes "lyrics_dir", this test still passes
# but production silently loses all metadata
def test_stores_audioshake_ids(tmp_path):
_store_lyrics_processing_metadata(
transcription_result={"lyrics_dir": str(tmp_path)}, # Too helpful!
...
)
assert call_args["audioshake_task_id"] == "task-abc" # ✅ passes, but useless
# ✅ GOOD: Also test that the caller produces the expected input
def test_transcribe_lyrics_returns_lyrics_dir(tmp_path):
result = processor.transcribe_lyrics(audio, artist, title, tmp_path)
assert "lyrics_dir" in result # Catches the actual bug
```
**When to write contract tests:**
- Function A builds a dict/object and passes it to function B
- Function B reads specific keys/fields from that dict/object
- The dict/object shape is implicit (no schema, no TypedDict, no dataclass)
**Especially dangerous:** Non-fatal code paths (try/except that swallows errors). If the function is designed to never crash, a test that only checks "didn't raise" provides zero signal. Assert on the *positive outcome* (data was stored, value was returned) not just the absence of exceptions.
See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#test-the-contract-not-just-the-function-mar-2026) for the production bug this pattern caused.
### Integration Tests (`tests/integration/`)
**Purpose:** Test CLI workflows and component interactions.
@@ -0,0 +1,294 @@
# Plan: Store Job Processing Metadata Permanently
**Date**: 2026-03-10
**Branch**: `feat/sess-20260309-2358-store-audioshake-ids`
**Status**: Implemented (all 6 phases)
## Problem
During a data export for AudioShake (lyrics correction feedback), we discovered that AudioShake task_id and asset_id were only stored ephemerally during processing and never persisted. We had to do a complex one-off recovery from Cloud Logging + AudioShake API pagination to reconstruct the mapping.
This is symptomatic of a broader issue: many pieces of valuable metadata generated during job processing are only logged or held in memory, then discarded. When a future data export, debugging, or analytics need arises, we're left scrambling to recover from logs (which have limited retention).
## Goals
1. **Immediate**: Persist AudioShake task_id and asset_id permanently with each job
2. **Broader**: Identify and store other high-value processing metadata that would be painful to reconstruct later
3. **Principle**: "Store it when you have it" - the cost of storing a few extra fields is negligible compared to the cost of not having them later
## Design: `processing_metadata` Field
Add a new top-level dict field `processing_metadata` to the Job model, separate from `state_data` (which is mutable workflow state). `processing_metadata` is **write-once** data captured during processing that describes _how_ the job was processed.
### Why Not `state_data`?
- `state_data` is for mutable workflow state (current stems, build IDs, etc.)
- `processing_metadata` is for immutable audit/provenance data
- Keeps concerns separate: "what stage is the job in" vs "how was it processed"
- Easier to project in queries (one field to include vs picking through state_data keys)
### Schema
```python
# In Job model
processing_metadata: Dict[str, Any] = Field(default_factory=dict)
"""
Immutable processing provenance data. Written once by each worker during processing.
Never modified after initial write. Used for analytics, debugging, and data export.
Structure:
{
"transcription": {
"provider": "audioshake",
"audioshake_task_id": "cmmjpbo7f...",
"audioshake_asset_id": "cmmjpbma4...",
"language_detected": "en",
"duration_seconds": 125.5,
"word_count": 358,
"segment_count": 42,
},
"correction": {
"handlers_applied": ["anchor_sequence", "gap_word_count", ...],
"corrections_made": 12,
"correction_ratio": 0.034,
"reference_sources_found": ["genius", "spotify", "lrclib"],
"agentic_routing": "rule-based",
"duration_seconds": 33.2,
},
"separation": {
"provider": "modal",
"clean_model": "model_bs_roformer_ep_317_sdr_12.9755.ckpt",
"backing_models": ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"],
"stems_generated": ["clean", "with_backing", "vocals", "backing_vocals"],
"duration_seconds": 420.5,
},
"audio_source": {
"input_format": "flac",
"input_sample_rate": 44100,
"input_channels": 2,
"input_duration_seconds": 210.4,
"input_file_size_bytes": 26541900,
},
"rendering": {
"render_duration_seconds": 18.7,
"encoding_duration_seconds": 180.5,
"output_formats": ["lossless_4k_mkv", "lossless_4k_mp4", "lossy_4k_mp4", "lossy_720p_mp4"],
"output_sizes_bytes": {
"lossless_4k_mkv": 45168200,
"lossy_720p_mp4": 34571800,
},
},
"review": {
"review_duration_seconds": 450.2,
"corrections_made_by_human": 5,
"total_words_reviewed": 358,
"instrumental_selected": "clean",
},
"distribution": {
"youtube_video_id": "dQw4w9WgXcQ",
"youtube_upload_duration_seconds": 240.5,
"dropbox_upload_duration_seconds": 120.5,
"gdrive_upload_duration_seconds": 95.3,
},
"cache": {
"transcription_cache_hit": true,
"lyrics_cache_hits": {"genius": true, "spotify": true, "lrclib": false},
},
"timing": {
"total_processing_seconds": 890.2,
"worker_durations": {
"audio": 420.5,
"lyrics": 125.3,
"screens": 45.2,
"render_video": 18.7,
"video": 180.2,
},
},
}
```
### Field Projection
Per the known gotcha (MEMORY.md), when adding new fields the dashboard needs, must add to BOTH:
1. `SUMMARY_FIELD_PATHS` in `backend/services/firestore_service.py`
2. `_SUMMARY_STATE_DATA_KEYS` in `backend/api/routes/jobs.py`
For `processing_metadata`, we'll add it to `SUMMARY_FIELD_PATHS` so it's available in job list queries. Since it's a top-level field (not under `state_data`), it doesn't need `_SUMMARY_STATE_DATA_KEYS`.
## Implementation Plan
### Phase 1: AudioShake IDs (Priority - the original ask)
**Files to modify:**
1. **`backend/models/job.py`** - Add `processing_metadata` field to Job model
2. **`karaoke_gen/lyrics_transcriber/core/controller.py`** - Pass transcription metadata (including task_id) through to CorrectionResult.metadata
3. **`backend/workers/lyrics_worker.py`** - Extract AudioShake IDs + transcription metadata from corrections.json and store in `processing_metadata.transcription`
4. **`backend/services/firestore_service.py`** - Add `processing_metadata` to `SUMMARY_FIELD_PATHS`
5. **`backend/api/routes/jobs.py`** - Ensure `processing_metadata` is included in job responses
**Detail:**
In `controller.py`, the `_convert_result_format` method on AudioShakeTranscriber already stores `task_id` in `TranscriptionData.metadata`. The issue is that `LyricsCorrector.run()` builds a new `CorrectionResult.metadata` dict that doesn't include this data. Fix:
- In `corrector.py`, pass through the primary transcription's metadata into the CorrectionResult metadata dict
- In `lyrics_worker.py`, after loading corrections.json, extract `metadata.transcription_metadata` and write to `processing_metadata`
Alternatively (simpler): in `lyrics_worker.py`, we already have access to the transcription result object. We can extract the AudioShake IDs directly from it before they're lost, and store them in `processing_metadata`.
**Chosen approach**: Store in `lyrics_worker.py` right after transcription completes, since we have direct access to the result there. Also flow the metadata through corrections.json for data integrity.
### Phase 2: Worker Timing & Processing Stats
**Files to modify:**
6. **`backend/workers/lyrics_worker.py`** - Add timing data + correction stats to `processing_metadata`
7. **`backend/workers/audio_worker.py`** - Add separation timing + model info to `processing_metadata`
8. **`backend/workers/screens_worker.py`** - Add screen generation timing
9. **`backend/workers/render_video_worker.py`** - Add render timing
10. **`backend/workers/video_worker.py`** / **`video_worker_orchestrator.py`** - Add encoding timing + output file sizes
**For each worker, the pattern is:**
```python
# At the end of successful processing:
job_manager.update_processing_metadata(job_id, 'separation', {
'provider': 'modal',
'clean_model': model_names.get('clean'),
'duration_seconds': round(sep_duration, 1),
...
})
```
### Phase 3: Audio Source & Cache Metadata
**Files to modify:**
11. **`backend/workers/lyrics_worker.py`** - Cache hit/miss stats
12. **`backend/api/routes/jobs.py`** or audio download handler - Input audio metadata (format, sample rate, duration, file size)
### Phase 4: Review & Distribution Metadata
**Files to modify:**
13. **`backend/api/routes/review.py`** - Review completion metadata (duration, corrections count)
14. **`backend/workers/video_worker.py`** - YouTube upload metadata (video ID is probably already stored, but upload timing is not)
### JobManager Helper
Add a helper method to JobManager for appending to `processing_metadata` without overwriting:
```python
def update_processing_metadata(self, job_id: str, section: str, data: dict):
"""Merge data into processing_metadata[section]. Write-once per section."""
from google.cloud.firestore_v1 import transforms
self.db.collection("jobs").document(job_id).update({
f"processing_metadata.{section}": data,
})
```
## Testing Strategy
### Unit Tests
- **`backend/tests/test_job_model.py`**: Verify `processing_metadata` field exists and defaults to empty dict
- **`backend/tests/test_lyrics_worker.py`**: Mock transcription result with AudioShake metadata, verify it's stored in `processing_metadata.transcription`
- **`backend/tests/test_audio_worker.py`**: Verify separation metadata stored
- **`backend/tests/test_job_manager.py`**: Test `update_processing_metadata` helper
### Integration Tests
- **`backend/tests/integration/`**: Firestore emulator test that processes a job through lyrics worker and verifies `processing_metadata` is written correctly
### Regression Test
- Add a test asserting `processing_metadata` is in `SUMMARY_FIELD_PATHS` (per the known gotcha)
## Migration
No migration needed for existing jobs - `processing_metadata` defaults to `{}`. New jobs will populate it as they process. The extraction script (`extract_audioshake_corrections.py`) already handles the one-off backfill for historical AudioShake IDs.
### Phase 5: Input Audio Metadata (ffprobe at ingest)
Currently we have ffprobe and pydub available in workers, but never store audio properties permanently. When a user uploads or we download audio, run ffprobe once and store the results.
**Files to modify:**
15. **`backend/workers/audio_worker.py`** (or wherever audio is first downloaded to disk) - Run ffprobe on the input audio file and store:
```json
"audio_source": {
"input_format": "flac",
"input_codec": "flac",
"input_sample_rate": 44100,
"input_bit_depth": 16,
"input_channels": 2,
"input_duration_seconds": 210.4,
"input_file_size_bytes": 26541900,
"input_bitrate_kbps": 1411
}
```
This is valuable for:
- Understanding what quality of source material produces the best results
- Debugging encoding/quality issues
- Analytics on user upload patterns
- Detecting re-encoded or low-quality uploads
### Phase 6: User & Abuse-Related Metadata
**Current state**: `request_metadata` already captures IP, User-Agent, client_id, and custom headers at job creation time. This is good for basic abuse investigation. However, some gaps:
**6a. Auth context at job creation**
Store which auth method was used and user tier, so we can correlate job creation patterns with account types during abuse investigation.
16. **`backend/api/routes/file_upload.py`** - Add to `extract_request_metadata()`:
```python
# Add auth context (already available from auth_result)
request_metadata['auth_method'] = auth_result.auth_method # "session", "api_key", "admin_token"
request_metadata['user_type'] = auth_result.user_type.value # "admin", "unlimited", "limited", etc.
request_metadata['credits_at_creation'] = auth_result.remaining_uses # snapshot of credits when job created
```
**6b. Audio search metadata (for audio search flow jobs)**
When a job is created from audio search, we know the search query, number of results, and which result was selected. Store these so we can understand search patterns and detect gaming.
17. **`backend/api/routes/audio_search.py`** - When creating a job from search, store:
```json
"request_metadata": {
...existing fields...,
"search_query": {"artist": "...", "title": "..."},
"search_results_count": 8,
"selected_result_rank": 1,
"selected_source": "RED"
}
```
**Not adding (already handled):**
- IP address: Already in `request_metadata.client_ip`
- User-Agent: Already in `request_metadata.user_agent`
- Email: Already in `job.user_email`
- Tenant: Already in `job.tenant_id`
- IP blocklist: Already exists in `blocklists/config`
- Session IP/UA: Already stored in session documents
- Magic link IP/UA: Already stored in magic link documents
## Scope & Boundaries
- **In scope**: Storing metadata that already exists in memory during processing
- **Out of scope**: Computing new metrics, changing external API calls, frontend changes
- **Out of scope**: Backfilling historical jobs (the one-off script handles AudioShake IDs)
- **Principle**: Each worker writes its own section. No worker reads another worker's metadata.
## Estimated Changes
| Phase | Files | Complexity | Notes |
|-------|-------|-----------|-------|
| 1 | 5 | Low | AudioShake IDs - the critical fix |
| 2 | 5 | Low | Timing data - already computed, just needs storing |
| 3 | 2 | Low | Source/cache metadata |
| 4 | 2 | Low | Review/distribution metadata |
| 5 | 1-2 | Low | ffprobe on input audio, store properties |
| 6 | 2 | Low | Auth context + search metadata at job creation |
| Tests | 4-5 | Medium | Unit + integration tests |
Total: ~18 files, mostly small additions (5-15 lines per file).
@@ -0,0 +1,153 @@
# Plan: Fix style_params.json Lifecycle Deletion, CDG Font Robustness, and Video Worker State Guard
**Created:** 2026-03-15
**Branch:** feat/sess-20260315-1520-investigate-state-transition
**Status:** Implemented
**Triggered by:** Job 27054772 (CDG generation failure) and Job 2d4a7bab (style_params.json 404 after 7 days)
## Overview
Three related issues discovered during investigation of production job failures:
1. **GCS lifecycle rule deletes `style_params.json` after 7 days** — The bucket has a lifecycle rule deleting objects with `uploads/` prefix after 7 days. `style_params.json` is stored under `uploads/{job_id}/style/` and gets deleted, breaking any job not completed within a week.
2. **CDG generation crashes with unhelpful error when font download fails** — When the font file can't be resolved, `_validate_and_setup_font()` sets `font_path = None`. Python's `toml.dump()` silently omits `None` values, causing `KeyError: 'font'` downstream in `KaraokeComposer`. The error message is opaque: "CDG generation was enabled but failed."
3. **Video worker doesn't guard against invalid state transitions** — Unlike other workers (audio, lyrics, render), the video worker doesn't call `validate_worker_can_run()` before transitioning to `GENERATING_VIDEO`. When Cloud Tasks retries a failed job, the worker attempts `failed -> GENERATING_VIDEO` which throws `InvalidStateTransitionError`, producing cascading noise in logs and error messages.
## Requirements
- [ ] Jobs must work regardless of how long they sit before completion (no 7-day style deadline)
- [ ] CDG generation must fail gracefully with a clear error, or fall back to a bundled font
- [ ] Video worker retries against failed/cancelled jobs must exit cleanly, not throw state errors
- [ ] All existing tests must continue to pass
- [ ] Backward compatibility: existing jobs with `uploads/` style paths must still work
## Technical Approach
### Fix 1: Move `style_params.json` from `uploads/` to `jobs/` prefix
The `jobs/` prefix is NOT subject to the lifecycle rule and is the natural home for job-scoped data. All other job outputs (stems, lyrics, screens, videos) already live under `jobs/{job_id}/`.
**Approach**: Change the path generation in `theme_service.prepare_job_style()` and all related upload paths in `file_upload.py` and `audio_search.py` from `uploads/{job_id}/style/` to `jobs/{job_id}/style/`.
**Backward compatibility**: Existing jobs in Firestore already store their `style_params_gcs_path` as a string field. Old jobs will still have `uploads/...` paths and will work until the lifecycle rule deletes them. No migration needed — workers read the path from the job document, not from a hardcoded pattern. New jobs will get `jobs/...` paths that persist forever.
**Note**: The `uploads/` prefix will still be used for temporary file upload staging (audio files, etc.) which is appropriate for the lifecycle rule.
### Fix 2: CDG font fallback to bundled default
The bundled fonts directory at `karaoke_gen/lyrics_transcriber/output/fonts/` already contains `AvenirNext-Bold.ttf` (the exact font used by the nomad theme). The CDG generator already tries this directory as a fallback, but the check at `_validate_and_setup_font()` looks for the full relative path (e.g., `themes/nomad/assets/AvenirNext-Bold.ttf`) rather than just the filename.
**Approach**: When the font path can't be resolved, fall back to the bundled font by filename (not full path). If even that fails, fall back to a known bundled font (`arial.ttf`) rather than setting `None`.
Additionally, add a safety net: if `font_path` is `None` when building the TOML data, raise a clear error instead of letting `toml.dump()` silently omit it.
### Fix 3: Video worker state guard
Follow the established pattern from `render_video_worker.py`, `audio_worker.py`, and `lyrics_worker.py`: call `validate_worker_can_run("video_worker", job)` before attempting the state transition. Make it a **hard failure** (return False) for terminal states (`failed`, `cancelled`, `complete`) since there's no point proceeding — unlike the soft warning in other workers.
Also update `_check_worker_idempotency()` to check for terminal job states, providing an additional safety layer at the HTTP endpoint level.
## Implementation Steps
### Step 1: Move style_params.json to `jobs/` prefix
1. [ ] **`backend/services/theme_service.py:337`** — Change `f"uploads/{job_id}/style/style_params.json"` to `f"jobs/{job_id}/style/style_params.json"`
2. [ ] **`backend/api/routes/file_upload.py`** — Update all `uploads/{job_id}/style/` references:
- Line 725: Custom style_params upload path
- Line 744: Style background image upload path
- Line 755: Custom font upload path
- Line 1079, 1083: `_get_gcs_path_for_file()` helper
- Line 1376, 1379: Signed URL upload finding logic
- Line 1873: Second path generation function
- Line 2205, 2458: Finalise-only endpoint style finding
- Line 2499: Style asset completion endpoint
3. [ ] **`backend/api/routes/audio_search.py:769,773`** — Update signed URL generation paths
4. [ ] **Update tests** to expect new `jobs/` prefix:
- `backend/tests/test_theme_service.py:339,358`
- `backend/tests/test_file_upload.py:701,708,715`
- `backend/tests/test_style_upload.py:183-184`
- `backend/tests/test_routes_review.py:331-337`
- `backend/tests/emulator/test_style_loading_direct.py:153-161,258`
- `tests/unit/test_remote_cli.py:699,2562,2644`
- `backend/tests/test_style_upload_endpoints.py:254,290`
Note: `backend/tests/test_change_visibility.py` already uses `jobs/` prefix — no changes needed there.
### Step 2: CDG font fallback robustness
5. [ ] **`karaoke_gen/lyrics_transcriber/output/cdg.py` — `_validate_and_setup_font()`** (lines 173-187):
- When font not found at full path, try just the filename in the bundled fonts directory
- If still not found, fall back to `arial.ttf` from bundled fonts (always present)
- Only set `None` if the bundled fonts directory itself doesn't exist (extreme edge case)
- Log warning with the fallback path chosen
6. [ ] **`karaoke_gen/lyrics_transcriber/output/cdg.py` — `_create_toml_data()`** (line 400):
- Add explicit check: if `cdg_styles["font_path"]` is None, raise `RuntimeError("CDG font_path is None — cannot generate CDG without a font")`
- This prevents the silent `toml.dump()` omission that causes a confusing downstream error
7. [ ] **Add test** for CDG font fallback behavior:
- Test that an unresolvable font path falls back to bundled font
- Test that `_create_toml_data` raises if font is None
### Step 3: Video worker state guard
8. [ ] **`backend/workers/video_worker.py` — `generate_video_orchestrated()`** (around line 224):
- Add `validate_worker_can_run("video_worker", job)` check after `_validate_prerequisites()`
- For terminal states (`failed`, `cancelled`, `complete`), return False (hard failure)
- Log the rejection clearly
9. [ ] **`backend/workers/video_worker.py` — `generate_video_legacy()`** (around line 637):
- Same guard as above
10. [ ] **`backend/api/routes/internal.py` — `_check_worker_idempotency()`** (around line 79):
- After checking `state_data` progress, also check if job is in a terminal state (`failed`, `cancelled`)
- Return "skipped" response for terminal states to prevent Cloud Tasks from triggering workers on dead jobs
11. [ ] **Add test** for video worker state guard:
- Test that video worker returns False when job is in `failed` state
- Test that idempotency check rejects terminal-state jobs
## Files to Create/Modify
| File | Action | Description |
|------|--------|-------------|
| `backend/services/theme_service.py` | Modify | Change style path prefix from `uploads/` to `jobs/` |
| `backend/api/routes/file_upload.py` | Modify | Update ~11 `uploads/{job_id}/style/` path references |
| `backend/api/routes/audio_search.py` | Modify | Update 2 signed URL path references |
| `karaoke_gen/lyrics_transcriber/output/cdg.py` | Modify | Improve font fallback logic, add None guard |
| `backend/workers/video_worker.py` | Modify | Add `validate_worker_can_run()` guard to both pipelines |
| `backend/api/routes/internal.py` | Modify | Add terminal state check to idempotency function |
| `backend/tests/test_theme_service.py` | Modify | Update expected paths |
| `backend/tests/test_file_upload.py` | Modify | Update expected paths |
| `backend/tests/test_style_upload.py` | Modify | Update expected paths |
| `backend/tests/test_routes_review.py` | Modify | Update expected paths |
| `backend/tests/test_style_upload_endpoints.py` | Modify | Update expected paths |
| `backend/tests/emulator/test_style_loading_direct.py` | Modify | Update expected paths |
| `tests/unit/test_remote_cli.py` | Modify | Update expected paths |
| `backend/tests/test_cdg_countdown.py` | Modify | Add font fallback tests |
| `backend/tests/test_video_worker_orchestrator.py` | Modify | Add state guard test |
## Testing Strategy
- **Unit tests**: Update all existing path assertions to expect `jobs/` prefix. Add new tests for CDG font fallback and video worker state guard.
- **Integration tests**: The emulator test in `test_style_loading_direct.py` verifies end-to-end style loading with real GCS operations.
- **Run full suite**: `make test 2>&1 | tail -n 500` must pass before committing.
## Open Questions
None — all three fixes are well-understood from investigation.
## Rollback Plan
- **Fix 1**: If `jobs/` prefix causes issues, revert the path change. Existing jobs with `uploads/` paths will still work since workers read the path from the job document.
- **Fix 2**: CDG font fallback is purely additive — remove the fallback logic to restore original behavior.
- **Fix 3**: State guard is purely additive — remove the `validate_worker_can_run` call to restore original behavior.
## Immediate Manual Fix Applied
- Re-uploaded `style_params.json` for job `2d4a7bab` so it can be retried before this fix ships.
+115 -30
View File
@@ -42,6 +42,7 @@ import {
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
@@ -159,6 +160,9 @@ function AdminJobsPageContent() {
const [logFilter, setLogFilter] = useState<string>("all")
const [logSearch, setLogSearch] = useState("")
// Source info modal
const [sourceModalOpen, setSourceModalOpen] = useState(false)
// Delete dialog
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
const [jobToDelete, setJobToDelete] = useState<Job | null>(null)
@@ -618,12 +622,24 @@ function AdminJobsPageContent() {
// Determine job source with detail data
const getJobSource = (job: Job) => {
if (job?.url) return { type: "url" as const, icon: Globe, label: "YouTube", detail: job.url }
// Check audio_source_type first (most reliable)
if (job?.audio_source_type === "youtube_url" || job?.url) {
return { type: "url" as const, icon: Globe, label: "YouTube", detail: job.url || "YouTube URL" }
}
if (job?.audio_source_type === "audio_search") {
const parts = [job.audio_search_artist, job.audio_search_title].filter(Boolean)
const detail = parts.length > 0 ? parts.join(" - ") : (job.target_file || job.filename || "Audio search")
const label = job.source_name ? `Search (${job.source_name})` : "Search"
return { type: "search" as const, icon: Search, label, detail }
}
if (job?.audio_source_type === "file_upload" || job?.filename) {
return { type: "upload" as const, icon: Upload, label: "Upload", detail: job.filename || "Uploaded file" }
}
// Fallback: check fields without audio_source_type (older jobs)
if (job?.audio_search_artist || job?.audio_search_title) {
const parts = [job.audio_search_artist, job.audio_search_title].filter(Boolean)
return { type: "search" as const, icon: Search, label: "Search", detail: parts.join(" - ") }
}
if (job?.filename) return { type: "upload" as const, icon: Upload, label: "Upload", detail: job.filename }
return { type: "unknown" as const, icon: FileText, label: "Unknown", detail: undefined }
}
@@ -1112,34 +1128,18 @@ function AdminJobsPageContent() {
</div>
<div className="space-y-1">
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Source</p>
{jobSource.type === "url" && jobSource.detail ? (
<a
href={jobSource.detail}
target="_blank"
rel="noopener noreferrer"
className="text-sm flex items-center gap-1.5 text-primary hover:underline cursor-pointer truncate"
title={`Open YouTube video: ${jobSource.detail}`}
onClick={(e) => e.stopPropagation()}
>
<SourceIcon className="w-3.5 h-3.5 shrink-0" />
<span className="truncate">{jobSource.detail.replace(/^https?:\/\/(www\.)?/, "").slice(0, 40)}</span>
</a>
) : jobSource.type === "search" && jobSource.detail ? (
<p className="text-sm flex items-center gap-1.5 truncate" title={`Audio search: ${jobSource.detail}`}>
<SourceIcon className="w-3.5 h-3.5 text-muted-foreground shrink-0" />
<span className="truncate">{jobSource.detail}</span>
</p>
) : jobSource.type === "upload" && jobSource.detail ? (
<p className="text-sm flex items-center gap-1.5 truncate" title={`Uploaded file: ${jobSource.detail}`}>
<SourceIcon className="w-3.5 h-3.5 text-muted-foreground shrink-0" />
<span className="truncate">{jobSource.detail}</span>
</p>
) : (
<p className="text-sm flex items-center gap-1.5 text-muted-foreground">
<SourceIcon className="w-3.5 h-3.5" />
Unknown
</p>
)}
<button
className="text-sm flex items-center gap-1.5 text-primary hover:underline cursor-pointer truncate text-left"
title="Click for source details"
onClick={() => setSourceModalOpen(true)}
>
<SourceIcon className="w-3.5 h-3.5 shrink-0" />
<span className="truncate">
{jobSource.type === "url" && jobSource.detail
? jobSource.detail.replace(/^https?:\/\/(www\.)?/, "").slice(0, 40)
: jobSource.detail || "Unknown"}
</span>
</button>
</div>
<div className="space-y-1">
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Created</p>
@@ -1428,6 +1428,91 @@ function AdminJobsPageContent() {
</TabsContent>
</Tabs>
{/* ===== SOURCE INFO MODAL ===== */}
<Dialog open={sourceModalOpen} onOpenChange={setSourceModalOpen}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<SourceIcon className="w-4 h-4" />
Audio Source Details
</DialogTitle>
<DialogDescription>
{jobSource.label} — {selectedJob.artist} - {selectedJob.title}
</DialogDescription>
</DialogHeader>
<div className="space-y-3 text-sm">
{selectedJob.audio_source_type && (
<div className="flex justify-between">
<span className="text-muted-foreground">Source Type</span>
<span className="font-medium">{selectedJob.audio_source_type.replace(/_/g, " ")}</span>
</div>
)}
{selectedJob.source_name && (
<div className="flex justify-between">
<span className="text-muted-foreground">Provider</span>
<span className="font-medium">{selectedJob.source_name}</span>
</div>
)}
{selectedJob.source_id && (
<div className="flex justify-between">
<span className="text-muted-foreground">Source ID</span>
<span className="font-mono text-xs">{selectedJob.source_id}</span>
</div>
)}
{selectedJob.url && (
<div className="flex justify-between gap-2">
<span className="text-muted-foreground shrink-0">URL</span>
<a
href={selectedJob.url}
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline truncate font-mono text-xs"
>
{selectedJob.url}
</a>
</div>
)}
{selectedJob.filename && (
<div className="flex justify-between gap-2">
<span className="text-muted-foreground shrink-0">Filename</span>
<span className="truncate font-mono text-xs">{selectedJob.filename}</span>
</div>
)}
{selectedJob.target_file && selectedJob.target_file !== selectedJob.filename && (
<div className="flex justify-between gap-2">
<span className="text-muted-foreground shrink-0">Target File</span>
<span className="truncate font-mono text-xs">{selectedJob.target_file}</span>
</div>
)}
{(selectedJob.audio_search_artist || selectedJob.audio_search_title) && (
<>
{selectedJob.audio_search_artist && (
<div className="flex justify-between">
<span className="text-muted-foreground">Search Artist</span>
<span>{selectedJob.audio_search_artist}</span>
</div>
)}
{selectedJob.audio_search_title && (
<div className="flex justify-between">
<span className="text-muted-foreground">Search Title</span>
<span>{selectedJob.audio_search_title}</span>
</div>
)}
</>
)}
{selectedJob.download_url && (
<div className="flex justify-between gap-2">
<span className="text-muted-foreground shrink-0">Download URL</span>
<span className="truncate font-mono text-xs">{selectedJob.download_url}</span>
</div>
)}
{!selectedJob.audio_source_type && !selectedJob.url && !selectedJob.filename && (
<p className="text-muted-foreground italic">No source information available for this job.</p>
)}
</div>
</DialogContent>
</Dialog>
{/* ===== LOGS MODAL ===== */}
<Dialog open={logsModalOpen} onOpenChange={setLogsModalOpen}>
<DialogContent className="max-w-5xl max-h-[85vh] flex flex-col">
@@ -472,7 +472,7 @@ test.describe('Admin Job Detail Page', () => {
await expect(page).toHaveURL(/\/admin\/users\/detail\/?\?email=user%40example\.com/);
});
test('YouTube source shows clickable external link', async ({ page }) => {
test('YouTube source opens modal with clickable link', async ({ page }) => {
await setupApiFixtures(page, {
mocks: [
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
@@ -485,8 +485,15 @@ test.describe('Admin Job Detail Page', () => {
await page.goto('/admin/jobs?id=test-job-123');
await page.waitForLoadState('networkidle');
// YouTube source should show as an external link
const sourceLink = page.locator('a[href*="youtube.com"]').first();
// Source should be a clickable button
const sourceButton = page.locator('button').filter({ hasText: /youtube\.com/ });
await expect(sourceButton).toBeVisible();
// Click to open modal, which should contain the clickable YouTube link
await sourceButton.click();
const modal = page.getByLabel('Audio Source Details');
await expect(modal).toBeVisible();
const sourceLink = modal.locator('a[href*="youtube.com"]');
await expect(sourceLink).toBeVisible();
await expect(sourceLink).toHaveAttribute('target', '_blank');
});
@@ -714,4 +721,103 @@ test.describe('Admin Job Detail Page', () => {
// Button should have disabled styling (opacity-50 class applied by shadcn)
await expect(delOutputsButton).toHaveClass(/disabled:opacity-50/);
});
test('shows source details modal for audio search job', async ({ page }) => {
const audioSearchJob = {
...mockJob,
url: undefined,
audio_source_type: 'audio_search',
source_name: 'RED',
source_id: '26048',
target_file: '04 - Living in a Bubble.flac',
filename: '04 - Living in a Bubble.flac',
};
await setupApiFixtures(page, {
mocks: [
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
{ method: 'GET', path: '/api/jobs', response: { body: [] } },
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: audioSearchJob } },
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
],
});
await page.goto('/admin/jobs?id=test-job-123');
await page.waitForLoadState('networkidle');
// Source should show as search with provider name
const sourceButton = page.locator('button').filter({ hasText: /Living in a Bubble/ });
await expect(sourceButton).toBeVisible();
// Click to open source modal
await sourceButton.click();
// Modal should display source details
const modal = page.getByLabel('Audio Source Details');
await expect(modal).toBeVisible();
await expect(modal.getByText('audio search', { exact: true })).toBeVisible();
await expect(modal.getByText('RED', { exact: true })).toBeVisible();
await expect(modal.getByText('26048')).toBeVisible();
await expect(modal.getByText('04 - Living in a Bubble.flac')).toBeVisible();
});
test('shows source details modal for YouTube job', async ({ page }) => {
await setupApiFixtures(page, {
mocks: [
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
{ method: 'GET', path: '/api/jobs', response: { body: [] } },
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: mockJob } },
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
],
});
await page.goto('/admin/jobs?id=test-job-123');
await page.waitForLoadState('networkidle');
// Source should be clickable
const sourceButton = page.locator('button').filter({ hasText: /youtube\.com/ });
await expect(sourceButton).toBeVisible();
// Click to open source modal
await sourceButton.click();
// Modal should show YouTube URL
const modal = page.getByLabel('Audio Source Details');
await expect(modal).toBeVisible();
await expect(modal.getByText('https://youtube.com/watch?v=abc123')).toBeVisible();
});
test('shows source details modal for file upload job', async ({ page }) => {
const uploadJob = {
...mockJob,
url: undefined,
audio_source_type: 'file_upload',
filename: 'my-song.mp3',
};
await setupApiFixtures(page, {
mocks: [
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
{ method: 'GET', path: '/api/jobs', response: { body: [] } },
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: uploadJob } },
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
],
});
await page.goto('/admin/jobs?id=test-job-123');
await page.waitForLoadState('networkidle');
// Source should show filename
const sourceButton = page.locator('button').filter({ hasText: /my-song\.mp3/ });
await expect(sourceButton).toBeVisible();
// Click to open source modal
await sourceButton.click();
// Modal should show upload details
const modal = page.getByLabel('Audio Source Details');
await expect(modal).toBeVisible();
await expect(modal.getByText('file upload')).toBeVisible();
await expect(modal.getByText('my-song.mp3')).toBeVisible();
});
});
+6
View File
@@ -80,6 +80,12 @@ export interface Job {
// Audio search fields
audio_search_artist?: string;
audio_search_title?: string;
// Audio source tracking
audio_source_type?: string;
source_name?: string;
source_id?: string;
target_file?: string;
download_url?: string;
// Theme and branding
theme_id?: string;
brand_prefix?: string;
+4
View File
@@ -474,6 +474,10 @@ class LyricsProcessor:
self.logger.info(f"Saved correction data to {corrections_filepath}")
# Include lyrics_dir so downstream consumers (e.g. _store_lyrics_processing_metadata)
# can find corrections.json and other artifacts
transcriber_outputs["lyrics_dir"] = lyrics_dir
# Capture countdown padding information for syncing with instrumental audio
transcriber_outputs["countdown_padding_added"] = getattr(results, "countdown_padding_added", False)
transcriber_outputs["countdown_padding_seconds"] = getattr(results, "countdown_padding_seconds", 0.0)
@@ -188,6 +188,21 @@ class LyricsCorrector:
span.set_attribute("correction_ratio", correction_ratio)
span.set_attribute("duration_seconds", time.time() - start_time)
# Build metadata dict, including primary transcription metadata for provenance
result_metadata = {
"anchor_sequences_count": len(anchor_sequences),
"gap_sequences_count": len(gap_sequences),
"total_words": total_words,
"correction_ratio": correction_ratio,
"available_handlers": self.all_handlers,
"enabled_handlers": enabled_handlers,
"agentic_routing": "agentic" if agentic_enabled else "rule-based",
}
# Pass through primary transcription metadata (e.g., AudioShake task_id, asset_id)
if primary_transcription.metadata:
result_metadata["transcription_metadata"] = primary_transcription.metadata
result = CorrectionResult(
original_segments=primary_transcription.segments,
corrected_segments=corrected_segments,
@@ -198,15 +213,7 @@ class LyricsCorrector:
anchor_sequences=anchor_sequences,
resized_segments=[],
gap_sequences=gap_sequences,
metadata={
"anchor_sequences_count": len(anchor_sequences),
"gap_sequences_count": len(gap_sequences),
"total_words": total_words,
"correction_ratio": correction_ratio,
"available_handlers": self.all_handlers,
"enabled_handlers": enabled_handlers,
"agentic_routing": "agentic" if agentic_enabled else "rule-based",
},
metadata=result_metadata,
correction_steps=correction_steps,
word_id_map=word_id_map,
segment_id_map=segment_id_map,
+52 -11
View File
@@ -171,20 +171,56 @@ class CDGGenerator:
self._write_toml_file(toml_data, output_file)
def _validate_and_setup_font(self, cdg_styles: dict) -> None:
"""Validate and set up font path in CDG styles."""
"""Validate and set up font path in CDG styles.
Resolution order:
1. Use font_path as-is if it's an absolute path that exists
2. Use font_path as-is if it exists as a relative path
3. Try full relative path inside bundled fonts directory
4. Try just the filename inside bundled fonts directory
5. Fall back to arial.ttf from bundled fonts
"""
if not cdg_styles.get("font_path"):
return
if not os.path.isabs(cdg_styles["font_path"]) and not os.path.exists(cdg_styles["font_path"]):
package_font_path = os.path.join(os.path.dirname(__file__), "fonts", cdg_styles["font_path"])
if os.path.exists(package_font_path):
cdg_styles["font_path"] = package_font_path
self.logger.debug(f"Found font in package fonts directory: {cdg_styles['font_path']}")
else:
self.logger.warning(
f"Font file {cdg_styles['font_path']} not found in package fonts directory {package_font_path}, will use default font"
)
cdg_styles["font_path"] = None
fonts_dir = os.path.join(os.path.dirname(__file__), "fonts")
font_path = cdg_styles["font_path"]
# Already exists (absolute or relative to cwd) — absolutize to avoid CWD issues
if os.path.isfile(font_path):
cdg_styles["font_path"] = os.path.abspath(font_path)
return
# Try full relative path in bundled fonts dir
package_font_path = os.path.join(fonts_dir, font_path)
if os.path.isfile(package_font_path):
cdg_styles["font_path"] = os.path.abspath(package_font_path)
self.logger.debug(f"Found font in package fonts directory: {package_font_path}")
return
# Try just the filename in bundled fonts dir
font_filename = os.path.basename(font_path)
package_font_by_name = os.path.join(fonts_dir, font_filename)
if os.path.isfile(package_font_by_name):
cdg_styles["font_path"] = os.path.abspath(package_font_by_name)
self.logger.warning(
f"Font file {font_path} not found, using bundled font: {font_filename}"
)
return
# Last resort: fall back to arial.ttf
fallback_font = os.path.join(fonts_dir, "arial.ttf")
if os.path.isfile(fallback_font):
cdg_styles["font_path"] = os.path.abspath(fallback_font)
self.logger.warning(
f"Font file {font_path} not found, falling back to bundled arial.ttf"
)
return
self.logger.error(
f"Font file {font_path} not found and no bundled fonts available in {fonts_dir}"
)
cdg_styles["font_path"] = None
def _compose_cdg(self, toml_file: str) -> None:
"""Compose CDG using KaraokeComposer."""
@@ -387,6 +423,11 @@ class CDGGenerator:
cdg_styles: dict,
) -> dict:
"""Create TOML data structure."""
if not cdg_styles.get("font_path"):
raise RuntimeError(
"CDG font_path is None — cannot generate CDG without a font. "
"Check that the font file exists and was downloaded correctly."
)
safe_output_name = self._get_safe_filename(artist, title, "Karaoke")
return {
"title": title,
@@ -293,6 +293,9 @@ class AudioShakeTranscriber(BaseTranscriber):
asset_id = self.api.upload_file(upload_filepath)
self.logger.debug(f"File uploaded successfully. Asset ID: {asset_id}")
# Store asset_id for later retrieval in metadata
self._last_asset_id = asset_id
task_id = self.api.create_task(asset_id)
self.logger.debug(f"Task created successfully. Task ID: {task_id}")
@@ -378,6 +381,7 @@ class AudioShakeTranscriber(BaseTranscriber):
metadata={
"language": transcription_data.get("metadata", {}).get("language"),
"task_id": task_data["id"],
"asset_id": task_data.get("assetId") or getattr(self, '_last_asset_id', None),
"duration": task_data.get("duration"),
},
)
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.141.2"
version = "0.142.3"
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"
+3 -3
View File
@@ -696,7 +696,7 @@ class TestRemoteKaraokeClient:
},
{
"file_type": "style_params",
"gcs_path": "uploads/new-job-456/style/style_params.json",
"gcs_path": "jobs/new-job-456/style/style_params.json",
"upload_url": "https://storage.googleapis.com/signed-url-2",
"content_type": "application/json"
}
@@ -2559,7 +2559,7 @@ class TestSearchAudioWithStyleFiles:
"style_upload_urls": [
{
"file_type": "style_params",
"gcs_path": "uploads/test-job-123/style/style_params.json",
"gcs_path": "jobs/test-job-123/style/style_params.json",
"upload_url": "https://storage.googleapis.com/signed-url-1"
}
]
@@ -2641,7 +2641,7 @@ class TestSearchAudioWithStyleFiles:
"style_upload_urls": [
{
"file_type": "style_params",
"gcs_path": "uploads/test-job-123/style/style_params.json",
"gcs_path": "jobs/test-job-123/style/style_params.json",
"upload_url": "https://storage.googleapis.com/signed-url-1"
}
]