mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-28 01:49:00 +09:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c94c553069 | ||
|
|
d757b0c860 | ||
|
|
c632e68b5b |
No files matched your search
@@ -1,8 +1,7 @@
|
||||
name: Backend Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main, replace-modal-with-google-cloud ]
|
||||
push: # Run on all branch pushes
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
|
||||
@@ -143,8 +142,9 @@ jobs:
|
||||
name: Deploy via Cloud Build
|
||||
runs-on: ubuntu-latest
|
||||
needs: [unit-tests, emulator-tests, lint]
|
||||
# Only deploy on push to the branch (not on PRs)
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/replace-modal-with-google-cloud'
|
||||
# Deploy on any push where tests pass (pre-alpha: rapid iteration mode)
|
||||
# TODO: Change back to main-only when ready for production: github.ref == 'refs/heads/main'
|
||||
if: github.event_name == 'push'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -772,12 +772,16 @@ async def retry_job(
|
||||
})
|
||||
|
||||
# Reset to INSTRUMENTAL_SELECTED and trigger video worker
|
||||
job_manager.transition_to_state(
|
||||
if not job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.INSTRUMENTAL_SELECTED,
|
||||
progress=65,
|
||||
message=f"Retrying video generation from failed state"
|
||||
)
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to transition job status for retry"
|
||||
)
|
||||
|
||||
# Trigger video generation worker
|
||||
background_tasks.add_task(worker_service.trigger_video_worker, job_id)
|
||||
@@ -802,12 +806,16 @@ async def retry_job(
|
||||
})
|
||||
|
||||
# Reset to REVIEW_COMPLETE and trigger render worker
|
||||
job_manager.transition_to_state(
|
||||
if not job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.REVIEW_COMPLETE,
|
||||
progress=70,
|
||||
message=f"Retrying video render from failed state"
|
||||
)
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to transition job status for retry"
|
||||
)
|
||||
|
||||
# Trigger render video worker
|
||||
background_tasks.add_task(worker_service.trigger_render_video_worker, job_id)
|
||||
@@ -832,12 +840,16 @@ async def retry_job(
|
||||
})
|
||||
|
||||
# Reset to a state before screens and trigger screens worker
|
||||
job_manager.transition_to_state(
|
||||
if not job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.LYRICS_COMPLETE,
|
||||
progress=45,
|
||||
message=f"Retrying from screens generation"
|
||||
)
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to transition job status for retry"
|
||||
)
|
||||
|
||||
# Trigger screens worker
|
||||
background_tasks.add_task(worker_service.trigger_screens_worker, job_id)
|
||||
|
||||
@@ -120,9 +120,14 @@ STATE_TRANSITIONS = {
|
||||
JobStatus.UPLOADING: [JobStatus.NOTIFYING, JobStatus.COMPLETE, JobStatus.FAILED],
|
||||
JobStatus.NOTIFYING: [JobStatus.COMPLETE, JobStatus.FAILED],
|
||||
|
||||
# Terminal states have no transitions
|
||||
# Terminal states - COMPLETE and CANCELLED have no transitions
|
||||
# FAILED allows retry transitions to resume from checkpoints
|
||||
JobStatus.COMPLETE: [],
|
||||
JobStatus.FAILED: [],
|
||||
JobStatus.FAILED: [
|
||||
JobStatus.INSTRUMENTAL_SELECTED, # Retry from video generation
|
||||
JobStatus.REVIEW_COMPLETE, # Retry from render stage
|
||||
JobStatus.LYRICS_COMPLETE, # Retry from screens generation
|
||||
],
|
||||
JobStatus.CANCELLED: [],
|
||||
|
||||
# Legacy states (for backward compatibility)
|
||||
|
||||
@@ -62,6 +62,16 @@ class TestJobStatusTransitions:
|
||||
if status not in excluded:
|
||||
valid_transitions = STATE_TRANSITIONS.get(status, [])
|
||||
assert JobStatus.FAILED in valid_transitions, f"{status} should be able to fail"
|
||||
|
||||
def test_failed_can_transition_for_retry(self):
|
||||
"""Test FAILED status can transition to retry checkpoint states."""
|
||||
from backend.models.job import STATE_TRANSITIONS
|
||||
valid_transitions = STATE_TRANSITIONS.get(JobStatus.FAILED, [])
|
||||
|
||||
# FAILED should allow retry transitions
|
||||
assert JobStatus.INSTRUMENTAL_SELECTED in valid_transitions, "FAILED should allow retry to INSTRUMENTAL_SELECTED"
|
||||
assert JobStatus.REVIEW_COMPLETE in valid_transitions, "FAILED should allow retry to REVIEW_COMPLETE"
|
||||
assert JobStatus.LYRICS_COMPLETE in valid_transitions, "FAILED should allow retry to LYRICS_COMPLETE"
|
||||
|
||||
|
||||
class TestJobModelSerialization:
|
||||
|
||||
@@ -41,8 +41,10 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# Loggers to capture for video worker
|
||||
# Include the full module path to properly capture KaraokeFinalise logs
|
||||
VIDEO_WORKER_LOGGERS = [
|
||||
"karaoke_gen.karaoke_finalise",
|
||||
"karaoke_gen.karaoke_finalise.karaoke_finalise", # The actual logger name from __name__
|
||||
]
|
||||
|
||||
|
||||
@@ -116,9 +118,9 @@ async def generate_video(job_id: str) -> bool:
|
||||
|
||||
# Download and set up files in the format KaraokeFinalise expects
|
||||
base_name = f"{job.artist} - {job.title}"
|
||||
job_log.info("Downloading files from GCS...")
|
||||
await _setup_working_directory(job_id, job, storage, temp_dir, base_name)
|
||||
job_log.info("Files downloaded successfully")
|
||||
job_log.info("Downloading files from GCS (this may take a few minutes for large files)...")
|
||||
await _setup_working_directory(job_id, job, storage, temp_dir, base_name, job_log)
|
||||
job_log.info("All files downloaded successfully")
|
||||
|
||||
# Load style config for CDG styles
|
||||
job_log.info("Loading CDG style configuration...")
|
||||
@@ -443,7 +445,8 @@ async def _setup_working_directory(
|
||||
job,
|
||||
storage: StorageService,
|
||||
temp_dir: str,
|
||||
base_name: str
|
||||
base_name: str,
|
||||
job_log=None
|
||||
) -> None:
|
||||
"""
|
||||
Download files from GCS and set up the directory structure KaraokeFinalise expects.
|
||||
@@ -455,25 +458,34 @@ async def _setup_working_directory(
|
||||
- {base_name} (Karaoke).lrc
|
||||
- Instrumental audio file
|
||||
"""
|
||||
logger.info(f"Job {job_id}: Setting up working directory")
|
||||
def log_progress(message: str):
|
||||
"""Log to both module logger and job logger if available."""
|
||||
logger.info(f"Job {job_id}: {message}")
|
||||
if job_log:
|
||||
job_log.info(message)
|
||||
|
||||
log_progress("Setting up working directory")
|
||||
|
||||
# Download title screen
|
||||
log_progress("Downloading title screen...")
|
||||
title_url = job.file_urls['screens']['title']
|
||||
title_path = os.path.join(temp_dir, f"{base_name} (Title).mov")
|
||||
storage.download_file(title_url, title_path)
|
||||
logger.info(f"Job {job_id}: Downloaded title screen")
|
||||
log_progress("Downloaded title screen")
|
||||
|
||||
# Download end screen
|
||||
log_progress("Downloading end screen...")
|
||||
end_url = job.file_urls['screens']['end']
|
||||
end_path = os.path.join(temp_dir, f"{base_name} (End).mov")
|
||||
storage.download_file(end_url, end_path)
|
||||
logger.info(f"Job {job_id}: Downloaded end screen")
|
||||
log_progress("Downloaded end screen")
|
||||
|
||||
# Download lyrics video (with vocals)
|
||||
# Download lyrics video (with vocals) - this is the largest file, ~1-2GB
|
||||
log_progress("Downloading karaoke video (largest file, may take 1-2 minutes)...")
|
||||
lyrics_video_url = job.file_urls['videos']['with_vocals']
|
||||
lyrics_video_path = os.path.join(temp_dir, f"{base_name} (With Vocals).mov")
|
||||
storage.download_file(lyrics_video_url, lyrics_video_path)
|
||||
logger.info(f"Job {job_id}: Downloaded lyrics video")
|
||||
log_progress("Downloaded karaoke video")
|
||||
|
||||
# Download selected instrumental
|
||||
instrumental_selection = job.state_data['instrumental_selection']
|
||||
@@ -481,8 +493,9 @@ async def _setup_working_directory(
|
||||
instrumental_url = job.file_urls['stems'][instrumental_key]
|
||||
instrumental_suffix = "Clean" if instrumental_selection == 'clean' else "Backing"
|
||||
instrumental_path = os.path.join(temp_dir, f"{base_name} (Instrumental {instrumental_suffix}).flac")
|
||||
log_progress(f"Downloading {instrumental_selection} instrumental audio...")
|
||||
storage.download_file(instrumental_url, instrumental_path)
|
||||
logger.info(f"Job {job_id}: Downloaded instrumental ({instrumental_selection})")
|
||||
log_progress(f"Downloaded instrumental ({instrumental_selection})")
|
||||
|
||||
# Download LRC file if available (needed for CDG/TXT)
|
||||
lyrics_urls = job.file_urls.get('lyrics', {})
|
||||
@@ -490,19 +503,19 @@ async def _setup_working_directory(
|
||||
lrc_url = lyrics_urls['lrc']
|
||||
lrc_path = os.path.join(temp_dir, f"{base_name} (Karaoke).lrc")
|
||||
storage.download_file(lrc_url, lrc_path)
|
||||
logger.info(f"Job {job_id}: Downloaded LRC file")
|
||||
log_progress("Downloaded LRC file")
|
||||
|
||||
# Download title/end JPG files (used for YouTube thumbnail)
|
||||
screens = job.file_urls.get('screens', {})
|
||||
if screens.get('title_jpg'):
|
||||
title_jpg_path = os.path.join(temp_dir, f"{base_name} (Title).jpg")
|
||||
storage.download_file(screens['title_jpg'], title_jpg_path)
|
||||
logger.info(f"Job {job_id}: Downloaded title JPG for thumbnail")
|
||||
log_progress("Downloaded title JPG for thumbnail")
|
||||
|
||||
if screens.get('end_jpg'):
|
||||
end_jpg_path = os.path.join(temp_dir, f"{base_name} (End).jpg")
|
||||
storage.download_file(screens['end_jpg'], end_jpg_path)
|
||||
logger.info(f"Job {job_id}: Downloaded end JPG")
|
||||
log_progress("Downloaded end JPG")
|
||||
|
||||
|
||||
async def _upload_results(
|
||||
|
||||
@@ -860,7 +860,7 @@ class KaraokeFinalise:
|
||||
return env_mov_input, ffmpeg_filter
|
||||
|
||||
def remux_and_encode_output_video_files(self, with_vocals_file, input_files, output_files):
|
||||
self.logger.info(f"Remuxing and encoding output video files...")
|
||||
self.logger.info(f"Remuxing and encoding output video files (4 formats, ~15-20 minutes total)...")
|
||||
|
||||
# Check if output files already exist
|
||||
if os.path.isfile(output_files["final_karaoke_lossless_mp4"]) and os.path.isfile(output_files["final_karaoke_lossless_mkv"]):
|
||||
@@ -871,16 +871,20 @@ class KaraokeFinalise:
|
||||
return
|
||||
|
||||
# Create karaoke version with instrumental audio
|
||||
self.logger.info(f"[Step 1/6] Remuxing video with instrumental audio...")
|
||||
self.remux_with_instrumental(with_vocals_file, input_files["instrumental_audio"], output_files["karaoke_mp4"])
|
||||
|
||||
# Convert the with vocals video to MP4 if needed
|
||||
if not with_vocals_file.endswith(".mp4"):
|
||||
self.logger.info(f"[Step 2/6] Converting karaoke video to MP4...")
|
||||
self.convert_mov_to_mp4(with_vocals_file, output_files["with_vocals_mp4"])
|
||||
|
||||
# Delete the with vocals mov after successfully converting it to mp4
|
||||
if not self.dry_run and os.path.isfile(with_vocals_file):
|
||||
self.logger.info(f"Deleting with vocals MOV file: {with_vocals_file}")
|
||||
os.remove(with_vocals_file)
|
||||
else:
|
||||
self.logger.info(f"[Step 2/6] Skipped - video already in MP4 format")
|
||||
|
||||
# Quote file paths to handle special characters
|
||||
title_mov_file = shlex.quote(os.path.abspath(input_files["title_mov"]))
|
||||
@@ -889,10 +893,17 @@ class KaraokeFinalise:
|
||||
# Prepare concat filter for combining videos
|
||||
env_mov_input, ffmpeg_filter = self.prepare_concat_filter(input_files)
|
||||
|
||||
# Create all output versions
|
||||
# Create all output versions with progress logging
|
||||
self.logger.info(f"[Step 3/6] Encoding lossless 4K MP4 (title + karaoke + end, ~5 minutes)...")
|
||||
self.encode_lossless_mp4(title_mov_file, karaoke_mp4_file, env_mov_input, ffmpeg_filter, output_files["final_karaoke_lossless_mp4"])
|
||||
|
||||
self.logger.info(f"[Step 4/6] Encoding lossy 4K MP4 with AAC audio (~1 minute)...")
|
||||
self.encode_lossy_mp4(output_files["final_karaoke_lossless_mp4"], output_files["final_karaoke_lossy_mp4"])
|
||||
|
||||
self.logger.info(f"[Step 5/6] Creating MKV with FLAC audio for YouTube (~1 minute)...")
|
||||
self.encode_lossless_mkv(output_files["final_karaoke_lossless_mp4"], output_files["final_karaoke_lossless_mkv"])
|
||||
|
||||
self.logger.info(f"[Step 6/6] Encoding 720p version (~3 minutes)...")
|
||||
self.encode_720p_version(output_files["final_karaoke_lossless_mp4"], output_files["final_karaoke_lossy_720p_mp4"])
|
||||
|
||||
# Skip user confirmation in non-interactive mode for Modal deployment
|
||||
@@ -1668,11 +1679,17 @@ class KaraokeFinalise:
|
||||
if self.dry_run:
|
||||
self.logger.warning("Dry run enabled. No actions will be performed.")
|
||||
|
||||
self.logger.info("=" * 60)
|
||||
self.logger.info("Starting KaraokeFinalise processing pipeline")
|
||||
self.logger.info("=" * 60)
|
||||
|
||||
# Check required input files and parameters exist, get user to confirm features before proceeding
|
||||
self.validate_input_parameters_for_features()
|
||||
|
||||
with_vocals_file = self.find_with_vocals_file()
|
||||
base_name, artist, title = self.get_names_from_withvocals(with_vocals_file)
|
||||
|
||||
self.logger.info(f"Processing: {artist} - {title}")
|
||||
|
||||
# Use the selected instrumental file if provided, otherwise search for one
|
||||
if self.selected_instrumental_file:
|
||||
@@ -1688,13 +1705,20 @@ class KaraokeFinalise:
|
||||
output_files = self.prepare_output_filenames(base_name)
|
||||
|
||||
if self.enable_cdg:
|
||||
self.logger.info("Creating CDG package...")
|
||||
self.create_cdg_zip_file(input_files, output_files, artist, title)
|
||||
self.logger.info("CDG package created successfully")
|
||||
|
||||
if self.enable_txt:
|
||||
self.logger.info("Creating TXT package...")
|
||||
self.create_txt_zip_file(input_files, output_files)
|
||||
self.logger.info("TXT package created successfully")
|
||||
|
||||
self.logger.info("Starting video encoding (this is the longest step, ~15-20 minutes)...")
|
||||
self.remux_and_encode_output_video_files(with_vocals_file, input_files, output_files)
|
||||
self.logger.info("Video encoding completed successfully")
|
||||
|
||||
self.logger.info("Executing distribution features (YouTube, Dropbox, Discord)...")
|
||||
self.execute_optional_features(artist, title, base_name, input_files, output_files, replace_existing)
|
||||
|
||||
result = {
|
||||
|
||||
@@ -610,6 +610,40 @@ class JobMonitor:
|
||||
self._last_timeline_index = 0
|
||||
self._last_log_index = 0
|
||||
self._show_worker_logs = True # Enable worker log display
|
||||
self._polls_without_updates = 0 # Track polling activity for heartbeat
|
||||
self._heartbeat_interval = 6 # Show heartbeat every N polls without updates (~30s with 5s poll)
|
||||
|
||||
# Status descriptions for user-friendly logging
|
||||
STATUS_DESCRIPTIONS = {
|
||||
'pending': 'Job queued, waiting to start',
|
||||
'downloading': 'Downloading and preparing input files',
|
||||
'separating_stage1': 'AI audio separation (stage 1 of 2)',
|
||||
'separating_stage2': 'AI audio separation (stage 2 of 2)',
|
||||
'audio_complete': 'Audio separation complete',
|
||||
'transcribing': 'Transcribing lyrics from audio',
|
||||
'correcting': 'Auto-correcting lyrics against reference sources',
|
||||
'lyrics_complete': 'Lyrics processing complete',
|
||||
'generating_screens': 'Creating title and end screens',
|
||||
'applying_padding': 'Adding intro/outro padding',
|
||||
'awaiting_review': 'Waiting for lyrics review',
|
||||
'in_review': 'Lyrics review in progress',
|
||||
'review_complete': 'Review complete, preparing video render',
|
||||
'rendering_video': 'Rendering karaoke video with lyrics',
|
||||
'awaiting_instrumental_selection': 'Waiting for instrumental selection',
|
||||
'instrumental_selected': 'Instrumental selected, preparing final encoding',
|
||||
'generating_video': 'Downloading files for final video encoding',
|
||||
'encoding': 'Encoding final videos (15-20 min, 4 formats)',
|
||||
'packaging': 'Creating CDG/TXT packages',
|
||||
'uploading': 'Uploading to distribution services',
|
||||
'notifying': 'Sending notifications',
|
||||
'complete': 'All processing complete',
|
||||
'failed': 'Job failed',
|
||||
'cancelled': 'Job cancelled',
|
||||
}
|
||||
|
||||
def _get_status_description(self, status: str) -> str:
|
||||
"""Get user-friendly description for a status."""
|
||||
return self.STATUS_DESCRIPTIONS.get(status, status)
|
||||
|
||||
def open_browser(self, url: str) -> None:
|
||||
"""Open URL in the default browser."""
|
||||
@@ -1101,6 +1135,7 @@ class JobMonitor:
|
||||
|
||||
self.logger.info(f"Monitoring job: {job_id}")
|
||||
self.logger.info(f"Service URL: {self.config.service_url}")
|
||||
self.logger.info(f"Polling every {self.config.poll_interval} seconds...")
|
||||
self.logger.info("")
|
||||
|
||||
while True:
|
||||
@@ -1111,16 +1146,40 @@ class JobMonitor:
|
||||
artist = job_data.get('artist', '')
|
||||
title = job_data.get('title', '')
|
||||
|
||||
# Track whether we got any new updates this poll
|
||||
had_updates = False
|
||||
prev_timeline_index = self._last_timeline_index
|
||||
prev_log_index = self._last_log_index
|
||||
|
||||
# Log timeline updates (shows status changes and progress)
|
||||
self.log_timeline_updates(job_data)
|
||||
if self._last_timeline_index > prev_timeline_index:
|
||||
had_updates = True
|
||||
|
||||
# Log worker logs (shows detailed worker output for debugging)
|
||||
self.log_worker_logs(job_id)
|
||||
if self._last_log_index > prev_log_index:
|
||||
had_updates = True
|
||||
|
||||
# Log status changes
|
||||
# Log status changes with user-friendly descriptions
|
||||
if status != last_status:
|
||||
self.logger.info(f"Status changed: {last_status} -> {status}")
|
||||
description = self._get_status_description(status)
|
||||
if last_status:
|
||||
self.logger.info(f"Status: {status} - {description}")
|
||||
else:
|
||||
self.logger.info(f"Current status: {status} - {description}")
|
||||
last_status = status
|
||||
had_updates = True
|
||||
|
||||
# Heartbeat: if no updates for a while, show we're still alive
|
||||
if had_updates:
|
||||
self._polls_without_updates = 0
|
||||
else:
|
||||
self._polls_without_updates += 1
|
||||
if self._polls_without_updates >= self._heartbeat_interval:
|
||||
description = self._get_status_description(status)
|
||||
self.logger.info(f" [Still processing: {description}]")
|
||||
self._polls_without_updates = 0
|
||||
|
||||
# Handle human interaction points
|
||||
if status in ['awaiting_review', 'in_review']:
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.71.17"
|
||||
version = "0.71.19"
|
||||
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
|
||||
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
|
||||
license = "MIT"
|
||||
|
||||
+1
-1
@@ -112,7 +112,7 @@ echo -e "${YELLOW}---BEGIN SERVICE ACCOUNT KEY---${NC}"
|
||||
cat "$KEY_FILE"
|
||||
echo -e "${YELLOW}---END SERVICE ACCOUNT KEY---${NC}"
|
||||
echo ""
|
||||
echo "3. After adding secrets, push to 'replace-modal-with-google-cloud' branch"
|
||||
echo "3. After adding secrets, push to 'main' branch"
|
||||
echo " to trigger an automated deployment!"
|
||||
echo ""
|
||||
echo -e "${RED}⚠️ IMPORTANT SECURITY NOTES:${NC}"
|
||||
|
||||
Reference in new issue
Block a user