Compare commits

...
Author SHA1 Message Date
Andrew Beveridge e507b3f685 fix: prevent duplicate log messages from external package side effects
External packages like lyrics_converter call logging.info() directly on the
root logger, which triggers Python's 'last resort' handler. This causes log
messages to appear twice: once from our custom handler and once from the
root logger's default handler.

Fixed by setting logger.propagate = False on all loggers that have their
own handlers configured. This prevents logs from propagating to the root
logger while still displaying through our custom formatted handlers.

Affected files:
- karaoke_gen/karaoke_finalise/karaoke_finalise.py
- karaoke_gen/karaoke_gen.py
- karaoke_gen/utils/gen_cli.py
- karaoke_gen/utils/remote_cli.py
- karaoke_gen/utils/bulk_cli.py

Also updated tests to use capsys instead of caplog since caplog relies
on log propagation to capture messages.

Bumps version to 0.71.47
2025-12-17 23:17:29 -05:00
Andrew Beveridge 6d0c765f4d test: add integration tests for run_instrumental_review parameter contract
Added tests that verify:
- WaveformGenerator.generate() is called with 'segments' (not 'audible_segments')
- Correct parameter values are passed between components
- Error handling and edge cases

These tests would have caught the parameter name bug that broke
the instrumental review flow. They exercise the actual function
with properly mocked components instead of mocking the entire function.

Bumps version to 0.71.46
2025-12-17 23:04:51 -05:00
Andrew Beveridge 8086242d38 fix: correct parameter name in WaveformGenerator.generate() call
The WaveformGenerator.generate() method expects 'segments' parameter,
not 'audible_segments'. This caused the instrumental review to fail
with 'unexpected keyword argument' error during karaoke-gen CLI execution.

Bumps version to 0.71.45
2025-12-17 22:56:59 -05:00
Andrew Beveridge ☄️ 3c3680632b Merge pull request #25 from nomadkaraoke/fix/instrumental-selection-single-path
Remove legacy instrumental selection fallback, fix path resolution
2025-12-17 22:23:46 -05:00
Andrew Beveridge dd5f05b291 fix: update integration test to use --skip_instrumental_review
The integration test was failing because it didn't provide the
separated_audio data structure expected by run_instrumental_review.
Since the test uses mocked audio data, it makes sense to use the
--skip_instrumental_review flag with auto_select_instrumental instead.

- Added --skip_instrumental_review to test CLI args
- Updated mock_process_audio_separation to return clean_instrumental
  data structure needed by auto_select_instrumental
- Bumped version to 0.71.44
2025-12-14 13:30:47 -05:00
Andrew Beveridge 9340ed5d9f Remove legacy instrumental selection fallback, fix path resolution
This change eliminates the silent fallback to the legacy numbered instrumental
selection in KaraokeFinalise and ensures a single code path for instrumental
selection:

1. **Path resolution fix**: Added `_resolve_path_for_cwd()` helper to correctly
   resolve paths in `separated_audio` after `os.chdir(track_dir)`. The paths
   were stored relative to the original directory, causing `os.path.exists()`
   to fail after the directory change.

2. **No silent fallback**: When `run_instrumental_review()` fails, the CLI now
   exits with a clear error message explaining what went wrong and how to fix
   it, rather than silently falling back to the legacy numbered selection.

3. **Auto-select for non-interactive mode**: Added `auto_select_instrumental()`
   function for `--skip_instrumental_review` mode that intelligently selects
   the best instrumental (preferring padded+combined > padded > combined > clean).

4. **Clear error messages**: When instrumental selection fails, users now get
   detailed diagnostics about what to check and how to recover.

The legacy `choose_instrumental_audio_file()` method in KaraokeFinalise is
preserved for direct usage but is no longer called from the gen_cli flow.

Includes comprehensive tests for the new helper functions.

Bump version to 0.71.43.
2025-12-14 13:10:29 -05:00
9 changed files with 776 additions and 32 deletions

No files matched your search

