mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-28 01:49:00 +09:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
41df208e5d | ||
|
|
7ffb219b9f | ||
|
|
f740c68f4b | ||
|
|
14c0abd40f | ||
|
|
4b01f1100f |
No files matched your search
@@ -2,6 +2,14 @@
|
||||
|
||||
This document contains guidelines and rules for AI assistants working on this codebase.
|
||||
|
||||
## Core Principles
|
||||
|
||||
**Always be testing.** Proactively evaluate, read, run, fix, and improve tests whenever you touch any part of the system—frontend, backend, infrastructure. Every code change should be thoroughly tested. Leave everything better tested than you found it.
|
||||
|
||||
**Always be documenting.** Continuously read, write, improve, update, and organize markdown documentation. Reference existing docs and keep them accurate as the codebase evolves.
|
||||
|
||||
**Build for maintainability.** Keep code SOLID, modular, and clean. Favor simplicity and clarity. Future developers (and AI agents) will thank you.
|
||||
|
||||
## Branching Workflow
|
||||
|
||||
**Never commit directly to `main`.** Always work on a feature branch.
|
||||
|
||||
+48
-11
@@ -1097,32 +1097,34 @@ async def retry_job(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
) -> dict:
|
||||
"""
|
||||
Retry a failed job from the last successful checkpoint.
|
||||
|
||||
This endpoint allows resuming jobs that failed during:
|
||||
Retry a failed or cancelled job from the last successful checkpoint.
|
||||
|
||||
This endpoint allows resuming jobs that failed or were cancelled during:
|
||||
- Audio processing (re-runs from beginning if input audio exists)
|
||||
- Video generation (re-runs video worker)
|
||||
- Encoding (re-runs video worker)
|
||||
- Packaging (re-runs video worker)
|
||||
|
||||
|
||||
The retry logic determines the appropriate stage to resume from
|
||||
based on what files/state already exist.
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
if job.status != JobStatus.FAILED:
|
||||
|
||||
if job.status not in [JobStatus.FAILED, JobStatus.CANCELLED]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Only failed jobs can be retried (current status: {job.status})"
|
||||
detail=f"Only failed or cancelled jobs can be retried (current status: {job.status})"
|
||||
)
|
||||
|
||||
try:
|
||||
# Determine retry point based on what's already complete
|
||||
error_details = job.error_details or {}
|
||||
error_stage = error_details.get('stage', 'unknown')
|
||||
|
||||
logger.info(f"Job {job_id}: Retrying from failed stage '{error_stage}'")
|
||||
original_status = job.status
|
||||
|
||||
logger.info(f"Job {job_id}: Retrying from {original_status} state (error stage: '{error_stage}')")
|
||||
|
||||
# Check what state exists to determine retry point
|
||||
file_urls = job.file_urls or {}
|
||||
@@ -1230,11 +1232,46 @@ async def retry_job(
|
||||
"retry_stage": "screens_generation"
|
||||
}
|
||||
|
||||
# If we have input audio (uploaded or from URL), restart from beginning
|
||||
elif job.input_media_gcs_path or job.url:
|
||||
logger.info(f"Job {job_id}: Has input audio, restarting from beginning")
|
||||
|
||||
# Clear error state and any partial progress
|
||||
job_manager.update_job(job_id, {
|
||||
'error_message': None,
|
||||
'error_details': None,
|
||||
'state_data': {}, # Clear parallel worker progress
|
||||
})
|
||||
|
||||
# Reset to DOWNLOADING and trigger audio worker
|
||||
if not job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING,
|
||||
progress=5,
|
||||
message=f"Restarting job from {original_status} state"
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to transition job status for retry"
|
||||
)
|
||||
|
||||
# Trigger audio worker (which kicks off parallel audio + lyrics processing)
|
||||
background_tasks.add_task(worker_service.trigger_audio_worker, job_id)
|
||||
background_tasks.add_task(worker_service.trigger_lyrics_worker, job_id)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"job_id": job_id,
|
||||
"job_status": "downloading",
|
||||
"message": f"Job restarted from {original_status} state",
|
||||
"retry_stage": "from_beginning"
|
||||
}
|
||||
|
||||
else:
|
||||
# Can't determine a safe retry point, need to restart from beginning
|
||||
# No input audio available - job needs to be resubmitted
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Cannot determine safe retry point. Job may need to be resubmitted."
|
||||
detail="Cannot retry: no input audio available. Job must be resubmitted."
|
||||
)
|
||||
|
||||
except HTTPException:
|
||||
|
||||
@@ -134,17 +134,23 @@ STATE_TRANSITIONS = {
|
||||
JobStatus.UPLOADING: [JobStatus.NOTIFYING, JobStatus.COMPLETE, JobStatus.FAILED],
|
||||
JobStatus.NOTIFYING: [JobStatus.COMPLETE, JobStatus.FAILED],
|
||||
|
||||
# Terminal states - COMPLETE, PREP_COMPLETE, and CANCELLED have no transitions
|
||||
# FAILED allows retry transitions to resume from checkpoints
|
||||
# Terminal states - COMPLETE, PREP_COMPLETE have no transitions
|
||||
# FAILED and CANCELLED allow retry transitions to resume from checkpoints
|
||||
# PREP_COMPLETE allows finalise-only continuation
|
||||
JobStatus.COMPLETE: [],
|
||||
JobStatus.PREP_COMPLETE: [JobStatus.AWAITING_INSTRUMENTAL_SELECTION, JobStatus.FAILED], # Finalise-only continues from here
|
||||
JobStatus.FAILED: [
|
||||
JobStatus.DOWNLOADING, # Retry from beginning (if input audio exists)
|
||||
JobStatus.INSTRUMENTAL_SELECTED, # Retry from video generation
|
||||
JobStatus.REVIEW_COMPLETE, # Retry from render stage
|
||||
JobStatus.LYRICS_COMPLETE, # Retry from screens generation
|
||||
],
|
||||
JobStatus.CANCELLED: [
|
||||
JobStatus.DOWNLOADING, # Retry from beginning (if input audio exists)
|
||||
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)
|
||||
JobStatus.QUEUED: [JobStatus.PENDING],
|
||||
|
||||
@@ -67,12 +67,31 @@ class TestJobStatusTransitions:
|
||||
"""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"
|
||||
|
||||
def test_cancelled_can_transition_for_retry(self):
|
||||
"""Test CANCELLED status can transition to retry checkpoint states."""
|
||||
from backend.models.job import STATE_TRANSITIONS
|
||||
valid_transitions = STATE_TRANSITIONS.get(JobStatus.CANCELLED, [])
|
||||
|
||||
# CANCELLED should allow same retry transitions as FAILED
|
||||
assert JobStatus.INSTRUMENTAL_SELECTED in valid_transitions, "CANCELLED should allow retry to INSTRUMENTAL_SELECTED"
|
||||
assert JobStatus.REVIEW_COMPLETE in valid_transitions, "CANCELLED should allow retry to REVIEW_COMPLETE"
|
||||
assert JobStatus.LYRICS_COMPLETE in valid_transitions, "CANCELLED should allow retry to LYRICS_COMPLETE"
|
||||
assert JobStatus.DOWNLOADING in valid_transitions, "CANCELLED should allow retry to DOWNLOADING (restart)"
|
||||
|
||||
def test_failed_can_restart_from_beginning(self):
|
||||
"""Test FAILED status can transition to DOWNLOADING for restart from beginning."""
|
||||
from backend.models.job import STATE_TRANSITIONS
|
||||
valid_transitions = STATE_TRANSITIONS.get(JobStatus.FAILED, [])
|
||||
|
||||
# FAILED should allow restart from beginning
|
||||
assert JobStatus.DOWNLOADING in valid_transitions, "FAILED should allow restart to DOWNLOADING"
|
||||
|
||||
|
||||
class TestJobModelSerialization:
|
||||
"""Tests for Job model serialization to/from API."""
|
||||
@@ -119,3 +138,145 @@ class TestJobModelSerialization:
|
||||
assert job.url is None
|
||||
assert job.file_urls == {}
|
||||
|
||||
|
||||
class TestRetryEndpoint:
|
||||
"""Tests for the retry job endpoint."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job_manager(self):
|
||||
"""Create mock job manager."""
|
||||
return MagicMock()
|
||||
|
||||
@pytest.fixture
|
||||
def mock_worker_service(self):
|
||||
"""Create mock worker service."""
|
||||
return MagicMock()
|
||||
|
||||
def test_retry_rejects_pending_job(self, mock_job_manager):
|
||||
"""Test retry endpoint rejects jobs that are not failed or cancelled."""
|
||||
# Create a pending job
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song"
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job
|
||||
|
||||
# The endpoint should reject this with a 400 error
|
||||
# (status check happens before any logic)
|
||||
assert job.status not in [JobStatus.FAILED, JobStatus.CANCELLED]
|
||||
|
||||
def test_retry_accepts_failed_job(self, mock_job_manager):
|
||||
"""Test retry endpoint accepts failed jobs."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.FAILED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
input_media_gcs_path="jobs/test123/input/audio.flac"
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job
|
||||
|
||||
# Status should be accepted
|
||||
assert job.status in [JobStatus.FAILED, JobStatus.CANCELLED]
|
||||
|
||||
def test_retry_accepts_cancelled_job(self, mock_job_manager):
|
||||
"""Test retry endpoint accepts cancelled jobs."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.CANCELLED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
input_media_gcs_path="jobs/test123/input/audio.flac"
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job
|
||||
|
||||
# Status should be accepted
|
||||
assert job.status in [JobStatus.FAILED, JobStatus.CANCELLED]
|
||||
|
||||
def test_retry_checkpoint_detection_video_generation(self):
|
||||
"""Test retry detects video generation checkpoint."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.FAILED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
file_urls={
|
||||
'videos': {'with_vocals': 'gs://bucket/path/video.mkv'}
|
||||
},
|
||||
state_data={
|
||||
'instrumental_selection': 'clean'
|
||||
}
|
||||
)
|
||||
|
||||
# This job has video and instrumental selection - should retry from video generation
|
||||
has_video = job.file_urls.get('videos', {}).get('with_vocals')
|
||||
has_instrumental_selection = (job.state_data or {}).get('instrumental_selection')
|
||||
assert has_video and has_instrumental_selection
|
||||
|
||||
def test_retry_checkpoint_detection_render_stage(self):
|
||||
"""Test retry detects render stage checkpoint."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.FAILED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
file_urls={
|
||||
'lyrics': {'corrections': 'gs://bucket/path/corrections.json'},
|
||||
'screens': {'title': 'gs://bucket/path/title.mov'}
|
||||
}
|
||||
)
|
||||
|
||||
# This job has corrections and screens - should retry from render
|
||||
has_corrections = job.file_urls.get('lyrics', {}).get('corrections')
|
||||
has_screens = job.file_urls.get('screens', {}).get('title')
|
||||
has_video = job.file_urls.get('videos', {}).get('with_vocals')
|
||||
assert has_corrections and has_screens and not has_video
|
||||
|
||||
def test_retry_checkpoint_detection_from_beginning(self):
|
||||
"""Test retry detects need to restart from beginning."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.CANCELLED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
input_media_gcs_path="jobs/test123/input/audio.flac",
|
||||
file_urls={} # No progress yet
|
||||
)
|
||||
|
||||
# This job has input audio but no other files - should restart from beginning
|
||||
has_input = job.input_media_gcs_path
|
||||
has_stems = job.file_urls.get('stems', {}).get('instrumental_clean')
|
||||
has_corrections = job.file_urls.get('lyrics', {}).get('corrections')
|
||||
assert has_input and not has_stems and not has_corrections
|
||||
|
||||
def test_retry_no_input_audio(self):
|
||||
"""Test retry fails when no input audio available."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.CANCELLED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
# No input_media_gcs_path and no url
|
||||
file_urls={}
|
||||
)
|
||||
|
||||
# This job has no input audio - should not be retryable
|
||||
has_input = job.input_media_gcs_path or job.url
|
||||
assert not has_input
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
/**
|
||||
* Tests for JobActions component
|
||||
*/
|
||||
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { JobActions } from '../job/JobActions'
|
||||
import { Job } from '@/lib/api'
|
||||
|
||||
// Mock the API module
|
||||
jest.mock('@/lib/api', () => ({
|
||||
api: {
|
||||
retryJob: jest.fn(),
|
||||
cancelJob: jest.fn(),
|
||||
deleteJob: jest.fn(),
|
||||
}
|
||||
}))
|
||||
|
||||
describe('JobActions', () => {
|
||||
const mockOnRefresh = jest.fn()
|
||||
const mockOnToggleLogs = jest.fn()
|
||||
|
||||
const baseJob: Partial<Job> = {
|
||||
job_id: '123',
|
||||
created_at: '2025-01-01T00:00:00Z',
|
||||
updated_at: '2025-01-01T00:00:00Z',
|
||||
artist: 'Test Artist',
|
||||
title: 'Test Song',
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('Retry button visibility', () => {
|
||||
it('shows retry button for failed jobs', () => {
|
||||
const failedJob = { ...baseJob, status: 'failed' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={failedJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Retry')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows retry button for cancelled jobs', () => {
|
||||
const cancelledJob = { ...baseJob, status: 'cancelled' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={cancelledJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Retry')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show retry button for pending jobs', () => {
|
||||
const pendingJob = { ...baseJob, status: 'pending' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={pendingJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.queryByText('Retry')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show retry button for processing jobs', () => {
|
||||
const processingJob = { ...baseJob, status: 'processing' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={processingJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.queryByText('Retry')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show retry button for complete jobs', () => {
|
||||
const completeJob = { ...baseJob, status: 'complete' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={completeJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.queryByText('Retry')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Cancel button visibility', () => {
|
||||
it('shows cancel button for pending jobs', () => {
|
||||
const pendingJob = { ...baseJob, status: 'pending' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={pendingJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Cancel')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show cancel button for failed jobs', () => {
|
||||
const failedJob = { ...baseJob, status: 'failed' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={failedJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.queryByText('Cancel')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show cancel button for cancelled jobs', () => {
|
||||
const cancelledJob = { ...baseJob, status: 'cancelled' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={cancelledJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.queryByText('Cancel')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Delete button visibility', () => {
|
||||
it('shows delete button for complete jobs', () => {
|
||||
const completeJob = { ...baseJob, status: 'complete' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={completeJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Delete')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows delete button for failed jobs', () => {
|
||||
const failedJob = { ...baseJob, status: 'failed' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={failedJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Delete')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows delete button for cancelled jobs', () => {
|
||||
const cancelledJob = { ...baseJob, status: 'cancelled' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={cancelledJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Delete')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show delete button for pending jobs', () => {
|
||||
const pendingJob = { ...baseJob, status: 'pending' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={pendingJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.queryByText('Delete')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Show Logs button', () => {
|
||||
it('always shows Show Logs button', () => {
|
||||
const pendingJob = { ...baseJob, status: 'pending' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={pendingJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Show Logs')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows Hide Logs when logs are visible', () => {
|
||||
const pendingJob = { ...baseJob, status: 'pending' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={pendingJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={true}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Hide Logs')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -19,7 +19,7 @@ export function JobActions({ job, onRefresh, showLogs, onToggleLogs }: JobAction
|
||||
const [isCancelling, setIsCancelling] = useState(false)
|
||||
const [isDeleting, setIsDeleting] = useState(false)
|
||||
|
||||
const canRetry = job.status === "failed"
|
||||
const canRetry = job.status === "failed" || job.status === "cancelled"
|
||||
const canCancel = !["complete", "failed", "cancelled"].includes(job.status)
|
||||
const canDelete = ["complete", "failed", "cancelled"].includes(job.status)
|
||||
|
||||
|
||||
@@ -31,6 +31,12 @@ from .video_generator import VideoGenerator
|
||||
from .video_background_processor import VideoBackgroundProcessor
|
||||
from .audio_fetcher import create_audio_fetcher, AudioFetcherError, NoResultsError, UserCancelledError
|
||||
|
||||
# Import lyrics_transcriber components for post-review countdown and video rendering
|
||||
from lyrics_transcriber.output.countdown_processor import CountdownProcessor
|
||||
from lyrics_transcriber.output.generator import OutputGenerator
|
||||
from lyrics_transcriber.types import CorrectionResult
|
||||
from lyrics_transcriber.core.config import OutputConfig as LyricsOutputConfig
|
||||
|
||||
|
||||
class KaraokePrep:
|
||||
def __init__(
|
||||
@@ -692,6 +698,112 @@ class KaraokePrep:
|
||||
|
||||
self.logger.info("=== Parallel Processing Complete ===")
|
||||
|
||||
# === POST-TRANSCRIPTION: Add countdown and render video ===
|
||||
# Since lyrics_processor.py now always defers countdown and video rendering,
|
||||
# we handle it here after human review is complete. This ensures the review UI
|
||||
# shows accurate, unshifted timestamps (same behavior as cloud backend).
|
||||
if processed_track.get("lyrics") and self.render_video:
|
||||
self.logger.info("=== Processing Countdown and Video Rendering ===")
|
||||
|
||||
from .utils import sanitize_filename
|
||||
sanitized_artist = sanitize_filename(self.artist)
|
||||
sanitized_title = sanitize_filename(self.title)
|
||||
lyrics_dir = os.path.join(track_output_dir, "lyrics")
|
||||
|
||||
# Find the corrections JSON file
|
||||
corrections_filename = f"{sanitized_artist} - {sanitized_title} (Lyrics Corrections).json"
|
||||
corrections_filepath = os.path.join(lyrics_dir, corrections_filename)
|
||||
|
||||
if os.path.exists(corrections_filepath):
|
||||
self.logger.info(f"Loading corrections from: {corrections_filepath}")
|
||||
|
||||
with open(corrections_filepath, 'r', encoding='utf-8') as f:
|
||||
corrections_data = json.load(f)
|
||||
|
||||
# Convert to CorrectionResult
|
||||
correction_result = CorrectionResult.from_dict(corrections_data)
|
||||
self.logger.info(f"Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
|
||||
|
||||
# Get the audio file path
|
||||
audio_path = processed_track["input_audio_wav"]
|
||||
|
||||
# Add countdown intro if needed (songs that start within 3 seconds)
|
||||
self.logger.info("Processing countdown intro (if needed)...")
|
||||
cache_dir = os.path.join(track_output_dir, "cache")
|
||||
os.makedirs(cache_dir, exist_ok=True)
|
||||
|
||||
countdown_processor = CountdownProcessor(
|
||||
cache_dir=cache_dir,
|
||||
logger=self.logger,
|
||||
)
|
||||
|
||||
correction_result, audio_path, padding_added, padding_seconds = countdown_processor.process(
|
||||
correction_result=correction_result,
|
||||
audio_filepath=audio_path,
|
||||
)
|
||||
|
||||
# Update processed_track with countdown info
|
||||
processed_track["countdown_padding_added"] = padding_added
|
||||
processed_track["countdown_padding_seconds"] = padding_seconds
|
||||
if padding_added:
|
||||
processed_track["padded_vocals_audio"] = audio_path
|
||||
self.logger.info(
|
||||
f"=== COUNTDOWN PADDING ADDED ===\n"
|
||||
f"Added {padding_seconds}s padding to audio and shifted timestamps.\n"
|
||||
f"Instrumental tracks will be padded after separation to maintain sync."
|
||||
)
|
||||
else:
|
||||
self.logger.info("No countdown needed - song starts after 3 seconds")
|
||||
|
||||
# Save the updated corrections with countdown timestamps
|
||||
updated_corrections_data = correction_result.to_dict()
|
||||
with open(corrections_filepath, 'w', encoding='utf-8') as f:
|
||||
json.dump(updated_corrections_data, f, indent=2)
|
||||
self.logger.info(f"Saved countdown-adjusted corrections to: {corrections_filepath}")
|
||||
|
||||
# Render video with lyrics
|
||||
self.logger.info("Rendering karaoke video with synchronized lyrics...")
|
||||
|
||||
output_config = LyricsOutputConfig(
|
||||
output_dir=lyrics_dir,
|
||||
cache_dir=cache_dir,
|
||||
output_styles_json=self.style_params_json,
|
||||
render_video=True,
|
||||
generate_cdg=False,
|
||||
generate_plain_text=True,
|
||||
generate_lrc=True,
|
||||
video_resolution="4k",
|
||||
subtitle_offset_ms=self.subtitle_offset_ms,
|
||||
)
|
||||
|
||||
output_generator = OutputGenerator(output_config, self.logger)
|
||||
output_prefix = f"{sanitized_artist} - {sanitized_title}"
|
||||
|
||||
outputs = output_generator.generate_outputs(
|
||||
transcription_corrected=correction_result,
|
||||
audio_filepath=audio_path,
|
||||
output_prefix=output_prefix,
|
||||
)
|
||||
|
||||
# Copy video to expected location in parent directory
|
||||
if outputs and outputs.get("video_filepath"):
|
||||
source_video = outputs["video_filepath"]
|
||||
dest_video = os.path.join(track_output_dir, f"{artist_title} (With Vocals).mkv")
|
||||
shutil.copy2(source_video, dest_video)
|
||||
self.logger.info(f"Video rendered successfully: {dest_video}")
|
||||
processed_track["with_vocals_video"] = dest_video
|
||||
|
||||
# Update ASS filepath for video background processing
|
||||
if outputs.get("ass_filepath"):
|
||||
processed_track["ass_filepath"] = outputs["ass_filepath"]
|
||||
else:
|
||||
self.logger.warning("Video rendering did not produce expected output")
|
||||
else:
|
||||
self.logger.warning(f"Corrections file not found: {corrections_filepath}")
|
||||
self.logger.warning("Skipping countdown processing and video rendering")
|
||||
elif not self.render_video:
|
||||
self.logger.info("Video rendering disabled - skipping countdown and video generation")
|
||||
|
||||
# Apply video background if requested and lyrics were processed
|
||||
if self.video_background_processor and processed_track.get("lyrics"):
|
||||
self.logger.info("=== Processing Video Background ===")
|
||||
|
||||
@@ -364,39 +364,20 @@ class LyricsProcessor:
|
||||
self.logger.info(f" rapidapi_key: {env_config.get('rapidapi_key')[:3] + '...' if env_config.get('rapidapi_key') else 'None'}")
|
||||
self.logger.info(f" lyrics_file: {self.lyrics_file}")
|
||||
|
||||
# Detect if we're running in a serverless/cloud environment (Modal or Cloud Run)
|
||||
# In these environments, we defer countdown processing to Phase 2 (render_video_worker)
|
||||
# so the review UI shows the original timing without the 3s shift
|
||||
is_serverless = (
|
||||
# Modal environment detection
|
||||
os.getenv("MODAL_TASK_ID") is not None or
|
||||
os.getenv("MODAL_FUNCTION_NAME") is not None or
|
||||
os.path.exists("/.modal") or # Modal creates this directory in containers
|
||||
# Cloud Run environment detection
|
||||
os.getenv("K_SERVICE") is not None # Cloud Run always sets this
|
||||
)
|
||||
|
||||
# In serverless environment, disable interactive review even if skip_transcription_review=False
|
||||
# This preserves CLI behavior while fixing serverless hanging
|
||||
enable_review_setting = not self.skip_transcription_review and not is_serverless
|
||||
|
||||
if is_serverless and not self.skip_transcription_review:
|
||||
self.logger.info("Detected cloud environment (Modal/Cloud Run) - disabling interactive review to prevent hanging")
|
||||
|
||||
# In serverless environment, disable video generation during Phase 1 to save compute
|
||||
# Video will be generated in Phase 2 after human review
|
||||
serverless_render_video = render_video and not is_serverless
|
||||
|
||||
if is_serverless and render_video:
|
||||
self.logger.info("Detected cloud environment (Modal/Cloud Run) - deferring video generation until after review")
|
||||
|
||||
if is_serverless:
|
||||
self.logger.info("Detected cloud environment (Modal/Cloud Run) - deferring countdown processing until after review")
|
||||
# Always defer countdown and video rendering to a later phase.
|
||||
# This ensures the review UI (both local and cloud) shows original timing
|
||||
# without the 3-second countdown shift. The caller is responsible for:
|
||||
# - Local CLI: karaoke_gen.py adds countdown and renders video after transcription
|
||||
# - Cloud backend: render_video_worker.py adds countdown and renders video
|
||||
#
|
||||
# This design ensures consistent behavior regardless of environment,
|
||||
# and the review UI always shows accurate, unshifted timestamps.
|
||||
self.logger.info("Deferring countdown and video rendering to post-review phase")
|
||||
|
||||
output_config = OutputConfig(
|
||||
output_styles_json=self.style_params_json,
|
||||
output_dir=lyrics_dir,
|
||||
render_video=serverless_render_video, # Disable video in serverless Phase 1
|
||||
render_video=False, # Always defer - caller handles video rendering after countdown
|
||||
fetch_lyrics=True,
|
||||
run_transcription=not self.skip_transcription,
|
||||
run_correction=True,
|
||||
@@ -404,9 +385,9 @@ class LyricsProcessor:
|
||||
generate_lrc=True,
|
||||
generate_cdg=False, # CDG generation disabled (not currently supported)
|
||||
video_resolution="4k",
|
||||
enable_review=enable_review_setting,
|
||||
enable_review=not self.skip_transcription_review, # Honor the caller's setting
|
||||
subtitle_offset_ms=self.subtitle_offset_ms,
|
||||
add_countdown=not is_serverless, # Defer countdown to Phase 2 (render_video_worker)
|
||||
add_countdown=False, # Always defer - caller handles countdown after review
|
||||
)
|
||||
|
||||
# Add this log entry to debug the OutputConfig
|
||||
|
||||
Reference in new issue
Block a user