Compare commits

...
Author SHA1 Message Date
Andrew Beveridge 9e53bb7934 Merge remote-tracking branch 'origin/main' into feature/annotation-toggle 2025-12-18 01:53:10 -05:00
Andrew Beveridge ☄️ a85727b147 Merge pull request #28 from nomadkaraoke/fix-flac-fetcher
Fix flacfetch API compatibility and use rich CLI output
2025-12-18 01:52:32 -05:00
Andrew Beveridge 3eb8f707b6 Add toggle to disable annotation prompts when editing lyrics
- Add "Feedback On/Off" chip in header next to title
- Toggle persists to localStorage for session continuity
- Defaults to enabled (annotation prompts shown)
- Hidden in read-only mode
- Tooltip explains functionality

Version bump: 0.71.63 -> 0.71.64
2025-12-18 01:46:41 -05:00
Andrew Beveridge 4b26fe9eac Add integration tests for flacfetch compatibility
Add comprehensive tests that would have caught both recent bugs:

1. TestGetManagerIntegration - Tests that actually execute _get_manager():
   - test_get_manager_imports_work: Would have caught YouTubeProvider rename
   - test_get_manager_registers_*: Would have caught missing downloader registration

2. TestFlacFetchReleaseModelCompatibility - Tests against real flacfetch models:
   - test_release_model_has_expected_attributes: Verifies attribute names match
   - test_search_converts_release_attributes_correctly: Tests with real Release objects

3. TestFlacFetchCLIHandlerCompatibility - Tests CLIHandler integration:
   - test_cli_handler_import_works: Verifies import path
   - test_cli_handler_works_with_real_releases: Tests with real Quality objects

These tests use real flacfetch classes instead of mocks to catch API changes.

Bump version to 0.71.63
2025-12-18 01:37:00 -05:00
Andrew Beveridge 4de3ecc85d Register downloaders for flacfetch sources
- Register YoutubeDownloader for YouTube source
- Register TorrentDownloader for Redacted and OPS sources
- Handle optional TorrentDownloader import (has extra dependencies)

This fixes "No downloader registered for source: Redacted" error when
trying to download from torrent tracker sources.

Bump version to 0.71.62
2025-12-18 01:32:52 -05:00
Andrew Beveridge cbb4cd8f9e Fix flacfetch API compatibility and use rich CLI output
- Update YouTubeProvider import to YoutubeProvider (API change in flacfetch 0.2.0)
- Update attribute names to match flacfetch Release model:
  - provider -> source_name
  - duration -> duration_seconds
  - url -> download_url
  - id -> info_hash
- Use flacfetch's built-in CLIHandler for rich, colorized interactive selection
- Add fallback to basic display if CLIHandler fails (e.g., in tests)
- Update tests to use correct flacfetch attribute names

Bump version to 0.71.61
2025-12-18 01:25:55 -05:00
Andrew Beveridge ☄️ 218011cf2a Merge pull request #27 from nomadkaraoke/refactor/instrumental-review-ui-improvements
Refactor instrumental review UI: extract frontend to static file and improve UX
2025-12-18 01:22:55 -05:00
Andrew Beveridge 22c6e7ed41 Fix audio listeners not attached after DOM rebuild
Track audio element reference instead of boolean flag to detect when the
audio element is replaced during render(). Re-attach listeners when the
element changes, ensuring new audio elements have proper event handlers.

Version bump: 0.71.59 → 0.71.60
2025-12-18 01:13:19 -05:00
Andrew Beveridge e104fb9252 Add original audio option to instrumental review UI
Backend:
- Add original_audio_path parameter to InstrumentalReviewServer
- Add /api/audio/original endpoint for streaming original audio
- Add "original" to valid selection options

Frontend:
- Add "Original" toggle button (shown first when available)
- Add "Original Audio" selection option with description
- Add original to success message labels

Helper script:
- Find original audio files matching "(Original)" pattern
- Log and pass original_audio_path to server

Version bump: 0.71.58 → 0.71.59
2025-12-18 01:05:11 -05:00
Andrew Beveridge 31931cc55d Address CodeRabbit PR review comments
Frontend (index.html):
- Fix duplicate event listeners: add audioListenersInitialized flag and named
  handlers (onAudioPlay, onAudioPause, onAudioEnded) to prevent accumulation
- Remove redundant removeEventListener in loadeddata handler (already using once: true)
- Use data-audio-type attributes on toggle buttons for robust type detection
- Add escapeHtml() helper to prevent XSS in artist/title/filename interpolation
- Guard updatePlayhead() against NaN/Infinity when duration is 0 or invalid
- Add explicit 'uploaded' branch in success message ternary

Backend (server.py):
- Wrap temp file handling in try/finally to ensure cleanup on error
- Track file_moved state to only unlink temp file if not successfully moved

Version bump: 0.71.57 → 0.71.58
2025-12-18 00:45:55 -05:00
Andrew Beveridge d21729bf3d Fix JavaScript syntax error and improve file discovery in helper script
- Fix invalid escape sequences in updateMuteRegionsPanel() - use string
  concatenation instead of nested template literals
- Update helper script to find instrumental files in main job directory
  (not just stems/) and handle "+BV" naming convention

Version bump: 0.71.56 → 0.71.57
2025-12-18 00:39:07 -05:00
Andrew Beveridge b49a09e1c6 Add helper script to run instrumental review UI from existing job folder
New script: scripts/run_instrumental_review.py
- Takes a karaoke job directory path as input
- Auto-discovers backing vocals, clean instrumental, and combined files in stems/
- Runs audio analysis and generates waveform if needed
- Starts the review server for frontend development iteration