@@ -54,6 +54,9 @@ class KaraokeFinalise:
if logger is None:
self.logger = logging.getLogger(__name__)
self.logger.setLevel(log_level)
# Prevent log propagation to root logger to avoid duplicate logs
# when external packages (like lyrics_converter) configure root logger handlers
self.logger.propagate = False
self.log_handler = logging.StreamHandler()
+3
View File
@@ -84,6 +84,9 @@ class KaraokePrep:
if logger is None:
self.logger = logging.getLogger(__name__)
self.logger.setLevel(log_level)
# Prevent log propagation to root logger to avoid duplicate logs
# when external packages (like lyrics_converter) configure root logger handlers
self.logger.propagate = False
self.log_handler = logging.StreamHandler()
+3
View File
@@ -19,6 +19,9 @@ from karaoke_gen.karaoke_finalise import KaraokeFinalise
# Global logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO) # Set initial log level
# Prevent log propagation to root logger to avoid duplicate logs
# when external packages (like lyrics_converter) configure root logger handlers
logger.propagate = False
async def process_track_prep(row, args, logger, log_formatter):
+136 -3
View File
@@ -59,6 +59,89 @@ def _resolve_path_for_cwd(path: str, track_dir: str) -> str:
return path
def auto_select_instrumental(track: dict, track_dir: str, logger: logging.Logger) -> str:
"""
Auto-select the best instrumental file when --skip_instrumental_review is used.
Selection priority:
1. Padded combined instrumental (+BV) - synchronized with vocals + backing vocals
2. Non-padded combined instrumental (+BV) - has backing vocals
3. Padded clean instrumental - synchronized with vocals
4. Non-padded clean instrumental - basic instrumental
Args:
track: The track dictionary from KaraokePrep containing separated audio info
track_dir: The track output directory (we're already chdir'd into it)
logger: Logger instance
Returns:
Path to the selected instrumental file
Raises:
FileNotFoundError: If no suitable instrumental file can be found
"""
separated = track.get("separated_audio", {})
# Look for combined instrumentals first (they include backing vocals)
combined = separated.get("combined_instrumentals", {})
for model, path in combined.items():
if path:
resolved = _resolve_path_for_cwd(path, track_dir)
# Prefer padded version if it exists
base, ext = os.path.splitext(resolved)
padded = f"{base} (Padded){ext}"
if os.path.exists(padded):
logger.info(f"Auto-selected padded combined instrumental: {padded}")
return padded
if os.path.exists(resolved):
logger.info(f"Auto-selected combined instrumental: {resolved}")
return resolved
# Fall back to clean instrumental
clean = separated.get("clean_instrumental", {})
if clean.get("instrumental"):
resolved = _resolve_path_for_cwd(clean["instrumental"], track_dir)
# Prefer padded version if it exists
base, ext = os.path.splitext(resolved)
padded = f"{base} (Padded){ext}"
if os.path.exists(padded):
logger.info(f"Auto-selected padded clean instrumental: {padded}")
return padded
if os.path.exists(resolved):
logger.info(f"Auto-selected clean instrumental: {resolved}")
return resolved
# If separated_audio doesn't have what we need, search the directory
# This handles edge cases and custom instrumentals
logger.info("No instrumental found in separated_audio, searching directory...")
instrumental_files = glob.glob("*(Instrumental*.flac") + glob.glob("*(Instrumental*.wav")
# Sort to prefer padded versions and combined instrumentals
padded_combined = [f for f in instrumental_files if "(Padded)" in f and "+BV" in f]
if padded_combined:
logger.info(f"Auto-selected from directory: {padded_combined[0]}")
return padded_combined[0]
padded_files = [f for f in instrumental_files if "(Padded)" in f]
if padded_files:
logger.info(f"Auto-selected from directory: {padded_files[0]}")
return padded_files[0]
combined_files = [f for f in instrumental_files if "+BV" in f]
if combined_files:
logger.info(f"Auto-selected from directory: {combined_files[0]}")
return combined_files[0]
if instrumental_files:
logger.info(f"Auto-selected from directory: {instrumental_files[0]}")
return instrumental_files[0]
raise FileNotFoundError(
"No instrumental file found. Audio separation may have failed. "
"Check the stems/ directory for separated audio files."
)
def run_instrumental_review(track: dict, logger: logging.Logger) -> str | None:
"""
Run the instrumental review UI to let user select the best instrumental track.
@@ -138,7 +221,7 @@ def run_instrumental_review(track: dict, logger: logging.Logger) -> str | None:
waveform_generator.generate(
audio_path=backing_vocals_path,
output_path=waveform_path,
audible_segments=analysis.audible_segments,
segments=analysis.audible_segments,
)
# Start the review server
@@ -199,6 +282,9 @@ def run_instrumental_review(track: dict, logger: logging.Logger) -> str | None:
async def async_main():
logger = logging.getLogger(__name__)
# Prevent log propagation to root logger to avoid duplicate logs
# when external packages (like lyrics_converter) configure root logger handlers
logger.propagate = False
log_handler = logging.StreamHandler()
log_formatter = logging.Formatter(fmt="%(asctime)s.%(msecs)03d - %(levelname)s - %(module)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log_handler.setFormatter(log_formatter)
@@ -638,13 +724,60 @@ async def async_main():
logger.info(f"Changing to directory: {track_dir}")
os.chdir(track_dir)
# Run instrumental review UI if not skipped
# Select instrumental file - either via web UI or auto-selection
# This ALWAYS produces a selected file - no silent fallback to legacy code
selected_instrumental_file = None
if not getattr(args, 'skip_instrumental_review', False):
skip_review = getattr(args, 'skip_instrumental_review', False)
if skip_review:
# Auto-select instrumental when review is skipped (non-interactive mode)
logger.info("Instrumental review skipped (--skip_instrumental_review), auto-selecting instrumental file...")
try:
selected_instrumental_file = auto_select_instrumental(
track=track,
track_dir=track_dir,
logger=logger,
)
except FileNotFoundError as e:
logger.error(f"Failed to auto-select instrumental: {e}")
logger.error("Check that audio separation completed successfully.")
sys.exit(1)
return # Explicit return for testing
else:
# Run instrumental review web UI
selected_instrumental_file = run_instrumental_review(
track=track,
logger=logger,
)
# If instrumental review failed/returned None, show error and exit
# NO SILENT FALLBACK - we want to know if the new flow has issues
if selected_instrumental_file is None:
logger.error("")
logger.error("=" * 70)
logger.error("INSTRUMENTAL SELECTION FAILED")
logger.error("=" * 70)
logger.error("")
logger.error("The instrumental review UI could not find the required files.")
logger.error("")
logger.error("Common causes:")
logger.error(" - No backing vocals file was found (check stems/ directory)")
logger.error(" - No clean instrumental was found (audio separation may have failed)")
logger.error(" - Path resolution failed after directory change")
logger.error("")
logger.error("To investigate:")
logger.error(" - Check the stems/ directory for: *Backing Vocals*.flac and *Instrumental*.flac")
logger.error(" - Look for separation errors earlier in the log")
logger.error(" - Verify audio separation completed without errors")
logger.error("")
logger.error("Workarounds:")
logger.error(" - Re-run with --skip_instrumental_review to auto-select an instrumental")
logger.error(" - Re-run the full pipeline to regenerate stems")
logger.error("")
sys.exit(1)
return # Explicit return for testing
logger.info(f"Selected instrumental file: {selected_instrumental_file}")
# Load CDG styles if CDG generation is enabled
cdg_styles = None
+3
View File
@@ -1879,6 +1879,9 @@ def main():
"""Main entry point for the remote CLI."""
# Set up logging - same format as gen_cli.py
logger = logging.getLogger(__name__)
# Prevent log propagation to root logger to avoid duplicate logs
# when external packages (like lyrics_converter) configure root logger handlers
logger.propagate = False
log_handler = logging.StreamHandler()
log_formatter = logging.Formatter(
fmt="%(asctime)s.%(msecs)03d - %(levelname)s - %(module)s - %(message)s",
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.71.42"
version = "0.71.47"
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"
+9 -2
View File
@@ -759,14 +759,20 @@ async def test_full_cli_integration(tmp_path, mocker):
print(f"MOCK process_audio_separation: Creating dummy separated files for {artist_title}")
# Create dummy instrumental files (using a generic model name)
instrumental_file = os.path.join(track_output_dir, f"{artist_title} (Instrumental model_bs_roformer_ep_317_sdr_12.9755.ckpt).flac")
model_name = "model_bs_roformer_ep_317_sdr_12.9755.ckpt"
instrumental_file = os.path.join(track_output_dir, f"{artist_title} (Instrumental {model_name}).flac")
with open(instrumental_file, "w") as f:
f.write("dummy instrumental audio content")
# Return data in the format expected by auto_select_instrumental
return {
"instrumental_path": instrumental_file,
"vocals_path": None, # Not needed for this test
# clean_instrumental is what auto_select_instrumental looks for
"clean_instrumental": {
"instrumental": instrumental_file
},
}
mocker.patch('karaoke_gen.audio_processor.AudioProcessor.process_audio_separation',
@@ -1093,7 +1099,8 @@ async def test_full_cli_integration(tmp_path, mocker):
'--enable_cdg', # Named: enable CDG creation
'--enable_txt', # Named: enable TXT creation
'-y', # Named: auto-confirm (bypass user confirmation)
'--log_level', 'DEBUG' # Named: log level
'--log_level', 'DEBUG', # Named: log level
'--skip_instrumental_review', # Named: skip instrumental review UI (use auto-select)
]
# Now run the actual karaoke generation pipeline
+177 -26
View File
@@ -130,7 +130,7 @@ def mock_sleep():
@patch("karaoke_gen.utils.gen_cli.is_url", return_value=True)
@patch("karaoke_gen.utils.gen_cli.is_file", return_value=False)
@patch("karaoke_gen.utils.gen_cli.KaraokePrep") # Use default MagicMock for class
async def test_arg_parsing_url_only(mock_kprep_class, mock_isfile, mock_isurl, mock_base_args, mock_logger, caplog):
async def test_arg_parsing_url_only(mock_kprep_class, mock_isfile, mock_isurl, mock_base_args, mock_logger, capsys):
"""Test URL-only argument parsing."""
mock_base_args.args = ["https://example.com/song.mp3"]
mock_kprep_instance = MagicMock()
@@ -145,8 +145,9 @@ async def test_arg_parsing_url_only(mock_kprep_class, mock_isfile, mock_isurl, m
# Verify that input_media=URL is passed
assert mock_kprep_class.call_args.kwargs["input_media"] == "https://example.com/song.mp3"
mock_kprep_instance.process.assert_awaited_once()
# Verify warning in log
assert "Input media provided without Artist and Title" in caplog.text
# Verify warning in log (captured in stderr since logger.propagate = False)
captured = capsys.readouterr()
assert "Input media provided without Artist and Title" in captured.err
@patch("karaoke_gen.utils.gen_cli.is_url", return_value=True)
@patch("karaoke_gen.utils.gen_cli.is_file", return_value=False)
@@ -194,7 +195,7 @@ async def test_arg_parsing_file_artist_title(mock_kprep_class, mock_isfile, mock
@patch("karaoke_gen.utils.gen_cli.is_file", return_value=False)
@patch("karaoke_gen.utils.gen_cli.os.path.isdir", return_value=False)
@patch("karaoke_gen.utils.gen_cli.KaraokePrep") # Use default MagicMock for class
async def test_arg_parsing_artist_title_only(mock_kprep_class, mock_isdir, mock_isfile, mock_isurl, mock_base_args, mock_logger, caplog):
async def test_arg_parsing_artist_title_only(mock_kprep_class, mock_isdir, mock_isfile, mock_isurl, mock_base_args, mock_logger, capsys):
"""Test Artist and Title only argument parsing."""
mock_base_args.args = ["Test Artist", "Test Title"]
mock_kprep_instance = MagicMock()
@@ -211,8 +212,9 @@ async def test_arg_parsing_artist_title_only(mock_kprep_class, mock_isdir, mock_
assert mock_kprep_class.call_args.kwargs["title"] == "Test Title"
assert mock_kprep_class.call_args.kwargs["input_media"] is None
mock_kprep_instance.process.assert_awaited_once()
# Verify message about flacfetch search is shown
assert "flacfetch will search for" in caplog.text
# Verify message about flacfetch search is shown (in stderr since logger.propagate = False)
captured = capsys.readouterr()
assert "flacfetch will search for" in captured.err
@patch("karaoke_gen.utils.gen_cli.is_url", return_value=False)
@patch("karaoke_gen.utils.gen_cli.is_file", return_value=False)
@@ -281,7 +283,8 @@ async def test_workflow_prep_only(mock_kfinalise, mock_kprep_class, mock_base_ar
@patch("karaoke_gen.utils.gen_cli.KaraokePrep") # Should not be called
@patch("karaoke_gen.utils.gen_cli.KaraokeFinalise")
@patch("builtins.open", new_callable=mock_open) # Mock open for style JSON if CDG enabled
async def test_workflow_finalise_only(mock_open, mock_kfinalise, mock_kprep, mock_base_args, mock_logger):
@patch("karaoke_gen.utils.gen_cli.run_instrumental_review", return_value="selected_instrumental.flac")
async def test_workflow_finalise_only(mock_run_review, mock_open, mock_kfinalise, mock_kprep, mock_base_args, mock_logger):
"""Test --finalise-only workflow."""
mock_base_args.finalise_only = True
mock_kfinalise_instance = mock_kfinalise.return_value
@@ -304,7 +307,8 @@ async def test_workflow_finalise_only(mock_open, mock_kfinalise, mock_kprep, moc
@patch("karaoke_gen.utils.gen_cli.os.path.basename", return_value="Edit Artist - Edit Title")
@patch("karaoke_gen.utils.gen_cli.os.getcwd", return_value="/fake/path/Edit Artist - Edit Title")
@patch("builtins.open", new_callable=mock_open) # Mock open for style JSON if CDG enabled
async def test_workflow_edit_lyrics(mock_open, mock_getcwd, mock_basename, mock_kfinalise, mock_kprep_class, mock_base_args, mock_logger):
@patch("karaoke_gen.utils.gen_cli.run_instrumental_review", return_value="selected_instrumental.flac")
async def test_workflow_edit_lyrics(mock_run_review, mock_open, mock_getcwd, mock_basename, mock_kfinalise, mock_kprep_class, mock_base_args, mock_logger):
"""Test --edit-lyrics workflow."""
mock_base_args.edit_lyrics = True
mock_base_args.enable_cdg = False # Simplify for now
@@ -370,7 +374,8 @@ async def test_workflow_test_email_template(mock_kfinalise, mock_base_args, mock
@patch("karaoke_gen.utils.gen_cli.KaraokePrep") # Use default MagicMock for class
@patch("karaoke_gen.utils.gen_cli.KaraokeFinalise")
async def test_workflow_lyrics_only(mock_kfinalise, mock_kprep_class, mock_base_args, mock_logger):
@patch("karaoke_gen.utils.gen_cli.run_instrumental_review", return_value="selected_instrumental.flac")
async def test_workflow_lyrics_only(mock_run_review, mock_kfinalise, mock_kprep_class, mock_base_args, mock_logger):
"""Test --lyrics-only workflow sets environment variables and skips."""
mock_base_args.args = ["Artist", "Title"]
mock_base_args.lyrics_only = True
@@ -404,7 +409,8 @@ async def test_workflow_lyrics_only(mock_kfinalise, mock_kprep_class, mock_base_
@patch("builtins.open", new_callable=mock_open, read_data=SAMPLE_STYLE_JSON)
@patch("karaoke_gen.utils.gen_cli.os.chdir") # Mock chdir
@patch("karaoke_gen.utils.gen_cli.os.path.exists", return_value=True) # Assume track dir exists
async def test_finalise_cdg_style_loading(mock_exists, mock_chdir, mock_open, mock_kfinalise, mock_kprep_class, mock_base_args):
@patch("karaoke_gen.utils.gen_cli.run_instrumental_review", return_value="selected_instrumental.flac")
async def test_finalise_cdg_style_loading(mock_run_review, mock_exists, mock_chdir, mock_open, mock_kfinalise, mock_kprep_class, mock_base_args):
"""Test that CDG styles are loaded correctly when --enable_cdg is used."""
mock_base_args.args = ["Artist", "Title"]
mock_base_args.enable_cdg = True
@@ -437,7 +443,8 @@ async def test_finalise_cdg_style_loading(mock_exists, mock_chdir, mock_open, mo
@patch("karaoke_gen.utils.gen_cli.os.chdir")
@patch("karaoke_gen.utils.gen_cli.os.path.exists", return_value=True)
@patch("karaoke_gen.utils.gen_cli.sys.exit")
async def test_finalise_cdg_style_file_not_found(mock_exit, mock_exists, mock_chdir, mock_open, mock_kfinalise, mock_kprep_class, mock_base_args, mock_logger):
@patch("karaoke_gen.utils.gen_cli.run_instrumental_review", return_value="selected_instrumental.flac")
async def test_finalise_cdg_style_file_not_found(mock_run_review, mock_exit, mock_exists, mock_chdir, mock_open, mock_kfinalise, mock_kprep_class, mock_base_args, mock_logger):
"""Test exit if CDG enabled but style file not found."""
mock_base_args.args = ["Artist", "Title"]
mock_base_args.enable_cdg = True
@@ -465,7 +472,8 @@ async def test_finalise_cdg_style_file_not_found(mock_exit, mock_exists, mock_ch
@patch("karaoke_gen.utils.gen_cli.os.chdir")
@patch("karaoke_gen.utils.gen_cli.os.path.exists", return_value=True)
@patch("karaoke_gen.utils.gen_cli.sys.exit")
async def test_finalise_cdg_style_invalid_json(mock_exit, mock_exists, mock_chdir, mock_open, mock_kfinalise, mock_kprep_class, mock_base_args, mock_logger):
@patch("karaoke_gen.utils.gen_cli.run_instrumental_review", return_value="selected_instrumental.flac")
async def test_finalise_cdg_style_invalid_json(mock_run_review, mock_exit, mock_exists, mock_chdir, mock_open, mock_kfinalise, mock_kprep_class, mock_base_args, mock_logger):
"""Test exit if CDG enabled but style file has invalid JSON."""
mock_base_args.args = ["Artist", "Title"]
mock_base_args.enable_cdg = True
@@ -490,7 +498,7 @@ async def test_finalise_cdg_style_invalid_json(mock_exit, mock_exists, mock_chdi
@patch("karaoke_gen.utils.gen_cli.KaraokePrep") # Use default MagicMock for class
@patch("karaoke_gen.utils.gen_cli.KaraokeFinalise")
async def test_error_handling_kprep_failure(mock_kfinalise, mock_kprep_class, mock_base_args, mock_logger, caplog):
async def test_error_handling_kprep_failure(mock_kfinalise, mock_kprep_class, mock_base_args, mock_logger):
"""Test error handling if KaraokePrep.process fails."""
mock_base_args.args = ["Artist", "Title"]
mock_kprep_instance = MagicMock()
@@ -512,7 +520,8 @@ async def test_error_handling_kprep_failure(mock_kfinalise, mock_kprep_class, mo
@patch("karaoke_gen.utils.gen_cli.KaraokeFinalise")
@patch("karaoke_gen.utils.gen_cli.os.chdir")
@patch("karaoke_gen.utils.gen_cli.os.path.exists", return_value=True)
async def test_error_handling_kfinalise_failure(mock_exists, mock_chdir, mock_kfinalise, mock_kprep_class, mock_base_args, mock_logger, caplog):
@patch("karaoke_gen.utils.gen_cli.run_instrumental_review", return_value="selected_instrumental.flac")
async def test_error_handling_kfinalise_failure(mock_run_review, mock_exists, mock_chdir, mock_kfinalise, mock_kprep_class, mock_base_args, mock_logger, capsys):
"""Test error handling if KaraokeFinalise.process fails."""
mock_base_args.args = ["Artist", "Title"]
mock_kprep_instance = MagicMock()
@@ -533,13 +542,15 @@ async def test_error_handling_kfinalise_failure(mock_exists, mock_chdir, mock_kf
mock_kfinalise.assert_called_once() # Finalise is called
mock_kfinalise_instance.process.assert_called_once() # Process is called
# Check the error message in log
assert "An error occurred during finalisation, see stack trace below: KFinalise Failed!" in caplog.text
# Check the error message in log (in stderr since logger.propagate = False)
captured = capsys.readouterr()
assert "An error occurred during finalisation, see stack trace below: KFinalise Failed!" in captured.err
@patch("karaoke_gen.utils.gen_cli.KaraokePrep") # Use default MagicMock for class
@patch("karaoke_gen.utils.gen_cli.KaraokeFinalise")
async def test_argument_passthrough(mock_kfinalise, mock_kprep_class, mock_base_args):
@patch("karaoke_gen.utils.gen_cli.run_instrumental_review", return_value="selected_instrumental.flac")
async def test_argument_passthrough(mock_run_review, mock_kfinalise, mock_kprep_class, mock_base_args):
"""Test that various arguments are passed correctly to KaraokePrep/Finalise."""
mock_base_args.args = ["Artist", "Title"]
mock_base_args.render_bounding_boxes = True
@@ -595,7 +606,8 @@ async def test_argument_passthrough(mock_kfinalise, mock_kprep_class, mock_base_
@patch("karaoke_gen.utils.gen_cli.os.chdir")
@patch("karaoke_gen.utils.gen_cli.os.path.exists", return_value=True)
@patch("karaoke_gen.utils.gen_cli.pyperclip.copy")
async def test_clipboard_copy_success(mock_copy, mock_exists, mock_chdir, mock_kfinalise, mock_kprep_class, mock_base_args, mock_logger, caplog):
@patch("karaoke_gen.utils.gen_cli.run_instrumental_review", return_value="selected_instrumental.flac")
async def test_clipboard_copy_success(mock_run_review, mock_copy, mock_exists, mock_chdir, mock_kfinalise, mock_kprep_class, mock_base_args, mock_logger, capsys):
"""Test logging when clipboard copy succeeds."""
mock_base_args.args = ["Artist", "Title"]
@@ -615,9 +627,10 @@ async def test_clipboard_copy_success(mock_copy, mock_exists, mock_chdir, mock_k
await gen_cli.async_main()
mock_kprep_instance.process.assert_awaited_once()
# Check log capture for success messages
assert "(Folder link copied to clipboard)" in caplog.text
assert "(YouTube URL copied to clipboard)" in caplog.text
# Check log capture for success messages (in stderr since logger.propagate = False)
captured = capsys.readouterr()
assert "(Folder link copied to clipboard)" in captured.err
assert "(YouTube URL copied to clipboard)" in captured.err
mock_copy.assert_has_calls([
call("http://share.link/fake"),
@@ -630,7 +643,8 @@ async def test_clipboard_copy_success(mock_copy, mock_exists, mock_chdir, mock_k
@patch("karaoke_gen.utils.gen_cli.os.chdir")
@patch("karaoke_gen.utils.gen_cli.os.path.exists", return_value=True)
@patch("karaoke_gen.utils.gen_cli.pyperclip.copy", side_effect=Exception("Clipboard Error"))
async def test_clipboard_copy_failure(mock_copy, mock_exists, mock_chdir, mock_kfinalise, mock_kprep_class, mock_base_args, mock_logger, caplog):
@patch("karaoke_gen.utils.gen_cli.run_instrumental_review", return_value="selected_instrumental.flac")
async def test_clipboard_copy_failure(mock_run_review, mock_copy, mock_exists, mock_chdir, mock_kfinalise, mock_kprep_class, mock_base_args, mock_logger, capsys):
"""Test logging when clipboard copy fails."""
mock_base_args.args = ["Artist", "Title"]
@@ -650,9 +664,10 @@ async def test_clipboard_copy_failure(mock_copy, mock_exists, mock_chdir, mock_k
await gen_cli.async_main()
mock_kprep_instance.process.assert_awaited_once()
# Check log capture for warning messages
assert "Failed to copy folder link to clipboard: Clipboard Error" in caplog.text
assert "Failed to copy YouTube URL to clipboard: Clipboard Error" in caplog.text
# Check log capture for warning messages (in stderr since logger.propagate = False)
captured = capsys.readouterr()
assert "Failed to copy folder link to clipboard: Clipboard Error" in captured.err
assert "Failed to copy YouTube URL to clipboard: Clipboard Error" in captured.err
# Verify clipboard calls were attempted
mock_copy.assert_has_calls([
@@ -662,7 +677,8 @@ async def test_clipboard_copy_failure(mock_copy, mock_exists, mock_chdir, mock_k
@patch("karaoke_gen.utils.gen_cli.KaraokePrep")
async def test_style_override_parsing(mock_kprep_class, mock_base_args):
@patch("karaoke_gen.utils.gen_cli.run_instrumental_review", return_value="selected_instrumental.flac")
async def test_style_override_parsing(mock_run_review, mock_kprep_class, mock_base_args):
"""Test that --style_override arguments are parsed correctly."""
mock_base_args.args = ["Artist", "Title"]
mock_base_args.style_override = ["intro.background_image=new_image.png", "end.video_duration=10"]
@@ -760,3 +776,138 @@ class TestResolvePathForCwd:
result = _resolve_path_for_cwd(path, track_dir)
# After normalization: "Artist - Title/stems/file.flac" vs "Artist - Title"
assert result == "stems/file.flac"
# --- Test auto_select_instrumental helper function ---
class TestAutoSelectInstrumental:
"""Tests for the auto_select_instrumental function.
This function automatically selects the best instrumental file when
--skip_instrumental_review is used.
"""
def test_prefers_padded_combined_over_non_padded(self, tmp_path, mock_logger):
"""Padded combined instrumental should be preferred."""
from karaoke_gen.utils.gen_cli import auto_select_instrumental
# Create test files
combined = tmp_path / "Artist - Title (Instrumental +BV model.ckpt).flac"
combined_padded = tmp_path / "Artist - Title (Instrumental +BV model.ckpt) (Padded).flac"
combined.touch()
combined_padded.touch()
track = {
"track_output_dir": str(tmp_path),
"separated_audio": {
"combined_instrumentals": {
"model.ckpt": str(combined)
}
}
}
# Change to temp directory (simulating the chdir in gen_cli)
original_dir = os.getcwd()
os.chdir(tmp_path)
try:
result = auto_select_instrumental(track, str(tmp_path), mock_logger)
assert "(Padded)" in result
finally:
os.chdir(original_dir)
def test_prefers_combined_over_clean(self, tmp_path, mock_logger):
"""Combined instrumental (+BV) should be preferred over clean."""
from karaoke_gen.utils.gen_cli import auto_select_instrumental
# Create test files
clean = tmp_path / "Artist - Title (Instrumental model.ckpt).flac"
combined = tmp_path / "Artist - Title (Instrumental +BV model.ckpt).flac"
clean.touch()
combined.touch()
track = {
"track_output_dir": str(tmp_path),
"separated_audio": {
"clean_instrumental": {
"instrumental": str(clean)
},
"combined_instrumentals": {
"model.ckpt": str(combined)
}
}
}
original_dir = os.getcwd()
os.chdir(tmp_path)
try:
result = auto_select_instrumental(track, str(tmp_path), mock_logger)
assert "+BV" in result
finally:
os.chdir(original_dir)
def test_falls_back_to_clean_when_no_combined(self, tmp_path, mock_logger):
"""Should use clean instrumental if no combined available."""
from karaoke_gen.utils.gen_cli import auto_select_instrumental
# Create test file
clean = tmp_path / "Artist - Title (Instrumental model.ckpt).flac"
clean.touch()
track = {
"track_output_dir": str(tmp_path),
"separated_audio": {
"clean_instrumental": {
"instrumental": str(clean)
},
"combined_instrumentals": {}
}
}
original_dir = os.getcwd()
os.chdir(tmp_path)
try:
result = auto_select_instrumental(track, str(tmp_path), mock_logger)
assert "Instrumental" in result
finally:
os.chdir(original_dir)
def test_raises_error_when_no_instrumental_found(self, tmp_path, mock_logger):
"""Should raise FileNotFoundError when no instrumental available."""
from karaoke_gen.utils.gen_cli import auto_select_instrumental
track = {
"track_output_dir": str(tmp_path),
"separated_audio": {
"clean_instrumental": {},
"combined_instrumentals": {}
}
}
original_dir = os.getcwd()
os.chdir(tmp_path)
try:
with pytest.raises(FileNotFoundError, match="No instrumental file found"):
auto_select_instrumental(track, str(tmp_path), mock_logger)
finally:
os.chdir(original_dir)
def test_searches_directory_as_fallback(self, tmp_path, mock_logger):
"""Should search directory if separated_audio is missing data."""
from karaoke_gen.utils.gen_cli import auto_select_instrumental
# Create test file in directory but not in separated_audio
instrumental = tmp_path / "Artist - Title (Instrumental model.ckpt).flac"
instrumental.touch()
track = {
"track_output_dir": str(tmp_path),
"separated_audio": {} # Empty - nothing in separated_audio
}
original_dir = os.getcwd()
os.chdir(tmp_path)
try:
result = auto_select_instrumental(track, str(tmp_path), mock_logger)
assert "Instrumental" in result
finally:
os.chdir(original_dir)
+441
View File
@@ -0,0 +1,441 @@
"""
Unit tests for run_instrumental_review function.
These tests verify that run_instrumental_review correctly integrates:
- AudioAnalyzer
- WaveformGenerator
- InstrumentalReviewServer
Importantly, these tests verify that the correct parameter names are used
when calling the underlying components, which caught the 'audible_segments'
vs 'segments' parameter name bug.
"""
import pytest
import os
import logging
from unittest.mock import MagicMock, patch, PropertyMock
from karaoke_gen.instrumental_review import (
AnalysisResult,
RecommendedSelection,
AudibleSegment,
)
class TestRunInstrumentalReviewIntegration:
"""Tests for run_instrumental_review that verify component integration."""
@pytest.fixture
def mock_logger(self):
"""Create a mock logger."""
logger = MagicMock(spec=logging.Logger)
return logger
@pytest.fixture
def sample_analysis(self):
"""Create a sample AnalysisResult."""
return AnalysisResult(
has_audible_content=True,
total_duration_seconds=180.0,
audible_segments=[
AudibleSegment(
start_seconds=10.0,
end_seconds=20.0,
duration_seconds=10.0,
avg_amplitude_db=-25.0,
),
AudibleSegment(
start_seconds=60.0,
end_seconds=75.0,
duration_seconds=15.0,
avg_amplitude_db=-22.0,
),
],
recommended_selection=RecommendedSelection.REVIEW_NEEDED,
silence_threshold_db=-40.0,
)
@pytest.fixture
def sample_track(self, tmp_path):
"""Create a sample track dictionary with test files."""
# Create fake files
stems_dir = tmp_path / "stems"
stems_dir.mkdir()
backing_vocals = stems_dir / "Test - Song (Backing Vocals model.ckpt).flac"
backing_vocals.touch()
clean_instrumental = tmp_path / "Test - Song (Instrumental model.ckpt).flac"
clean_instrumental.touch()
combined_instrumental = tmp_path / "Test - Song (Instrumental +BV model.ckpt).flac"
combined_instrumental.touch()
return {
"artist": "Test",
"title": "Song",
"track_output_dir": str(tmp_path),
"separated_audio": {
"backing_vocals": {
"model.ckpt": {
"backing_vocals": str(backing_vocals),
}
},
"clean_instrumental": {
"instrumental": str(clean_instrumental),
},
"combined_instrumentals": {
"model.ckpt": str(combined_instrumental),
},
},
}
def test_waveform_generator_called_with_correct_param_names(
self, sample_track, sample_analysis, mock_logger, tmp_path
):
"""
CRITICAL TEST: Verify WaveformGenerator.generate() is called with
'segments' parameter, NOT 'audible_segments'.
This test would have caught the bug where 'audible_segments' was
incorrectly used instead of 'segments'.
"""
from karaoke_gen.utils.gen_cli import run_instrumental_review
# Change to the track directory (simulating gen_cli behavior)
original_dir = os.getcwd()
os.chdir(tmp_path)
try:
with patch('karaoke_gen.utils.gen_cli.AudioAnalyzer') as MockAnalyzer, \
patch('karaoke_gen.utils.gen_cli.WaveformGenerator') as MockWaveformGen, \
patch('karaoke_gen.utils.gen_cli.InstrumentalReviewServer') as MockServer:
# Setup analyzer mock
mock_analyzer_instance = MockAnalyzer.return_value
mock_analyzer_instance.analyze.return_value = sample_analysis
# Setup waveform generator mock
mock_waveform_instance = MockWaveformGen.return_value
mock_waveform_instance.generate.return_value = "waveform.png"
# Setup server mock - simulate user selecting "clean"
mock_server_instance = MockServer.return_value
mock_server_instance._selection_event = MagicMock()
mock_server_instance._selection_event.wait.return_value = None
mock_server_instance.get_selection.return_value = "clean"
# Call the function
result = run_instrumental_review(
track=sample_track,
logger=mock_logger,
)
# CRITICAL ASSERTION: Verify correct parameter name
# The method should be called with 'segments=', not 'audible_segments='
mock_waveform_instance.generate.assert_called_once()
call_kwargs = mock_waveform_instance.generate.call_args.kwargs
# This is the key check that would have caught the bug
assert 'segments' in call_kwargs, \
"WaveformGenerator.generate() should be called with 'segments' parameter"
assert 'audible_segments' not in call_kwargs, \
"WaveformGenerator.generate() should NOT use 'audible_segments' (wrong param name)"
# Verify the segments value is the analysis segments
assert call_kwargs['segments'] == sample_analysis.audible_segments
finally:
os.chdir(original_dir)
def test_waveform_generator_receives_analysis_segments(
self, sample_track, sample_analysis, mock_logger, tmp_path
):
"""Verify the analysis audible_segments are passed to waveform generator."""
from karaoke_gen.utils.gen_cli import run_instrumental_review
original_dir = os.getcwd()
os.chdir(tmp_path)
try:
with patch('karaoke_gen.utils.gen_cli.AudioAnalyzer') as MockAnalyzer, \
patch('karaoke_gen.utils.gen_cli.WaveformGenerator') as MockWaveformGen, \
patch('karaoke_gen.utils.gen_cli.InstrumentalReviewServer') as MockServer:
mock_analyzer_instance = MockAnalyzer.return_value
mock_analyzer_instance.analyze.return_value = sample_analysis
mock_waveform_instance = MockWaveformGen.return_value
mock_waveform_instance.generate.return_value = "waveform.png"
mock_server_instance = MockServer.return_value
mock_server_instance._selection_event = MagicMock()
mock_server_instance._selection_event.wait.return_value = None
mock_server_instance.get_selection.return_value = "clean"
run_instrumental_review(track=sample_track, logger=mock_logger)
# Verify the correct segments were passed
call_kwargs = mock_waveform_instance.generate.call_args.kwargs
passed_segments = call_kwargs['segments']
assert len(passed_segments) == 2
assert passed_segments[0].start_seconds == 10.0
assert passed_segments[1].start_seconds == 60.0
finally:
os.chdir(original_dir)
def test_analyzer_called_with_backing_vocals_path(
self, sample_track, sample_analysis, mock_logger, tmp_path
):
"""Verify AudioAnalyzer.analyze() is called with backing vocals path."""
from karaoke_gen.utils.gen_cli import run_instrumental_review
original_dir = os.getcwd()
os.chdir(tmp_path)
try:
with patch('karaoke_gen.utils.gen_cli.AudioAnalyzer') as MockAnalyzer, \
patch('karaoke_gen.utils.gen_cli.WaveformGenerator') as MockWaveformGen, \
patch('karaoke_gen.utils.gen_cli.InstrumentalReviewServer') as MockServer:
mock_analyzer_instance = MockAnalyzer.return_value
mock_analyzer_instance.analyze.return_value = sample_analysis
mock_waveform_instance = MockWaveformGen.return_value
mock_waveform_instance.generate.return_value = "waveform.png"
mock_server_instance = MockServer.return_value
mock_server_instance._selection_event = MagicMock()
mock_server_instance._selection_event.wait.return_value = None
mock_server_instance.get_selection.return_value = "clean"
run_instrumental_review(track=sample_track, logger=mock_logger)
# Verify analyzer was called with a backing vocals path
mock_analyzer_instance.analyze.assert_called_once()
analyzed_path = mock_analyzer_instance.analyze.call_args[0][0]
assert "Backing Vocals" in analyzed_path or os.path.exists(analyzed_path)
finally:
os.chdir(original_dir)
def test_server_started_with_correct_parameters(
self, sample_track, sample_analysis, mock_logger, tmp_path
):
"""Verify InstrumentalReviewServer is created with correct parameters."""
from karaoke_gen.utils.gen_cli import run_instrumental_review
original_dir = os.getcwd()
os.chdir(tmp_path)
try:
with patch('karaoke_gen.utils.gen_cli.AudioAnalyzer') as MockAnalyzer, \
patch('karaoke_gen.utils.gen_cli.WaveformGenerator') as MockWaveformGen, \
patch('karaoke_gen.utils.gen_cli.InstrumentalReviewServer') as MockServer:
mock_analyzer_instance = MockAnalyzer.return_value
mock_analyzer_instance.analyze.return_value = sample_analysis
mock_waveform_instance = MockWaveformGen.return_value
mock_waveform_instance.generate.return_value = "waveform.png"
mock_server_instance = MockServer.return_value
mock_server_instance._selection_event = MagicMock()
mock_server_instance._selection_event.wait.return_value = None
mock_server_instance.get_selection.return_value = "clean"
run_instrumental_review(track=sample_track, logger=mock_logger)
# Verify server was created with expected parameters
MockServer.assert_called_once()
server_kwargs = MockServer.call_args.kwargs
assert server_kwargs['base_name'] == "Test - Song"
assert server_kwargs['analysis'] == sample_analysis
assert 'waveform_path' in server_kwargs
assert 'backing_vocals_path' in server_kwargs
assert 'clean_instrumental_path' in server_kwargs
finally:
os.chdir(original_dir)
def test_returns_clean_instrumental_when_clean_selected(
self, sample_track, sample_analysis, mock_logger, tmp_path
):
"""Verify correct path returned when user selects 'clean'."""
from karaoke_gen.utils.gen_cli import run_instrumental_review
original_dir = os.getcwd()
os.chdir(tmp_path)
try:
with patch('karaoke_gen.utils.gen_cli.AudioAnalyzer') as MockAnalyzer, \
patch('karaoke_gen.utils.gen_cli.WaveformGenerator') as MockWaveformGen, \
patch('karaoke_gen.utils.gen_cli.InstrumentalReviewServer') as MockServer:
mock_analyzer_instance = MockAnalyzer.return_value
mock_analyzer_instance.analyze.return_value = sample_analysis
mock_waveform_instance = MockWaveformGen.return_value
mock_waveform_instance.generate.return_value = "waveform.png"
mock_server_instance = MockServer.return_value
mock_server_instance._selection_event = MagicMock()
mock_server_instance._selection_event.wait.return_value = None
mock_server_instance.get_selection.return_value = "clean"
result = run_instrumental_review(track=sample_track, logger=mock_logger)
# Should return the clean instrumental path
assert result is not None
assert "Instrumental" in result
assert "+BV" not in result
finally:
os.chdir(original_dir)
def test_returns_with_backing_when_selected(
self, sample_track, sample_analysis, mock_logger, tmp_path
):
"""Verify correct path returned when user selects 'with_backing'."""
from karaoke_gen.utils.gen_cli import run_instrumental_review
original_dir = os.getcwd()
os.chdir(tmp_path)
try:
with patch('karaoke_gen.utils.gen_cli.AudioAnalyzer') as MockAnalyzer, \
patch('karaoke_gen.utils.gen_cli.WaveformGenerator') as MockWaveformGen, \
patch('karaoke_gen.utils.gen_cli.InstrumentalReviewServer') as MockServer:
mock_analyzer_instance = MockAnalyzer.return_value
mock_analyzer_instance.analyze.return_value = sample_analysis
mock_waveform_instance = MockWaveformGen.return_value
mock_waveform_instance.generate.return_value = "waveform.png"
mock_server_instance = MockServer.return_value
mock_server_instance._selection_event = MagicMock()
mock_server_instance._selection_event.wait.return_value = None
mock_server_instance.get_selection.return_value = "with_backing"
result = run_instrumental_review(track=sample_track, logger=mock_logger)
# Should return the combined instrumental path (with backing vocals)
assert result is not None
assert "+BV" in result
finally:
os.chdir(original_dir)
def test_returns_none_when_no_backing_vocals(
self, mock_logger, tmp_path
):
"""Verify None returned when no backing vocals file exists."""
from karaoke_gen.utils.gen_cli import run_instrumental_review
track = {
"artist": "Test",
"title": "Song",
"track_output_dir": str(tmp_path),
"separated_audio": {
"backing_vocals": {}, # No backing vocals
"clean_instrumental": {},
"combined_instrumentals": {},
},
}
original_dir = os.getcwd()
os.chdir(tmp_path)
try:
result = run_instrumental_review(track=track, logger=mock_logger)
assert result is None
finally:
os.chdir(original_dir)
def test_returns_none_when_no_separated_audio(
self, mock_logger, tmp_path
):
"""Verify None returned when no separated_audio in track."""
from karaoke_gen.utils.gen_cli import run_instrumental_review
track = {
"artist": "Test",
"title": "Song",
"track_output_dir": str(tmp_path),
"separated_audio": {},
}
result = run_instrumental_review(track=track, logger=mock_logger)
assert result is None
def test_handles_exception_gracefully(
self, sample_track, mock_logger, tmp_path
):
"""Verify exceptions are caught and None is returned."""
from karaoke_gen.utils.gen_cli import run_instrumental_review
original_dir = os.getcwd()
os.chdir(tmp_path)
try:
with patch('karaoke_gen.utils.gen_cli.AudioAnalyzer') as MockAnalyzer:
# Make analyzer raise an exception
mock_analyzer_instance = MockAnalyzer.return_value
mock_analyzer_instance.analyze.side_effect = Exception("Test error")
result = run_instrumental_review(track=sample_track, logger=mock_logger)
# Should return None on error
assert result is None
# Should log the error
mock_logger.error.assert_called()
finally:
os.chdir(original_dir)
class TestWaveformGeneratorParameterContract:
"""
Contract tests to verify WaveformGenerator.generate() parameter signature.
These tests ensure the interface is stable and document expected parameters.
"""
def test_generate_accepts_segments_parameter(self):
"""Verify generate() method accepts 'segments' as a keyword argument."""
from karaoke_gen.instrumental_review import WaveformGenerator
import inspect
sig = inspect.signature(WaveformGenerator.generate)
params = sig.parameters
assert 'segments' in params, \
"WaveformGenerator.generate() must have a 'segments' parameter"
def test_generate_does_not_have_audible_segments_parameter(self):
"""
Verify generate() does NOT have 'audible_segments' parameter.
This documents that the correct parameter name is 'segments',
not 'audible_segments' (which matches the model field name).
"""
from karaoke_gen.instrumental_review import WaveformGenerator
import inspect
sig = inspect.signature(WaveformGenerator.generate)
params = sig.parameters
assert 'audible_segments' not in params, \
"WaveformGenerator.generate() should use 'segments', not 'audible_segments'"
def test_generate_parameter_types_documented(self):
"""Verify generate() method has proper type annotations."""
from karaoke_gen.instrumental_review import WaveformGenerator
import inspect
sig = inspect.signature(WaveformGenerator.generate)
params = sig.parameters
# Key parameters should have annotations
assert params['audio_path'].annotation == str
assert params['output_path'].annotation == str