mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-20 13:07:57 +09:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f99d6c1fb4 | ||
|
|
f8a45bfbd2 |
No files matched your search
@@ -447,11 +447,24 @@ async def upload_lyrics_results(
|
||||
corrections_data = json.load(f)
|
||||
|
||||
# Store metadata in state_data
|
||||
job_manager.update_state_data(job_id, 'lyrics_metadata', {
|
||||
# Include countdown padding info for instrumental synchronization
|
||||
lyrics_metadata = {
|
||||
'segment_count': len(corrections_data.get('corrected_segments', [])),
|
||||
'has_corrections': True,
|
||||
'ready_for_review': True
|
||||
})
|
||||
'ready_for_review': True,
|
||||
}
|
||||
|
||||
# Add countdown padding info from transcription result
|
||||
# This is needed by video_worker to pad instrumentals for sync
|
||||
if transcription_result.get("countdown_padding_added"):
|
||||
lyrics_metadata['has_countdown_padding'] = True
|
||||
lyrics_metadata['countdown_padding_seconds'] = transcription_result.get("countdown_padding_seconds", 3.0)
|
||||
logger.info(f"Job {job_id}: Countdown padding detected: {lyrics_metadata['countdown_padding_seconds']}s")
|
||||
else:
|
||||
lyrics_metadata['has_countdown_padding'] = False
|
||||
lyrics_metadata['countdown_padding_seconds'] = 0.0
|
||||
|
||||
job_manager.update_state_data(job_id, 'lyrics_metadata', lyrics_metadata)
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {job_id}: Could not parse corrections JSON: {e}")
|
||||
else:
|
||||
|
||||
@@ -162,6 +162,14 @@ async def generate_video(job_id: str) -> bool:
|
||||
message="Encoding videos (15-20 min)"
|
||||
)
|
||||
|
||||
# Get countdown padding info from lyrics metadata
|
||||
# This ensures instrumental is padded to match vocals if countdown was added
|
||||
lyrics_metadata = job.state_data.get('lyrics_metadata', {})
|
||||
countdown_padding_seconds = None
|
||||
if lyrics_metadata.get('has_countdown_padding'):
|
||||
countdown_padding_seconds = lyrics_metadata.get('countdown_padding_seconds', 3.0)
|
||||
job_log.info(f"Countdown padding detected: {countdown_padding_seconds}s - instrumental will be padded if needed")
|
||||
|
||||
# Log finalization parameters
|
||||
job_log.info("Creating KaraokeFinalise with parameters:")
|
||||
job_log.info(f" enable_cdg: {getattr(job, 'enable_cdg', False)}")
|
||||
@@ -169,6 +177,7 @@ async def generate_video(job_id: str) -> bool:
|
||||
job_log.info(f" brand_prefix: {getattr(job, 'brand_prefix', None)}")
|
||||
job_log.info(f" discord_webhook: {'configured' if getattr(job, 'discord_webhook_url', None) else 'not configured'}")
|
||||
job_log.info(f" instrumental source: {instrumental_source}")
|
||||
job_log.info(f" countdown_padding_seconds: {countdown_padding_seconds}")
|
||||
if existing_instrumental_path:
|
||||
job_log.info(f" using user-provided instrumental (selection was: {instrumental_selection})")
|
||||
|
||||
@@ -209,6 +218,8 @@ async def generate_video(job_id: str) -> bool:
|
||||
non_interactive=True,
|
||||
server_side_mode=True,
|
||||
selected_instrumental_file=instrumental_file,
|
||||
# Audio synchronization - ensure instrumental matches vocal padding
|
||||
countdown_padding_seconds=countdown_padding_seconds,
|
||||
)
|
||||
|
||||
# Call process() - this does ALL the work:
|
||||
|
||||
@@ -771,8 +771,16 @@ class AudioProcessor:
|
||||
padded_result["other_stems"] = separation_result.get("other_stems", {})
|
||||
padded_result["backing_vocals"] = separation_result.get("backing_vocals", {})
|
||||
|
||||
self.logger.info(
|
||||
f"✓ Countdown padding applied to {len(padded_result['combined_instrumentals']) + 1} instrumental file(s)"
|
||||
)
|
||||
# Count actual padded files (don't assume clean instrumental was padded)
|
||||
padded_count = (1 if padded_result["clean_instrumental"].get("instrumental") else 0) + len(padded_result["combined_instrumentals"])
|
||||
|
||||
if padded_count > 0:
|
||||
self.logger.info(
|
||||
f"✓ Countdown padding applied to {padded_count} instrumental file(s)"
|
||||
)
|
||||
else:
|
||||
self.logger.warning(
|
||||
"No instrumental files found to pad. Check that audio separation completed successfully."
|
||||
)
|
||||
|
||||
return padded_result
|
||||
@@ -47,6 +47,7 @@ class KaraokeFinalise:
|
||||
user_youtube_credentials=None, # Add support for pre-stored credentials
|
||||
server_side_mode=False, # New parameter for server-side deployment
|
||||
selected_instrumental_file=None, # Add support for pre-selected instrumental file
|
||||
countdown_padding_seconds=None, # Padding applied to vocals; instrumental must match
|
||||
):
|
||||
self.log_level = log_level
|
||||
self.log_formatter = log_formatter
|
||||
@@ -108,6 +109,7 @@ class KaraokeFinalise:
|
||||
self.user_youtube_credentials = user_youtube_credentials
|
||||
self.server_side_mode = server_side_mode
|
||||
self.selected_instrumental_file = selected_instrumental_file
|
||||
self.countdown_padding_seconds = countdown_padding_seconds
|
||||
|
||||
self.suffixes = {
|
||||
"title_mov": " (Title).mov",
|
||||
@@ -732,6 +734,32 @@ class KaraokeFinalise:
|
||||
artist, title = base_name.split(" - ", 1)
|
||||
return base_name, artist, title
|
||||
|
||||
def _pad_audio_file(self, input_audio, output_audio, padding_seconds):
|
||||
"""
|
||||
Pad an audio file by prepending silence at the beginning.
|
||||
|
||||
Uses the same ffmpeg approach as LyricsTranscriber's CountdownProcessor
|
||||
to ensure consistent padding behavior.
|
||||
|
||||
Args:
|
||||
input_audio: Path to input audio file
|
||||
output_audio: Path for the padded output file
|
||||
padding_seconds: Amount of silence to prepend (in seconds)
|
||||
"""
|
||||
self.logger.info(f"Padding audio file with {padding_seconds}s of silence")
|
||||
|
||||
# Use ffmpeg to prepend silence - this matches the approach in audio_processor.py
|
||||
# adelay filter adds delay in milliseconds
|
||||
delay_ms = int(padding_seconds * 1000)
|
||||
|
||||
ffmpeg_command = (
|
||||
f'{self.ffmpeg_base_command} -i "{input_audio}" '
|
||||
f'-af "adelay={delay_ms}|{delay_ms}" '
|
||||
f'"{output_audio}"'
|
||||
)
|
||||
|
||||
self.execute_command(ffmpeg_command, f"Padding audio with {padding_seconds}s silence")
|
||||
|
||||
def execute_command(self, command, description):
|
||||
"""Execute a shell command and log the output. For general commands (rclone, etc.)"""
|
||||
self.logger.info(f"{description}")
|
||||
@@ -776,11 +804,32 @@ class KaraokeFinalise:
|
||||
|
||||
def remux_with_instrumental(self, with_vocals_file, instrumental_audio, output_file):
|
||||
"""Remux the video with instrumental audio to create karaoke version"""
|
||||
# Safety net: If countdown padding was applied to vocals, ensure instrumental is padded too
|
||||
actual_instrumental = instrumental_audio
|
||||
if self.countdown_padding_seconds and self.countdown_padding_seconds > 0:
|
||||
# Check if the instrumental file is already padded (has "(Padded)" in name)
|
||||
if "(Padded)" not in instrumental_audio:
|
||||
self.logger.warning(
|
||||
f"Countdown padding ({self.countdown_padding_seconds}s) was applied to vocals, "
|
||||
f"but instrumental doesn't appear to be padded. Creating padded version..."
|
||||
)
|
||||
# Create a padded version of the instrumental
|
||||
base, ext = os.path.splitext(instrumental_audio)
|
||||
padded_instrumental = f"{base} (Padded){ext}"
|
||||
|
||||
if not os.path.exists(padded_instrumental):
|
||||
self._pad_audio_file(instrumental_audio, padded_instrumental, self.countdown_padding_seconds)
|
||||
self.logger.info(f"Created padded instrumental: {padded_instrumental}")
|
||||
|
||||
actual_instrumental = padded_instrumental
|
||||
else:
|
||||
self.logger.info(f"Using already-padded instrumental: {instrumental_audio}")
|
||||
|
||||
# This operation is primarily I/O bound (remuxing), so hardware acceleration doesn't provide significant benefit
|
||||
# Keep the existing approach but use the new execute method
|
||||
ffmpeg_command = (
|
||||
f'{self.ffmpeg_base_command} -an -i "{with_vocals_file}" '
|
||||
f'-vn -i "{instrumental_audio}" -c:v copy -c:a pcm_s16le "{output_file}"'
|
||||
f'-vn -i "{actual_instrumental}" -c:v copy -c:a pcm_s16le "{output_file}"'
|
||||
)
|
||||
self.execute_command(ffmpeg_command, "Remuxing video with instrumental audio")
|
||||
|
||||
|
||||
@@ -259,6 +259,101 @@ class KaraokePrep:
|
||||
self.artist = metadata_result["artist"]
|
||||
self.title = metadata_result["title"]
|
||||
|
||||
def _scan_directory_for_instrumentals(self, track_output_dir, artist_title):
|
||||
"""
|
||||
Scan the directory for existing instrumental files and build a separated_audio structure.
|
||||
|
||||
This is used when transcription was skipped (existing files found) but we need to
|
||||
pad instrumentals due to countdown padding.
|
||||
|
||||
Args:
|
||||
track_output_dir: The track output directory to scan
|
||||
artist_title: The "{artist} - {title}" string for matching files
|
||||
|
||||
Returns:
|
||||
Dictionary with separated_audio structure containing found instrumental paths
|
||||
"""
|
||||
self.logger.info(f"Scanning directory for existing instrumentals: {track_output_dir}")
|
||||
|
||||
separated_audio = {
|
||||
"clean_instrumental": {},
|
||||
"backing_vocals": {},
|
||||
"other_stems": {},
|
||||
"combined_instrumentals": {},
|
||||
}
|
||||
|
||||
# Search patterns for instrumental files
|
||||
# Files are named like: "{artist} - {title} (Instrumental {model}).flac"
|
||||
# Or with backing vocals: "{artist} - {title} (Instrumental +BV {model}).flac"
|
||||
|
||||
# Look for files in the track output directory
|
||||
search_dir = track_output_dir
|
||||
|
||||
# Find all instrumental files (not padded ones - we want the originals)
|
||||
instrumental_pattern = os.path.join(search_dir, f"{artist_title} (Instrumental*.flac")
|
||||
instrumental_files = glob.glob(instrumental_pattern)
|
||||
|
||||
# Also check for wav files
|
||||
instrumental_pattern_wav = os.path.join(search_dir, f"{artist_title} (Instrumental*.wav")
|
||||
instrumental_files.extend(glob.glob(instrumental_pattern_wav))
|
||||
|
||||
self.logger.debug(f"Found {len(instrumental_files)} instrumental files")
|
||||
|
||||
for filepath in instrumental_files:
|
||||
filename = os.path.basename(filepath)
|
||||
|
||||
# Skip already padded files
|
||||
if "(Padded)" in filename:
|
||||
self.logger.debug(f"Skipping already padded file: {filename}")
|
||||
continue
|
||||
|
||||
# Determine if it's a combined instrumental (+BV) or clean instrumental
|
||||
if "+BV" in filename or "+bv" in filename.lower():
|
||||
# Combined instrumental with backing vocals
|
||||
# Extract model name from filename
|
||||
# Pattern: "(Instrumental +BV {model}).flac"
|
||||
model_match = re.search(r'\(Instrumental \+BV ([^)]+)\)', filename)
|
||||
if model_match:
|
||||
model_name = model_match.group(1).strip()
|
||||
separated_audio["combined_instrumentals"][model_name] = filepath
|
||||
self.logger.info(f"Found combined instrumental: {filename}")
|
||||
else:
|
||||
# Clean instrumental (no backing vocals)
|
||||
# Pattern: "(Instrumental {model}).flac"
|
||||
model_match = re.search(r'\(Instrumental ([^)]+)\)', filename)
|
||||
if model_match:
|
||||
# Use as clean instrumental if we don't have one yet
|
||||
if not separated_audio["clean_instrumental"].get("instrumental"):
|
||||
separated_audio["clean_instrumental"]["instrumental"] = filepath
|
||||
self.logger.info(f"Found clean instrumental: {filename}")
|
||||
else:
|
||||
# Additional clean instrumentals go to combined_instrumentals for padding
|
||||
model_name = model_match.group(1).strip()
|
||||
separated_audio["combined_instrumentals"][model_name] = filepath
|
||||
self.logger.info(f"Found additional instrumental: {filename}")
|
||||
|
||||
# Also look for backing vocals files
|
||||
backing_vocals_pattern = os.path.join(search_dir, f"{artist_title} (Backing Vocals*.flac")
|
||||
backing_vocals_files = glob.glob(backing_vocals_pattern)
|
||||
backing_vocals_pattern_wav = os.path.join(search_dir, f"{artist_title} (Backing Vocals*.wav")
|
||||
backing_vocals_files.extend(glob.glob(backing_vocals_pattern_wav))
|
||||
|
||||
for filepath in backing_vocals_files:
|
||||
filename = os.path.basename(filepath)
|
||||
model_match = re.search(r'\(Backing Vocals ([^)]+)\)', filename)
|
||||
if model_match:
|
||||
model_name = model_match.group(1).strip()
|
||||
if model_name not in separated_audio["backing_vocals"]:
|
||||
separated_audio["backing_vocals"][model_name] = {"backing_vocals": filepath}
|
||||
self.logger.info(f"Found backing vocals: {filename}")
|
||||
|
||||
# Log summary
|
||||
clean_count = 1 if separated_audio["clean_instrumental"].get("instrumental") else 0
|
||||
combined_count = len(separated_audio["combined_instrumentals"])
|
||||
self.logger.info(f"Directory scan complete: {clean_count} clean instrumental, {combined_count} combined instrumentals")
|
||||
|
||||
return separated_audio
|
||||
|
||||
async def prep_single_track(self):
|
||||
# Add signal handler at the start
|
||||
loop = asyncio.get_running_loop()
|
||||
@@ -767,6 +862,18 @@ class KaraokePrep:
|
||||
f"Applying {padding_seconds}s padding to all instrumental files to sync with vocal countdown"
|
||||
)
|
||||
|
||||
# If separated_audio is empty (e.g., transcription was skipped but existing files have countdown),
|
||||
# scan the directory for existing instrumental files
|
||||
has_instrumentals = (
|
||||
processed_track["separated_audio"].get("clean_instrumental", {}).get("instrumental") or
|
||||
processed_track["separated_audio"].get("combined_instrumentals")
|
||||
)
|
||||
if not has_instrumentals:
|
||||
self.logger.info("No instrumentals in separated_audio, scanning directory for existing files...")
|
||||
processed_track["separated_audio"] = self._scan_directory_for_instrumentals(
|
||||
track_output_dir, artist_title
|
||||
)
|
||||
|
||||
# Apply padding using AudioProcessor
|
||||
padded_separation_result = self.audio_processor.apply_countdown_padding_to_instrumentals(
|
||||
separation_result=processed_track["separated_audio"],
|
||||
|
||||
@@ -11,6 +11,9 @@ from .utils import sanitize_filename
|
||||
|
||||
# Placeholder class or functions for lyrics processing
|
||||
class LyricsProcessor:
|
||||
# Standard countdown padding duration used by LyricsTranscriber
|
||||
COUNTDOWN_PADDING_SECONDS = 3.0
|
||||
|
||||
def __init__(
|
||||
self, logger, style_params_json, lyrics_file, skip_transcription, skip_transcription_review, render_video, subtitle_offset_ms
|
||||
):
|
||||
@@ -22,6 +25,60 @@ class LyricsProcessor:
|
||||
self.render_video = render_video
|
||||
self.subtitle_offset_ms = subtitle_offset_ms
|
||||
|
||||
def _detect_countdown_padding_from_lrc(self, lrc_filepath):
|
||||
"""
|
||||
Detect if countdown padding was applied by checking the first lyric timestamp in the LRC file.
|
||||
|
||||
LRC format timestamps look like: [mm:ss.xx] or [mm:ss.xxx]
|
||||
If the first lyric timestamp is >= 3.0 seconds, countdown padding was likely applied.
|
||||
|
||||
Args:
|
||||
lrc_filepath: Path to the LRC file
|
||||
|
||||
Returns:
|
||||
Tuple of (countdown_padding_added: bool, countdown_padding_seconds: float)
|
||||
"""
|
||||
try:
|
||||
with open(lrc_filepath, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
|
||||
# Find all timestamp patterns in the LRC file
|
||||
# LRC timestamps: [mm:ss.xx] or [mm:ss.xxx]
|
||||
timestamp_pattern = r'\[(\d{1,2}):(\d{2})\.(\d{2,3})\]'
|
||||
matches = re.findall(timestamp_pattern, content)
|
||||
|
||||
if not matches:
|
||||
self.logger.debug("No timestamps found in LRC file")
|
||||
return (False, 0.0)
|
||||
|
||||
# Find the first non-metadata timestamp (metadata like [ar:Artist] doesn't have decimal)
|
||||
# We already filtered for decimal timestamps in our pattern
|
||||
first_timestamp = matches[0]
|
||||
minutes = int(first_timestamp[0])
|
||||
seconds = int(first_timestamp[1])
|
||||
# Handle both .xx and .xxx formats
|
||||
centiseconds = first_timestamp[2]
|
||||
if len(centiseconds) == 2:
|
||||
milliseconds = int(centiseconds) * 10
|
||||
else:
|
||||
milliseconds = int(centiseconds)
|
||||
|
||||
first_lyric_time = minutes * 60 + seconds + milliseconds / 1000.0
|
||||
|
||||
self.logger.debug(f"First lyric timestamp in LRC: {first_lyric_time:.3f}s")
|
||||
|
||||
# If first lyric is at or after 3 seconds, countdown padding was applied
|
||||
# Use a small buffer (2.5s) to account for songs that naturally start a bit late
|
||||
if first_lyric_time >= 2.5:
|
||||
self.logger.info(f"Detected countdown padding from LRC: first lyric at {first_lyric_time:.2f}s")
|
||||
return (True, self.COUNTDOWN_PADDING_SECONDS)
|
||||
|
||||
return (False, 0.0)
|
||||
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to detect countdown padding from LRC file: {e}")
|
||||
return (False, 0.0)
|
||||
|
||||
def find_best_split_point(self, line):
|
||||
"""
|
||||
Find the best split point in a line based on the specified criteria.
|
||||
@@ -138,23 +195,43 @@ class LyricsProcessor:
|
||||
lyrics_video_path = os.path.join(lyrics_dir, f"{sanitized_artist} - {sanitized_title} (With Vocals).mkv")
|
||||
lyrics_lrc_path = os.path.join(lyrics_dir, f"{sanitized_artist} - {sanitized_title} (Karaoke).lrc")
|
||||
|
||||
# If files exist in parent directory, return early
|
||||
# If files exist in parent directory, return early (but detect countdown padding first)
|
||||
if os.path.exists(parent_video_path) and os.path.exists(parent_lrc_path):
|
||||
self.logger.info(f"Found existing video and LRC files in parent directory, skipping transcription")
|
||||
self.logger.info("Found existing video and LRC files in parent directory, skipping transcription")
|
||||
|
||||
# Detect countdown padding from existing LRC file
|
||||
countdown_padding_added, countdown_padding_seconds = self._detect_countdown_padding_from_lrc(parent_lrc_path)
|
||||
|
||||
if countdown_padding_added:
|
||||
self.logger.info(f"Existing files have countdown padding: {countdown_padding_seconds}s")
|
||||
|
||||
return {
|
||||
"lrc_filepath": parent_lrc_path,
|
||||
"ass_filepath": parent_video_path,
|
||||
"countdown_padding_added": countdown_padding_added,
|
||||
"countdown_padding_seconds": countdown_padding_seconds,
|
||||
"padded_audio_filepath": None, # Original padded audio may not exist
|
||||
}
|
||||
|
||||
# If files exist in lyrics directory, copy to parent and return
|
||||
# If files exist in lyrics directory, copy to parent and return (but detect countdown padding first)
|
||||
if os.path.exists(lyrics_video_path) and os.path.exists(lyrics_lrc_path):
|
||||
self.logger.info(f"Found existing video and LRC files in lyrics directory, copying to parent")
|
||||
self.logger.info("Found existing video and LRC files in lyrics directory, copying to parent")
|
||||
os.makedirs(track_output_dir, exist_ok=True)
|
||||
shutil.copy2(lyrics_video_path, parent_video_path)
|
||||
shutil.copy2(lyrics_lrc_path, parent_lrc_path)
|
||||
|
||||
# Detect countdown padding from existing LRC file
|
||||
countdown_padding_added, countdown_padding_seconds = self._detect_countdown_padding_from_lrc(parent_lrc_path)
|
||||
|
||||
if countdown_padding_added:
|
||||
self.logger.info(f"Existing files have countdown padding: {countdown_padding_seconds}s")
|
||||
|
||||
return {
|
||||
"lrc_filepath": parent_lrc_path,
|
||||
"ass_filepath": parent_video_path,
|
||||
"countdown_padding_added": countdown_padding_added,
|
||||
"countdown_padding_seconds": countdown_padding_seconds,
|
||||
"padded_audio_filepath": None, # Original padded audio may not exist
|
||||
}
|
||||
|
||||
# Create lyrics directory if it doesn't exist
|
||||
|
||||
@@ -820,6 +820,12 @@ async def async_main():
|
||||
|
||||
logger.info(f"Selected instrumental file: {selected_instrumental_file}")
|
||||
|
||||
# Get countdown padding info from track (if vocals were padded, instrumental must match)
|
||||
countdown_padding_seconds = None
|
||||
if track.get("countdown_padding_added", False):
|
||||
countdown_padding_seconds = track.get("countdown_padding_seconds", 3.0)
|
||||
logger.info(f"Countdown padding detected: {countdown_padding_seconds}s (will be applied to instrumental if needed)")
|
||||
|
||||
# Load CDG styles if CDG generation is enabled
|
||||
cdg_styles = None
|
||||
if args.enable_cdg:
|
||||
@@ -864,6 +870,7 @@ async def async_main():
|
||||
keep_brand_code=getattr(args, 'keep_brand_code', False),
|
||||
non_interactive=args.yes,
|
||||
selected_instrumental_file=selected_instrumental_file,
|
||||
countdown_padding_seconds=countdown_padding_seconds,
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.71.69"
|
||||
version = "0.72.0"
|
||||
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"
|
||||
|
||||
@@ -435,6 +435,266 @@ class TestExistingInstrumentalPadding:
|
||||
assert '3.0' in call_args or 3.0 in call_args
|
||||
|
||||
|
||||
class TestDetectCountdownPaddingFromLRC:
|
||||
"""Tests for detecting countdown padding from existing LRC files."""
|
||||
|
||||
def test_detect_padding_from_lrc_with_padding(self, basic_karaoke_gen, temp_dir):
|
||||
"""Test that countdown padding is detected when first lyric is after 3 seconds."""
|
||||
lrc_file = os.path.join(temp_dir, 'test.lrc')
|
||||
|
||||
# Create an LRC file with first lyric at 3 seconds (padding was applied)
|
||||
lrc_content = """[ti:Test Song]
|
||||
[ar:Test Artist]
|
||||
[00:03.50]First line of lyrics
|
||||
[00:06.20]Second line of lyrics
|
||||
[00:10.00]Third line of lyrics
|
||||
"""
|
||||
with open(lrc_file, 'w') as f:
|
||||
f.write(lrc_content)
|
||||
|
||||
padding_added, padding_seconds = basic_karaoke_gen.lyrics_processor._detect_countdown_padding_from_lrc(lrc_file)
|
||||
|
||||
assert padding_added is True
|
||||
assert padding_seconds == 3.0
|
||||
|
||||
def test_detect_padding_from_lrc_without_padding(self, basic_karaoke_gen, temp_dir):
|
||||
"""Test that no padding is detected when first lyric is before 3 seconds."""
|
||||
lrc_file = os.path.join(temp_dir, 'test.lrc')
|
||||
|
||||
# Create an LRC file with first lyric at 0.5 seconds (no padding)
|
||||
lrc_content = """[ti:Test Song]
|
||||
[ar:Test Artist]
|
||||
[00:00.50]First line of lyrics
|
||||
[00:03.20]Second line of lyrics
|
||||
[00:06.00]Third line of lyrics
|
||||
"""
|
||||
with open(lrc_file, 'w') as f:
|
||||
f.write(lrc_content)
|
||||
|
||||
padding_added, padding_seconds = basic_karaoke_gen.lyrics_processor._detect_countdown_padding_from_lrc(lrc_file)
|
||||
|
||||
assert padding_added is False
|
||||
assert padding_seconds == 0.0
|
||||
|
||||
def test_detect_padding_from_lrc_edge_case(self, basic_karaoke_gen, temp_dir):
|
||||
"""Test detection at the 2.5 second boundary."""
|
||||
lrc_file = os.path.join(temp_dir, 'test.lrc')
|
||||
|
||||
# Create an LRC file with first lyric at exactly 2.5 seconds (boundary)
|
||||
lrc_content = """[00:02.50]First line at boundary
|
||||
[00:05.00]Second line
|
||||
"""
|
||||
with open(lrc_file, 'w') as f:
|
||||
f.write(lrc_content)
|
||||
|
||||
padding_added, padding_seconds = basic_karaoke_gen.lyrics_processor._detect_countdown_padding_from_lrc(lrc_file)
|
||||
|
||||
# 2.5 is the boundary - should be detected as padding
|
||||
assert padding_added is True
|
||||
assert padding_seconds == 3.0
|
||||
|
||||
def test_detect_padding_from_lrc_just_below_boundary(self, basic_karaoke_gen, temp_dir):
|
||||
"""Test detection just below the 2.5 second boundary."""
|
||||
lrc_file = os.path.join(temp_dir, 'test.lrc')
|
||||
|
||||
# Create an LRC file with first lyric at 2.4 seconds (just below boundary)
|
||||
lrc_content = """[00:02.40]First line just below boundary
|
||||
[00:05.00]Second line
|
||||
"""
|
||||
with open(lrc_file, 'w') as f:
|
||||
f.write(lrc_content)
|
||||
|
||||
padding_added, padding_seconds = basic_karaoke_gen.lyrics_processor._detect_countdown_padding_from_lrc(lrc_file)
|
||||
|
||||
# 2.4 is below boundary - should NOT be detected as padding
|
||||
assert padding_added is False
|
||||
assert padding_seconds == 0.0
|
||||
|
||||
def test_detect_padding_from_lrc_empty_file(self, basic_karaoke_gen, temp_dir):
|
||||
"""Test handling of empty LRC file."""
|
||||
lrc_file = os.path.join(temp_dir, 'test.lrc')
|
||||
|
||||
with open(lrc_file, 'w') as f:
|
||||
f.write('')
|
||||
|
||||
padding_added, padding_seconds = basic_karaoke_gen.lyrics_processor._detect_countdown_padding_from_lrc(lrc_file)
|
||||
|
||||
assert padding_added is False
|
||||
assert padding_seconds == 0.0
|
||||
|
||||
def test_detect_padding_from_lrc_no_timestamps(self, basic_karaoke_gen, temp_dir):
|
||||
"""Test handling of LRC file with no valid timestamps."""
|
||||
lrc_file = os.path.join(temp_dir, 'test.lrc')
|
||||
|
||||
lrc_content = """[ti:Test Song]
|
||||
[ar:Test Artist]
|
||||
Just text without timestamps
|
||||
More text
|
||||
"""
|
||||
with open(lrc_file, 'w') as f:
|
||||
f.write(lrc_content)
|
||||
|
||||
padding_added, padding_seconds = basic_karaoke_gen.lyrics_processor._detect_countdown_padding_from_lrc(lrc_file)
|
||||
|
||||
assert padding_added is False
|
||||
assert padding_seconds == 0.0
|
||||
|
||||
def test_detect_padding_from_lrc_missing_file(self, basic_karaoke_gen, temp_dir):
|
||||
"""Test handling of missing LRC file."""
|
||||
lrc_file = os.path.join(temp_dir, 'nonexistent.lrc')
|
||||
|
||||
padding_added, padding_seconds = basic_karaoke_gen.lyrics_processor._detect_countdown_padding_from_lrc(lrc_file)
|
||||
|
||||
assert padding_added is False
|
||||
assert padding_seconds == 0.0
|
||||
|
||||
def test_detect_padding_from_lrc_three_digit_milliseconds(self, basic_karaoke_gen, temp_dir):
|
||||
"""Test parsing LRC files with three-digit milliseconds."""
|
||||
lrc_file = os.path.join(temp_dir, 'test.lrc')
|
||||
|
||||
# Some LRC files use [mm:ss.xxx] format
|
||||
lrc_content = """[00:03.500]First line at 3.5 seconds
|
||||
[00:06.200]Second line
|
||||
"""
|
||||
with open(lrc_file, 'w') as f:
|
||||
f.write(lrc_content)
|
||||
|
||||
padding_added, padding_seconds = basic_karaoke_gen.lyrics_processor._detect_countdown_padding_from_lrc(lrc_file)
|
||||
|
||||
assert padding_added is True
|
||||
assert padding_seconds == 3.0
|
||||
|
||||
|
||||
class TestExistingFilesWithPaddingDetection:
|
||||
"""Tests for transcribe_lyrics returning padding info from existing files."""
|
||||
|
||||
def test_transcribe_lyrics_existing_files_returns_padding_info(self, basic_karaoke_gen, temp_dir):
|
||||
"""Test that transcribe_lyrics returns padding info when using existing files."""
|
||||
track_output_dir = temp_dir
|
||||
artist = "Test Artist"
|
||||
title = "Test Title"
|
||||
|
||||
# Create existing files
|
||||
video_path = os.path.join(track_output_dir, f"{artist} - {title} (With Vocals).mkv")
|
||||
lrc_path = os.path.join(track_output_dir, f"{artist} - {title} (Karaoke).lrc")
|
||||
|
||||
# Create the video file
|
||||
with open(video_path, 'w') as f:
|
||||
f.write('mock video')
|
||||
|
||||
# Create LRC file with countdown padding (first lyric at 3.5s)
|
||||
lrc_content = """[00:03.50]First line with padding
|
||||
[00:06.00]Second line
|
||||
"""
|
||||
with open(lrc_path, 'w') as f:
|
||||
f.write(lrc_content)
|
||||
|
||||
# Call transcribe_lyrics - it should detect existing files and return padding info
|
||||
result = basic_karaoke_gen.lyrics_processor.transcribe_lyrics(
|
||||
input_audio_wav=None, # Not needed when existing files found
|
||||
artist=artist,
|
||||
title=title,
|
||||
track_output_dir=track_output_dir,
|
||||
)
|
||||
|
||||
# Should return padding info from LRC detection
|
||||
assert result['countdown_padding_added'] is True
|
||||
assert result['countdown_padding_seconds'] == 3.0
|
||||
assert result['padded_audio_filepath'] is None # Original padded audio not available
|
||||
|
||||
def test_transcribe_lyrics_existing_files_no_padding(self, basic_karaoke_gen, temp_dir):
|
||||
"""Test existing files case when there's no countdown padding."""
|
||||
track_output_dir = temp_dir
|
||||
artist = "Test Artist"
|
||||
title = "Test Title"
|
||||
|
||||
# Create existing files
|
||||
video_path = os.path.join(track_output_dir, f"{artist} - {title} (With Vocals).mkv")
|
||||
lrc_path = os.path.join(track_output_dir, f"{artist} - {title} (Karaoke).lrc")
|
||||
|
||||
# Create the video file
|
||||
with open(video_path, 'w') as f:
|
||||
f.write('mock video')
|
||||
|
||||
# Create LRC file WITHOUT countdown padding (first lyric at 0.5s)
|
||||
lrc_content = """[00:00.50]First line starts immediately
|
||||
[00:03.00]Second line
|
||||
"""
|
||||
with open(lrc_path, 'w') as f:
|
||||
f.write(lrc_content)
|
||||
|
||||
result = basic_karaoke_gen.lyrics_processor.transcribe_lyrics(
|
||||
input_audio_wav=None,
|
||||
artist=artist,
|
||||
title=title,
|
||||
track_output_dir=track_output_dir,
|
||||
)
|
||||
|
||||
# Should return no padding info
|
||||
assert result['countdown_padding_added'] is False
|
||||
assert result['countdown_padding_seconds'] == 0.0
|
||||
|
||||
|
||||
class TestScanDirectoryForInstrumentals:
|
||||
"""Tests for scanning directory for existing instrumentals."""
|
||||
|
||||
def test_scan_directory_finds_clean_instrumental(self, basic_karaoke_gen, temp_dir):
|
||||
"""Test that _scan_directory_for_instrumentals finds clean instrumentals."""
|
||||
artist_title = "Test Artist - Test Song"
|
||||
|
||||
# Create a clean instrumental file
|
||||
instrumental_file = os.path.join(temp_dir, f"{artist_title} (Instrumental Clean).flac")
|
||||
with open(instrumental_file, 'w') as f:
|
||||
f.write('mock instrumental')
|
||||
|
||||
result = basic_karaoke_gen._scan_directory_for_instrumentals(temp_dir, artist_title)
|
||||
|
||||
assert result['clean_instrumental']['instrumental'] == instrumental_file
|
||||
|
||||
def test_scan_directory_finds_combined_instrumentals(self, basic_karaoke_gen, temp_dir):
|
||||
"""Test that _scan_directory_for_instrumentals finds combined instrumentals."""
|
||||
artist_title = "Test Artist - Test Song"
|
||||
|
||||
# Create combined instrumental files
|
||||
bv_file = os.path.join(temp_dir, f"{artist_title} (Instrumental +BV HTDemucs).flac")
|
||||
with open(bv_file, 'w') as f:
|
||||
f.write('mock instrumental with backing')
|
||||
|
||||
result = basic_karaoke_gen._scan_directory_for_instrumentals(temp_dir, artist_title)
|
||||
|
||||
assert 'HTDemucs' in result['combined_instrumentals']
|
||||
assert result['combined_instrumentals']['HTDemucs'] == bv_file
|
||||
|
||||
def test_scan_directory_skips_padded_files(self, basic_karaoke_gen, temp_dir):
|
||||
"""Test that _scan_directory_for_instrumentals skips already-padded files."""
|
||||
artist_title = "Test Artist - Test Song"
|
||||
|
||||
# Create both original and padded files
|
||||
original_file = os.path.join(temp_dir, f"{artist_title} (Instrumental Clean).flac")
|
||||
padded_file = os.path.join(temp_dir, f"{artist_title} (Instrumental Clean) (Padded).flac")
|
||||
|
||||
with open(original_file, 'w') as f:
|
||||
f.write('mock original')
|
||||
with open(padded_file, 'w') as f:
|
||||
f.write('mock padded')
|
||||
|
||||
result = basic_karaoke_gen._scan_directory_for_instrumentals(temp_dir, artist_title)
|
||||
|
||||
# Should return original, not padded
|
||||
assert result['clean_instrumental']['instrumental'] == original_file
|
||||
assert 'Padded' not in result['clean_instrumental']['instrumental']
|
||||
|
||||
def test_scan_directory_empty_directory(self, basic_karaoke_gen, temp_dir):
|
||||
"""Test _scan_directory_for_instrumentals on empty directory."""
|
||||
artist_title = "Test Artist - Test Song"
|
||||
|
||||
result = basic_karaoke_gen._scan_directory_for_instrumentals(temp_dir, artist_title)
|
||||
|
||||
# Should return empty structure
|
||||
assert result['clean_instrumental'].get('instrumental') is None
|
||||
assert len(result['combined_instrumentals']) == 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
pytest.main([__file__, '-v'])
|
||||
|
||||
Reference in new issue
Block a user