Usage:
  python scripts/run_instrumental_review.py "Artist - Title"
  python scripts/run_instrumental_review.py "path/to/job" --port 9000
  python scripts/run_instrumental_review.py "path/to/job" --no-browser

Version bump: 0.71.55 → 0.71.56
2025-12-18 00:34:41 -05:00
Andrew Beveridge e6b2194272 Preserve scroll position when adding/removing mute regions while zoomed
- Replace full render() calls with targeted updates when modifying mute regions
- Add updateMuteRegionsPanel() to update only the mute panel DOM
- Just redraw waveform canvas instead of rebuilding entire UI
- Scroll position is now preserved when adding, removing, or clearing regions

Version bump: 0.71.54 → 0.71.55
2025-12-18 00:31:51 -05:00
Andrew Beveridge a08b83df40 Add custom instrumental upload and waveform zoom features
Upload feature:
- Add POST /api/jobs/local/upload-instrumental endpoint
- Validate uploaded audio duration matches original (±0.5s tolerance)
- Support .flac, .mp3, .wav, .m4a, .ogg formats
- Show upload progress overlay with spinner
- Auto-select uploaded audio after successful upload
- Add "Uploaded" option to audio toggles and final selection

Zoom feature:
- Add 1x, 2x, 4x zoom levels for waveform precision
- Waveform container is horizontally scrollable when zoomed
- Zoom controls in toolbar with active state indication
- Maintain proportional scroll position when changing zoom
- Playhead and selection overlay work correctly at all zoom levels

Version bump: 0.71.53 → 0.71.54
2025-12-18 00:27:38 -05:00
Andrew Beveridge 53d2ed2828 Fix duplicate audio when switching sources during playback
- Remove full render() call from setActiveAudio() to avoid recreating audio element
- Update toggle button states directly via classList instead of DOM rebuild
- Check actual audio.paused state instead of isPlaying variable (which gets stale)
- Prevents multiple audio streams playing simultaneously

Version bump: 0.71.52 → 0.71.53
2025-12-18 00:10:58 -05:00
Andrew Beveridge ff20b5ffb3 Fix audio playback AbortError when DOM rebuilds during render
- Pause audio before rebuilding DOM in render() to prevent AbortError
- Use loadeddata event to safely restore playback position and state
- Handle audio lifecycle properly in setActiveAudio() and createCustomInstrumental()
- Prevents duplicate audio playback and console errors

Version bump: 0.71.51 → 0.71.52
2025-12-18 00:09:08 -05:00
Andrew Beveridge 49290f94d7 Refactor instrumental review UI: extract frontend to static file and improve UX
- Move inline HTML/CSS/JS from server.py to static/index.html for better maintainability
- Add proper syntax highlighting, formatting, and linting support for frontend code
- Server now reads HTML from file using Path(__file__).parent / "static"

UI/UX improvements:
- Click on waveform now seeks AND starts playback automatically
- Switching audio sources (Backing/Clean/Combined) maintains playback state
- Clearer audio mode labels: "Backing Vocals Only", "Pure Instrumental", "Instrumental + Backing"
- Replace M key toggle mode with Shift+drag for intuitive mute region selection
- Update help text and keyboard hints

Package configuration:
- Add karaoke_gen/instrumental_review/static/* to pyproject.toml includes
- Verified static files are correctly packaged in wheel for pip installs

Version bump: 0.71.48 → 0.71.51
2025-12-18 00:07:13 -05:00
Andrew Beveridge ☄️ 9b114fcb3d Merge pull request #26 from nomadkaraoke/fix/waveform-generator-param-name
fix: correct parameter name in WaveformGenerator.generate() call
2025-12-17 23:34:34 -05:00
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
16 changed files with 2730 additions and 945 deletions

No files matched your search

+85 -24
View File
@@ -169,25 +169,38 @@ class FlacFetchAudioFetcher(AudioFetcher):
if self._manager is None:
# Import flacfetch here to avoid import errors if not installed
from flacfetch.core.manager import FetchManager
from flacfetch.providers.youtube import YouTubeProvider
from flacfetch.providers.youtube import YoutubeProvider
from flacfetch.downloaders.youtube import YoutubeDownloader
# Try to import TorrentDownloader (has optional dependencies)
try:
from flacfetch.downloaders.torrent import TorrentDownloader
except ImportError:
TorrentDownloader = None
self.logger.debug("TorrentDownloader not available (missing dependencies)")
self._manager = FetchManager()
# Add providers based on available API keys
# Add providers and downloaders based on available API keys
if self._redacted_api_key:
from flacfetch.providers.redacted import RedactedProvider
self._manager.add_provider(RedactedProvider(api_key=self._redacted_api_key))
if TorrentDownloader:
self._manager.register_downloader("Redacted", TorrentDownloader())
self.logger.debug("Added Redacted provider")
if self._ops_api_key:
from flacfetch.providers.ops import OPSProvider
self._manager.add_provider(OPSProvider(api_key=self._ops_api_key))
if TorrentDownloader:
self._manager.register_downloader("OPS", TorrentDownloader())
self.logger.debug("Added OPS provider")
# Always add YouTube as a fallback provider
self._manager.add_provider(YouTubeProvider())
# Always add YouTube as a fallback provider with its downloader
self._manager.add_provider(YoutubeProvider())
self._manager.register_downloader("YouTube", YoutubeDownloader())
self.logger.debug("Added YouTube provider")
return self._manager
@@ -220,15 +233,19 @@ class FlacFetchAudioFetcher(AudioFetcher):
# Convert to our AudioSearchResult format
search_results = []
for result in results:
# Get quality as string if it's a Quality object
quality = getattr(result, "quality", None)
quality_str = str(quality) if quality else None
search_results.append(
AudioSearchResult(
title=getattr(result, "title", title),
artist=getattr(result, "artist", artist),
url=getattr(result, "url", ""),
provider=getattr(result, "provider", "Unknown"),
duration=getattr(result, "duration", None),
quality=getattr(result, "quality", None),
source_id=getattr(result, "id", None),
url=getattr(result, "download_url", "") or "",
provider=getattr(result, "source_name", "Unknown"),
duration=getattr(result, "duration_seconds", None),
quality=quality_str,
source_id=getattr(result, "info_hash", None),
raw_result=result,
)
)
@@ -265,7 +282,7 @@ class FlacFetchAudioFetcher(AudioFetcher):
if output_filename is None:
output_filename = f"{result.artist} - {result.title}"
self.logger.info(f"Downloading: {result.artist} - {result.title} from {result.provider}")
self.logger.info(f"Downloading: {result.artist} - {result.title} from {result.provider or 'Unknown'}")
try:
# Use flacfetch to download
@@ -336,7 +353,7 @@ class FlacFetchAudioFetcher(AudioFetcher):
if auto_select:
# Auto mode: select best result based on flacfetch's ranking
selected = manager.select_best(results)
self.logger.info(f"Auto-selected: {getattr(selected, 'title', title)} from {getattr(selected, 'provider', 'Unknown')}")
self.logger.info(f"Auto-selected: {getattr(selected, 'title', title)} from {getattr(selected, 'source_name', 'Unknown')}")
else:
# Interactive mode: present options to user
selected = self._interactive_select(results, artist, title)
@@ -351,7 +368,7 @@ class FlacFetchAudioFetcher(AudioFetcher):
if output_filename is None:
output_filename = f"{artist} - {title}"
self.logger.info(f"Downloading from {getattr(selected, 'provider', 'Unknown')}...")
self.logger.info(f"Downloading from {getattr(selected, 'source_name', 'Unknown')}...")
try:
filepath = manager.download(
@@ -365,13 +382,17 @@ class FlacFetchAudioFetcher(AudioFetcher):
self.logger.info(f"Downloaded to: {filepath}")
# Get quality as string if it's a Quality object
quality = getattr(selected, "quality", None)
quality_str = str(quality) if quality else None
return AudioFetchResult(
filepath=filepath,
artist=artist,
title=title,
provider=getattr(selected, "provider", "Unknown"),
duration=getattr(selected, "duration", None),
quality=getattr(selected, "quality", None),
provider=getattr(selected, "source_name", "Unknown"),
duration=getattr(selected, "duration_seconds", None),
quality=quality_str,
)
except Exception as e:
@@ -381,35 +402,75 @@ class FlacFetchAudioFetcher(AudioFetcher):
"""
Present search results to the user for interactive selection.
Uses flacfetch's built-in CLIHandler for rich, colorized output.
Args:
results: List of search results from flacfetch
results: List of Release objects from flacfetch
artist: The artist name being searched
title: The track title being searched
Returns:
The selected result object
The selected Release object
"""
try:
# Use flacfetch's built-in CLIHandler for rich display
from flacfetch.interface.cli import CLIHandler
handler = CLIHandler(target_artist=artist)
return handler.select_release(results)
except ImportError:
# Fallback to basic display if CLIHandler not available
return self._basic_interactive_select(results, artist, title)
except (KeyboardInterrupt, EOFError):
print("\nCancelled")
return None
except (AttributeError, TypeError):
# Fallback if results aren't proper Release objects (e.g., in tests)
return self._basic_interactive_select(results, artist, title)
def _basic_interactive_select(self, results: list, artist: str, title: str) -> object:
"""
Basic fallback for interactive selection without rich formatting.
Args:
results: List of Release objects from flacfetch
artist: The artist name being searched
title: The track title being searched
Returns:
The selected Release object
"""
print(f"\n{'=' * 60}")
print(f"Search Results for: {artist} - {title}")
print(f"{'=' * 60}\n")
for i, result in enumerate(results, 1):
provider = getattr(result, "provider", "Unknown")
# Use correct flacfetch attribute names
source_name = getattr(result, "source_name", "Unknown")
result_title = getattr(result, "title", "Unknown")
result_artist = getattr(result, "artist", "Unknown")
quality = getattr(result, "quality", "")
duration = getattr(result, "duration", None)
quality = getattr(result, "quality", None)
duration_seconds = getattr(result, "duration_seconds", None)
seeders = getattr(result, "seeders", None)
target_file = getattr(result, "target_file", None)
# Format duration if available
duration_str = ""
if duration:
minutes = duration // 60
seconds = duration % 60
if duration_seconds:
minutes = duration_seconds // 60
seconds = duration_seconds % 60
duration_str = f" [{minutes}:{seconds:02d}]"
# Format quality - it's a Quality object with __str__
quality_str = f" ({quality})" if quality else ""
print(f" {i}. [{provider}] {result_artist} - {result_title}{quality_str}{duration_str}")
# Format seeders for torrent sources
seeders_str = f" Seeders: {seeders}" if seeders is not None else ""
# Format target file
file_str = f' "{target_file}"' if target_file else ""
print(f" {i}. [{source_name}] {result_artist} - {result_title}{quality_str}{duration_str}{seeders_str}{file_str}")
print()
print(" 0. Cancel")
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -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):
+4 -1
View File
@@ -221,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
@@ -282,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)
+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,4 +1,4 @@
import { Box, Button, Typography, useMediaQuery, useTheme, Switch, FormControlLabel, Tooltip, Paper, IconButton } from '@mui/material'
import { Box, Button, Typography, useMediaQuery, useTheme, Switch, FormControlLabel, Tooltip, Paper, IconButton, Chip } from '@mui/material'
import LockIcon from '@mui/icons-material/Lock'
import UploadFileIcon from '@mui/icons-material/UploadFile'
import FindReplaceIcon from '@mui/icons-material/FindReplace'
@@ -7,6 +7,7 @@ import UndoIcon from '@mui/icons-material/Undo'
import RedoIcon from '@mui/icons-material/Redo'
import TimerIcon from '@mui/icons-material/Timer'
import RestoreIcon from '@mui/icons-material/Restore'
import RateReviewIcon from '@mui/icons-material/RateReview'
import { CorrectionData, InteractionMode } from '../types'
import CorrectionMetrics from './CorrectionMetrics'
import AgenticCorrectionMetrics from './AgenticCorrectionMetrics'
@@ -41,6 +42,8 @@ interface HeaderProps {
onRedo: () => void
canUndo: boolean
canRedo: boolean
annotationsEnabled?: boolean
onAnnotationsToggle?: (enabled: boolean) => void
}
export default function Header({
@@ -65,6 +68,8 @@ export default function Header({
onRedo,
canUndo,
canRedo,
annotationsEnabled = true,
onAnnotationsToggle,
}: HeaderProps) {
const theme = useTheme()
const isMobile = useMediaQuery(theme.breakpoints.down('md'))
@@ -135,17 +140,38 @@ export default function Header({
<Typography variant="h4" sx={{ fontSize: isMobile ? '1.3rem' : '1.5rem' }}>
Nomad Karaoke: Lyrics Transcription Review
</Typography>
{isReadOnly && (
<Button
variant="outlined"
size="small"
startIcon={<UploadFileIcon />}
onClick={onFileLoad}
fullWidth={isMobile}
>
Load File
</Button>
)}
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
{!isReadOnly && onAnnotationsToggle && (
<Tooltip title={annotationsEnabled
? "Click to disable annotation prompts when editing"
: "Click to enable annotation prompts when editing"
}>
<Chip
icon={<RateReviewIcon />}
label={annotationsEnabled ? "Feedback On" : "Feedback Off"}
onClick={() => onAnnotationsToggle(!annotationsEnabled)}
color={annotationsEnabled ? "primary" : "default"}
variant={annotationsEnabled ? "filled" : "outlined"}
size="small"
sx={{
cursor: 'pointer',
'& .MuiChip-icon': { fontSize: '1rem' }
}}
/>
</Tooltip>
)}
{isReadOnly && (
<Button
variant="outlined"
size="small"
startIcon={<UploadFileIcon />}
onClick={onFileLoad}
fullWidth={isMobile}
>
Load File
</Button>
)}
</Box>
</Box>
<Box sx={{
@@ -200,6 +200,8 @@ interface MemoizedHeaderProps {
canUndo: boolean
canRedo: boolean
onUnCorrectAll: () => void
annotationsEnabled: boolean
onAnnotationsToggle: (enabled: boolean) => void
}
// Create a memoized Header component
@@ -224,7 +226,9 @@ const MemoizedHeader = memo(function MemoizedHeader({
onRedo,
canUndo,
canRedo,
onUnCorrectAll
onUnCorrectAll,
annotationsEnabled,
onAnnotationsToggle
}: MemoizedHeaderProps) {
return (
<Header
@@ -249,6 +253,8 @@ const MemoizedHeader = memo(function MemoizedHeader({
canUndo={canUndo}
canRedo={canRedo}
onUnCorrectAll={onUnCorrectAll}
annotationsEnabled={annotationsEnabled}
onAnnotationsToggle={onAnnotationsToggle}
/>
);
});
@@ -295,13 +301,18 @@ export default function LyricsAnalyzer({ data: initialData, onFileLoad, apiClien
wordIdsAffected: string[]
gapId?: string
} | null>(null)
const [annotationsEnabled] = useState(() => {
const [annotationsEnabled, setAnnotationsEnabled] = useState(() => {
// Check localStorage for user preference
const saved = localStorage.getItem('annotationsEnabled')
return saved !== null ? saved === 'true' : true // Default: enabled
// TODO: Add UI toggle to enable/disable via setAnnotationsEnabled
})
// Persist annotation preference to localStorage
const handleAnnotationsToggle = useCallback((enabled: boolean) => {
setAnnotationsEnabled(enabled)
localStorage.setItem('annotationsEnabled', String(enabled))
}, [])
// Correction detail card state
const [correctionDetailOpen, setCorrectionDetailOpen] = useState(false)
const [selectedCorrection, setSelectedCorrection] = useState<{
@@ -1164,6 +1175,8 @@ export default function LyricsAnalyzer({ data: initialData, onFileLoad, apiClien
canUndo={canUndo}
canRedo={canRedo}
onUnCorrectAll={handleUnCorrectAll}
annotationsEnabled={annotationsEnabled}
onAnnotationsToggle={handleAnnotationsToggle}
/>
<Grid container direction={isMobile ? 'column' : 'row'}>
+2 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.71.44"
version = "0.71.64"
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"
@@ -10,6 +10,7 @@ packages = [
{ include = "lyrics_transcriber", from = "lyrics_transcriber_temp" }
]
include = [
"karaoke_gen/instrumental_review/static/*",
"lyrics_transcriber_temp/lyrics_transcriber/frontend/web_assets",
"lyrics_transcriber_temp/lyrics_transcriber/frontend/web_assets/**/*",
"lyrics_transcriber_temp/lyrics_transcriber/output/fonts/*",
+249
View File
@@ -0,0 +1,249 @@
#!/usr/bin/env python3
"""
Helper script to run the Instrumental Review UI from an existing karaoke job folder.
This allows iterating on the frontend without running a full karaoke generation.
Usage:
python scripts/run_instrumental_review.py "path/to/Artist - Title"
# Or with optional port:
python scripts/run_instrumental_review.py "path/to/Artist - Title" --port 8888
"""
import argparse
import glob
import logging
import os
import sys
# Add parent directory to path for imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from karaoke_gen.instrumental_review import (
AudioAnalyzer,
InstrumentalReviewServer,
WaveformGenerator,
)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
def find_file(directory: str, patterns: list[str]) -> str | None:
"""Find a file matching any of the given patterns."""
for pattern in patterns:
matches = glob.glob(os.path.join(directory, pattern))
if matches:
return matches[0]
return None
def find_audio_files(job_dir: str) -> dict:
"""
Find the required audio files in a karaoke job directory.
Returns dict with paths to:
- backing_vocals: The backing vocals stem (in stems/)
- clean_instrumental: The clean instrumental (no backing vocals) - in job_dir
- with_backing: The instrumental with backing vocals (optional) - in job_dir
- original: The original audio file (optional) - in job_dir
"""
stems_dir = os.path.join(job_dir, "stems")
# Find backing vocals in stems/ directory
backing_vocals = None
if os.path.exists(stems_dir):
backing_vocals = find_file(stems_dir, [
"*Backing Vocals*.flac",
"*Backing Vocals*.mp3",
"*Backing Vocals*.wav",
"*backing_vocals*.flac",
"*backing_vocals*.mp3",
])
# Also check main directory for backing vocals
if not backing_vocals:
backing_vocals = find_file(job_dir, [
"*Backing Vocals*.flac",
"*Backing Vocals*.mp3",
"*Backing Vocals*.wav",
])
if not backing_vocals:
raise FileNotFoundError(f"No backing vocals file found in {job_dir}")
# Find original audio file - look for "(Original)" in name
original = find_file(job_dir, [
"*(Original)*.flac",
"*(Original)*.mp3",
"*(Original)*.wav",
])
# Find instrumentals in main job directory
# Look for "(Instrumental ...)" files - clean ones don't have "+BV" or "Backing"
all_instrumentals = glob.glob(os.path.join(job_dir, "*Instrumental*.flac"))
all_instrumentals += glob.glob(os.path.join(job_dir, "*Instrumental*.mp3"))
# Also check stems/ directory
if os.path.exists(stems_dir):
all_instrumentals += glob.glob(os.path.join(stems_dir, "*Instrumental*.flac"))
all_instrumentals += glob.glob(os.path.join(stems_dir, "*Instrumental*.mp3"))
# Filter: files with "+BV" or "Backing" are combined, others are clean
clean_instrumental = None
with_backing = None
for inst in all_instrumentals:
basename = os.path.basename(inst)
if "+BV" in basename or "Backing" in basename or "backing" in basename:
with_backing = inst
elif "Custom" not in basename: # Skip custom instrumentals from previous runs
clean_instrumental = inst
if not clean_instrumental:
raise FileNotFoundError(f"No clean instrumental file found in {job_dir}")
return {
"backing_vocals": backing_vocals,
"clean_instrumental": clean_instrumental,
"with_backing": with_backing,
"original": original,
}
def main():
parser = argparse.ArgumentParser(
description="Run the Instrumental Review UI from an existing karaoke job folder",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python scripts/run_instrumental_review.py "Sabrina Carpenter - Please, Please, Please"
python scripts/run_instrumental_review.py "./output/Artist - Song" --port 9000
""",
)
parser.add_argument(
"job_dir",
help="Path to the karaoke job directory (containing stems/ folder)",
)
parser.add_argument(
"--port",
type=int,
default=8765,
help="Port to run the server on (default: 8765)",
)
parser.add_argument(
"--no-browser",
action="store_true",
help="Don't automatically open browser",
)
args = parser.parse_args()
job_dir = os.path.abspath(args.job_dir)
if not os.path.exists(job_dir):
logger.error(f"Directory not found: {job_dir}")
sys.exit(1)
# Extract base name from directory name
base_name = os.path.basename(job_dir)
logger.info(f"Job directory: {job_dir}")
logger.info(f"Base name: {base_name}")
# Find audio files
try:
files = find_audio_files(job_dir)
except FileNotFoundError as e:
logger.error(str(e))
sys.exit(1)
logger.info(f"Found backing vocals: {os.path.basename(files['backing_vocals'])}")
logger.info(f"Found clean instrumental: {os.path.basename(files['clean_instrumental'])}")
if files["with_backing"]:
logger.info(f"Found with backing: {os.path.basename(files['with_backing'])}")
else:
logger.info("No combined instrumental found (optional)")
if files["original"]:
logger.info(f"Found original: {os.path.basename(files['original'])}")
else:
logger.info("No original audio found (optional)")
# Analyze backing vocals
logger.info("Analyzing backing vocals...")
analyzer = AudioAnalyzer()
analysis = analyzer.analyze(files["backing_vocals"])
logger.info(f" Has audible content: {analysis.has_audible_content}")
logger.info(f" Total duration: {analysis.total_duration_seconds:.1f}s")
logger.info(f" Audible segments: {len(analysis.audible_segments)}")
logger.info(f" Audible percentage: {analysis.audible_percentage:.1f}%")
logger.info(f" Recommendation: {analysis.recommended_selection.value}")
# Generate or find waveform
waveform_path = os.path.join(job_dir, f"{base_name} (Backing Vocals Waveform).png")
if os.path.exists(waveform_path):
logger.info(f"Using existing waveform: {os.path.basename(waveform_path)}")
else:
logger.info("Generating waveform visualization...")
waveform_generator = WaveformGenerator()
waveform_generator.generate(
audio_path=files["backing_vocals"],
output_path=waveform_path,
segments=analysis.audible_segments,
)
logger.info(f"Generated waveform: {os.path.basename(waveform_path)}")
# Create and start server
logger.info(f"Starting instrumental review server on port {args.port}...")
server = InstrumentalReviewServer(
output_dir=job_dir,
base_name=base_name,
analysis=analysis,
waveform_path=waveform_path,
backing_vocals_path=files["backing_vocals"],
clean_instrumental_path=files["clean_instrumental"],
with_backing_path=files["with_backing"],
original_audio_path=files["original"],
)
url = f"http://localhost:{args.port}/"
logger.info(f"Server URL: {url}")
if args.no_browser:
logger.info("Browser auto-open disabled. Open the URL manually.")
# Start server without opening browser
import uvicorn
app = server._create_app()
uvicorn.run(app, host="127.0.0.1", port=args.port, log_level="warning")
else:
logger.info("Opening browser...")
logger.info("Press Ctrl+C to stop the server")
try:
selection = server.start_and_open_browser(port=args.port)
logger.info(f"Selection: {selection}")
if selection == "custom":
custom_path = server.get_custom_instrumental_path()
if custom_path:
logger.info(f"Custom instrumental saved to: {custom_path}")
if selection == "uploaded":
uploaded_path = server.get_uploaded_instrumental_path()
if uploaded_path:
logger.info(f"Uploaded instrumental saved to: {uploaded_path}")
except KeyboardInterrupt:
logger.info("\nServer stopped")
server.stop()
if __name__ == "__main__":
main()
+268 -25
View File
@@ -162,16 +162,16 @@ class TestFlacFetchAudioFetcher:
@patch('karaoke_gen.audio_fetcher.FlacFetchAudioFetcher._get_manager')
def test_search_success(self, mock_get_manager, fetcher):
"""Test successful search returns results."""
# Set up mock
# Set up mock using correct flacfetch Release attribute names
mock_manager = MagicMock()
mock_result = MagicMock()
mock_result.title = "Found Song"
mock_result.artist = "Found Artist"
mock_result.url = "https://example.com/song"
mock_result.provider = "YouTube"
mock_result.duration = 200
mock_result.quality = "320kbps"
mock_result.id = "abc123"
mock_result.download_url = "https://example.com/song"
mock_result.source_name = "YouTube"
mock_result.duration_seconds = 200
mock_result.quality = MagicMock(__str__=MagicMock(return_value="320kbps"))
mock_result.info_hash = "abc123"
mock_manager.search.return_value = [mock_result]
mock_get_manager.return_value = mock_manager
@@ -273,14 +273,14 @@ class TestFlacFetchAudioFetcher:
@patch('karaoke_gen.audio_fetcher.FlacFetchAudioFetcher._get_manager')
def test_search_and_download_auto_select(self, mock_get_manager, fetcher, tmp_path):
"""Test search_and_download with auto_select=True uses select_best."""
# Set up mock
# Set up mock using correct flacfetch Release attribute names
mock_manager = MagicMock()
mock_result = MagicMock()
mock_result.title = "Test Song"
mock_result.artist = "Test Artist"
mock_result.provider = "YouTube"
mock_result.duration = 180
mock_result.quality = "FLAC"
mock_result.source_name = "YouTube"
mock_result.duration_seconds = 180
mock_result.quality = MagicMock(__str__=MagicMock(return_value="FLAC 16bit CD"))
mock_manager.search.return_value = [mock_result]
mock_manager.select_best.return_value = mock_result
downloaded_path = str(tmp_path / "song.flac")
@@ -305,14 +305,16 @@ class TestFlacFetchAudioFetcher:
@patch('builtins.input', return_value='1')
def test_search_and_download_interactive_select(self, mock_input, mock_get_manager, fetcher, tmp_path, capsys):
"""Test search_and_download with interactive selection."""
# Set up mock
# Set up mock using correct flacfetch Release attribute names
mock_manager = MagicMock()
mock_result = MagicMock()
mock_result.title = "Test Song"
mock_result.artist = "Test Artist"
mock_result.provider = "YouTube"
mock_result.duration = 180
mock_result.quality = "320kbps"
mock_result.source_name = "YouTube"
mock_result.duration_seconds = 180
mock_result.quality = MagicMock(__str__=MagicMock(return_value="320kbps"))
mock_result.seeders = None
mock_result.target_file = None
mock_manager.search.return_value = [mock_result]
downloaded_path = str(tmp_path / "song.flac")
mock_manager.download.return_value = downloaded_path
@@ -352,12 +354,15 @@ class TestFlacFetchAudioFetcher:
@patch('builtins.input', return_value='0')
def test_interactive_select_cancel(self, mock_input, fetcher):
"""Test interactive selection returns None when user cancels."""
# Use correct flacfetch Release attribute names for fallback display
mock_result = MagicMock()
mock_result.provider = "YouTube"
mock_result.source_name = "YouTube"
mock_result.title = "Test"
mock_result.artist = "Artist"
mock_result.quality = "FLAC"
mock_result.duration = 180
mock_result.quality = MagicMock(__str__=MagicMock(return_value="FLAC 16bit CD"))
mock_result.duration_seconds = 180
mock_result.seeders = None
mock_result.target_file = None
result = fetcher._interactive_select([mock_result], "Artist", "Test")
assert result is None
@@ -366,11 +371,13 @@ class TestFlacFetchAudioFetcher:
def test_interactive_select_invalid_then_valid(self, mock_input, fetcher):
"""Test interactive selection handles invalid input gracefully."""
mock_result = MagicMock()
mock_result.provider = "YouTube"
mock_result.source_name = "YouTube"
mock_result.title = "Test"
mock_result.artist = "Artist"
mock_result.quality = "FLAC"
mock_result.duration = 180
mock_result.quality = MagicMock(__str__=MagicMock(return_value="FLAC 16bit CD"))
mock_result.duration_seconds = 180
mock_result.seeders = None
mock_result.target_file = None
result = fetcher._interactive_select([mock_result], "Artist", "Test")
assert result == mock_result
@@ -379,11 +386,13 @@ class TestFlacFetchAudioFetcher:
def test_interactive_select_out_of_range_then_valid(self, mock_input, fetcher, capsys):
"""Test interactive selection handles out-of-range input."""
mock_result = MagicMock()
mock_result.provider = "YouTube"
mock_result.source_name = "YouTube"
mock_result.title = "Test"
mock_result.artist = "Artist"
mock_result.quality = "FLAC"
mock_result.duration = 180
mock_result.quality = MagicMock(__str__=MagicMock(return_value="FLAC 16bit CD"))
mock_result.duration_seconds = 180
mock_result.seeders = None
mock_result.target_file = None
result = fetcher._interactive_select([mock_result], "Artist", "Test")
assert result == mock_result
@@ -395,11 +404,13 @@ class TestFlacFetchAudioFetcher:
def test_interactive_select_keyboard_interrupt(self, mock_input, fetcher, capsys):
"""Test interactive selection handles keyboard interrupt."""
mock_result = MagicMock()
mock_result.provider = "YouTube"
mock_result.source_name = "YouTube"
mock_result.title = "Test"
mock_result.artist = "Artist"
mock_result.quality = None
mock_result.duration = None
mock_result.duration_seconds = None
mock_result.seeders = None
mock_result.target_file = None
result = fetcher._interactive_select([mock_result], "Artist", "Test")
assert result is None
@@ -448,6 +459,238 @@ class TestFlacFetchManagerInitialization:
assert fetcher._ops_api_key == "ops_key"
class TestGetManagerIntegration:
"""
Integration tests for _get_manager that verify real flacfetch imports and registration.
These tests catch issues like:
- Import errors from renamed classes (e.g., YouTubeProvider vs YoutubeProvider)
- Missing downloader registration
- API changes in flacfetch
"""
def test_get_manager_imports_work(self):
"""Test that _get_manager can import all required flacfetch modules.
This test would have caught the YouTubeProvider -> YoutubeProvider rename.
"""
fetcher = FlacFetchAudioFetcher()
# Actually call _get_manager to verify imports work
manager = fetcher._get_manager()
# Verify manager was created
assert manager is not None
assert fetcher._manager is manager # Should be cached
# Verify calling again returns same instance (lazy init)
manager2 = fetcher._get_manager()
assert manager is manager2
def test_get_manager_registers_youtube_provider_and_downloader(self):
"""Test that YouTube provider AND downloader are registered.
This test would have caught the missing downloader registration.
"""
fetcher = FlacFetchAudioFetcher()
manager = fetcher._get_manager()
# Verify YouTube provider is registered
provider_names = [p.name for p in manager.providers]
assert "YouTube" in provider_names
# Verify YouTube downloader is registered
assert "YouTube" in manager._downloader_map, \
"YouTube downloader must be registered to download from YouTube"
def test_get_manager_registers_redacted_with_api_key(self):
"""Test that Redacted provider and downloader are registered when API key is provided."""
fetcher = FlacFetchAudioFetcher(redacted_api_key="test_key")
manager = fetcher._get_manager()
# Verify Redacted provider is registered
provider_names = [p.name for p in manager.providers]
assert "Redacted" in provider_names
# Verify Redacted downloader is registered (if TorrentDownloader is available)
# Note: TorrentDownloader may not be available in all environments
try:
from flacfetch.downloaders.torrent import TorrentDownloader
assert "Redacted" in manager._downloader_map, \
"Redacted downloader must be registered when TorrentDownloader is available"
except ImportError:
# TorrentDownloader not available, which is okay
pass
def test_get_manager_registers_ops_with_api_key(self):
"""Test that OPS provider and downloader are registered when API key is provided."""
fetcher = FlacFetchAudioFetcher(ops_api_key="test_key")
manager = fetcher._get_manager()
# Verify OPS provider is registered
provider_names = [p.name for p in manager.providers]
assert "OPS" in provider_names
# Verify OPS downloader is registered (if TorrentDownloader is available)
try:
from flacfetch.downloaders.torrent import TorrentDownloader
assert "OPS" in manager._downloader_map, \
"OPS downloader must be registered when TorrentDownloader is available"
except ImportError:
pass
def test_get_manager_with_all_providers(self):
"""Test manager setup with all providers configured."""
fetcher = FlacFetchAudioFetcher(
redacted_api_key="red_key",
ops_api_key="ops_key",
)
manager = fetcher._get_manager()
provider_names = [p.name for p in manager.providers]
# All three providers should be registered
assert "Redacted" in provider_names
assert "OPS" in provider_names
assert "YouTube" in provider_names
# YouTube downloader should always be registered
assert "YouTube" in manager._downloader_map
class TestFlacFetchReleaseModelCompatibility:
"""
Tests to verify our code is compatible with flacfetch's Release model.
These tests use real flacfetch models to catch attribute name mismatches.
"""
def test_release_model_has_expected_attributes(self):
"""Verify flacfetch Release model has the attributes we expect.
This serves as a canary test - if flacfetch changes attribute names,
this test will fail immediately.
"""
from flacfetch.core.models import Release, Quality, AudioFormat, MediaSource
# Create a real Release object
quality = Quality(format=AudioFormat.FLAC, bit_depth=16, media=MediaSource.CD)
release = Release(
title="Test Song",
artist="Test Artist",
quality=quality,
source_name="Redacted",
)
# Verify the attributes we use in audio_fetcher.py exist
assert hasattr(release, 'title')
assert hasattr(release, 'artist')
assert hasattr(release, 'source_name') # NOT 'provider'
assert hasattr(release, 'quality')
assert hasattr(release, 'download_url')
assert hasattr(release, 'duration_seconds') # NOT 'duration'
assert hasattr(release, 'info_hash') # NOT 'id'
assert hasattr(release, 'seeders')
assert hasattr(release, 'target_file')
# Verify quality can be converted to string
quality_str = str(quality)
assert isinstance(quality_str, str)
assert "FLAC" in quality_str
def test_search_converts_release_attributes_correctly(self):
"""Test that search() correctly maps Release attributes to AudioSearchResult."""
from flacfetch.core.models import Release, Quality, AudioFormat, MediaSource
fetcher = FlacFetchAudioFetcher()
# Create a real Release object with all fields populated
quality = Quality(format=AudioFormat.FLAC, bit_depth=24, media=MediaSource.WEB)
real_release = Release(
title="Real Song",
artist="Real Artist",
quality=quality,
source_name="Redacted",
download_url="https://example.com/download",
duration_seconds=240,
info_hash="abc123hash",
seeders=50,
target_file="01 - Real Song.flac",
)
# Mock the manager to return our real release
with patch.object(fetcher, '_get_manager') as mock_get_manager:
mock_manager = MagicMock()
mock_manager.search.return_value = [real_release]
mock_get_manager.return_value = mock_manager
results = fetcher.search("Real Artist", "Real Song")
# Verify correct attribute mapping
assert len(results) == 1
result = results[0]
assert result.title == "Real Song"
assert result.artist == "Real Artist"
assert result.provider == "Redacted" # source_name -> provider
assert result.duration == 240 # duration_seconds -> duration
assert result.url == "https://example.com/download" # download_url -> url
assert result.source_id == "abc123hash" # info_hash -> source_id
assert "FLAC" in result.quality # quality converted to string
assert result.raw_result is real_release
class TestFlacFetchCLIHandlerCompatibility:
"""Tests to verify compatibility with flacfetch's CLIHandler for rich output."""
def test_cli_handler_import_works(self):
"""Verify we can import CLIHandler from flacfetch."""
from flacfetch.interface.cli import CLIHandler
handler = CLIHandler(target_artist="Test Artist")
assert handler is not None
def test_cli_handler_works_with_real_releases(self):
"""Test that CLIHandler can display real Release objects.
This ensures we're passing proper Release objects, not mocks with wrong attributes.
"""
from flacfetch.core.models import Release, Quality, AudioFormat, MediaSource
from flacfetch.interface.cli import CLIHandler
quality = Quality(format=AudioFormat.FLAC, bit_depth=16, media=MediaSource.CD)
release = Release(
title="Test Song",
artist="Test Artist",
quality=quality,
source_name="Redacted",
seeders=25,
)
handler = CLIHandler(target_artist="Test Artist")
# This should not raise any AttributeError
# (Previously would fail if quality.is_lossless() didn't exist)
try:
# We can't easily test the full select_release without mocking input,
# but we can at least verify _print_release works
import io
import sys
# Capture stdout
captured = io.StringIO()
sys.stdout = captured
try:
handler._print_release(1, release)
finally:
sys.stdout = sys.__stdout__
output = captured.getvalue()
assert "Test Artist" in output or "Test Song" in output
except AttributeError as e:
pytest.fail(f"CLIHandler failed with AttributeError: {e}")
class TestDownloadWithCustomFilename:
"""Tests for download with custom filename."""
+23 -18
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)
@@ -496,7 +498,7 @@ async def test_finalise_cdg_style_invalid_json(mock_run_review, mock_exit, mock_
@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()
@@ -519,7 +521,7 @@ async def test_error_handling_kprep_failure(mock_kfinalise, mock_kprep_class, 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.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, caplog):
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()
@@ -540,8 +542,9 @@ async def test_error_handling_kfinalise_failure(mock_run_review, mock_exists, mo
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
@@ -604,7 +607,7 @@ async def test_argument_passthrough(mock_run_review, mock_kfinalise, mock_kprep_
@patch("karaoke_gen.utils.gen_cli.os.path.exists", return_value=True)
@patch("karaoke_gen.utils.gen_cli.pyperclip.copy")
@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, caplog):
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"]
@@ -624,9 +627,10 @@ async def test_clipboard_copy_success(mock_run_review, mock_copy, mock_exists, m
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"),
@@ -640,7 +644,7 @@ async def test_clipboard_copy_success(mock_run_review, mock_copy, mock_exists, m
@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"))
@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, caplog):
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"]
@@ -660,9 +664,10 @@ async def test_clipboard_copy_failure(mock_run_review, mock_copy, mock_exists, m
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([
@@ -284,7 +284,6 @@ class TestServerAppCreation:
assert isinstance(html, str)
assert "<!DOCTYPE html>" in html
assert "Karaoke Generator" in html
assert "Instrumental Review" in html
def test_get_frontend_html_contains_required_elements(self, mock_analysis, temp_files):
@@ -422,7 +421,7 @@ class TestServerAPIEndpoints:
response = client.get("/")
assert response.status_code == 200
assert "text/html" in response.headers["content-type"]
assert "Karaoke Generator" in response.text
assert "Instrumental Review" in response.text
def test_get_analysis_returns_data(self, client, mock_analysis):
"""Test analysis endpoint returns correct data."""
+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