Compare commits

...
Author SHA1 Message Date
Andrew Beveridge ☄️ 8015e2a228 Update README.md 2025-12-24 01:28:41 -05:00
Andrew Beveridge ☄️ 55b9691fb9 Merge pull request #56 from nomadkaraoke/fix/improve-transcription-provider-error-messages
fix: Improve error messaging for missing transcription provider configuration
2025-12-24 01:27:15 -05:00
Andrew Beveridge 6e089850a7 fix: add mock env vars to countdown padding tests for provider validation
Tests in TestLyricsProcessorIntegration now mock AUDIOSHAKE_API_TOKEN
to satisfy the new transcription provider validation check.

Bump version to 0.75.37
2025-12-24 01:11:08 -05:00
Andrew Beveridge 5f52cffc34 fix: improve error messaging for missing transcription provider configuration
Addresses GitHub issue #55 - users were getting "No suitable files found for processing"
error without understanding the root cause was missing transcription providers.

Changes:
- lyrics_processor.py: Add _check_transcription_providers() and validation in
  transcribe_lyrics() that raises ValueError with detailed setup instructions when
  transcription is enabled but no providers configured
- controller.py: Improve "Starting transcription with providers: []" to WARNING
  level with explanation of consequences and setup instructions
- karaoke_finalise.py: Update find_with_vocals_file() exception to explain that
  missing "(With Vocals).mkv" typically indicates transcription failure, with
  common causes and troubleshooting steps
- README.md: Add "Transcription Providers" section with setup instructions for
  AudioShake and Whisper/RunPod, and add "Troubleshooting" section
- tests/unit/test_lyrics.py: Add comprehensive tests for new provider validation

Bump version to 0.75.36
2025-12-24 00:46:29 -05:00
Andrew Beveridge ☄️ 71ebd43771 Merge pull request #54 from nomadkaraoke/fix/remote-flacfetch-display-formatting
fix: correct remote flacfetch API result display formatting
2025-12-23 23:34:15 -05:00
Andrew Beveridge c6bcb8cead fix: correct remote flacfetch API result display formatting
The RemoteFlacFetchAudioFetcher was showing "lossy" and "Unknown" for all
results instead of the correct quality and source info (e.g., "LOSSLESS" "RED").

Root cause: The API response format uses different field names than what
Release.from_dict() expects:
- API uses "provider" → Release expects "source_name"
- API uses "quality" as display string → Release expects "quality" as dict
- API uses "quality_data" as structured dict → not mapped

Fix:
- Add _convert_api_result_for_release() method to properly map API format
- Map provider → source_name
- Map quality_data → quality (structured dict)
- Store original quality string as quality_str
- Preserve is_lossless flag

Also improved _basic_interactive_select() to show lossless/lossy status.

Added 12 unit tests for the new conversion method.

Bump version to 0.75.35
2025-12-23 23:11:08 -05:00
Andrew Beveridge ☄️ 84288b78d2 Update README.md 2025-12-23 21:57:46 -05:00
Andrew Beveridge ☄️ 41d1eda574 Merge pull request #52 from nomadkaraoke/fix/countdown-padding-existing-corrections
fix: create padded audio when loading existing corrections with countdown
2025-12-23 20:33:55 -05:00
9 changed files with 1856 additions and 15 deletions

No files matched your search

+103 -2
View File
@@ -1,7 +1,7 @@
# Karaoke Generator 🎶 🎥 🚀
![PyPI - Version](https://img.shields.io/pypi/v/karaoke-gen)
![Python Version](https://img.shields.io/badge/python-3.10+-blue)
![PyPI - Python Version](https://img.shields.io/pypi/pyversions/karaoke-gen)
![Tests](https://github.com/nomadkaraoke/karaoke-gen/workflows/Test%20and%20Publish/badge.svg)
![Test Coverage](https://codecov.io/gh/nomadkaraoke/karaoke-gen/branch/main/graph/badge.svg)
@@ -54,10 +54,44 @@ pip install karaoke-gen
This installs both `karaoke-gen` (local) and `karaoke-gen-remote` (cloud) CLIs.
### Requirements
- Python 3.10+
- Python 3.10-3.13
- FFmpeg
- For local processing: CUDA-capable GPU or Apple Silicon CPU recommended
### Transcription Provider Setup
**Transcription is required** for creating karaoke videos with synchronized lyrics. The system needs word-level timing data to display lyrics in sync with the music.
#### Option 1: AudioShake (Recommended)
Commercial service with high-quality transcription. Best for production use.
```bash
export AUDIOSHAKE_API_TOKEN="your_audioshake_token"
```
Get an API key at [https://www.audioshake.ai/](https://www.audioshake.ai/) - business only, at time of writing this.
#### Option 2: Whisper via RunPod
Open-source alternative using OpenAI's Whisper model on RunPod infrastructure.
```bash
export RUNPOD_API_KEY="your_runpod_key"
export WHISPER_RUNPOD_ID="your_whisper_endpoint_id"
```
Set up a Whisper endpoint at [https://www.runpod.io/](https://www.runpod.io/)
#### Without Transcription (Instrumental Only)
If you don't need synchronized lyrics, use the `--skip-lyrics` flag:
```bash
karaoke-gen --skip-lyrics "Artist" "Title"
```
This creates an instrumental-only karaoke video without lyrics overlay.
> **Note:** See `lyrics_transcriber_temp/README.md` for detailed transcription provider configuration options.
---
## 🖥️ Local CLI (`karaoke-gen`)
@@ -475,6 +509,73 @@ Check backend health status.
---
## 🔧 Troubleshooting
### "No suitable files found for processing"
This error occurs during the finalisation step when the `(With Vocals).mkv` file is missing. This file is created during lyrics transcription.
**Most common cause:** No transcription provider configured.
**Quick fix:**
1. Check if transcription providers are configured:
```bash
echo $AUDIOSHAKE_API_TOKEN
echo $RUNPOD_API_KEY
```
2. If both are empty, set up a provider (see [Transcription Provider Setup](#transcription-provider-setup))
3. Or use `--skip-lyrics` for instrumental-only karaoke:
```bash
karaoke-gen --skip-lyrics "Artist" "Title"
```
**Other causes:**
- Invalid API credentials - verify your tokens are correct and active
- API service unavailable - check service status pages
- Network connectivity issues - ensure you can reach the API endpoints
- Transcription timeout - try again or use a different provider
### Transcription Fails Silently
If karaoke-gen runs without errors but produces no synchronized lyrics:
1. **Check logs** - Run with `--log_level debug` for detailed output:
```bash
karaoke-gen --log_level debug "Artist" "Title"
```
2. **Verify environment variables** - Ensure API tokens are exported in your shell:
```bash
# Check if set
printenv | grep -E "(AUDIOSHAKE|RUNPOD|WHISPER)"
# Set in current session
export AUDIOSHAKE_API_TOKEN="your_token"
```
3. **Test API connectivity** - Verify you can reach the transcription service
### "No lyrics found from any source"
This warning means no reference lyrics were fetched from online sources (Genius, Spotify, Musixmatch). The transcription will still work, but auto-correction may be less accurate.
**To fix:**
- Set `GENIUS_API_TOKEN` for Genius lyrics
- Set `SPOTIFY_COOKIE_SP_DC` for Spotify lyrics
- Set `RAPIDAPI_KEY` for Musixmatch lyrics
- Or provide lyrics manually with `--lyrics_file /path/to/lyrics.txt`
### Video Quality Issues
If the output video has quality problems:
- Ensure FFmpeg is properly installed: `ffmpeg -version`
- Check available codecs: `ffmpeg -codecs`
- For 4K output, ensure sufficient disk space (10GB+ per track)
---
## 🧪 Development
### Running Tests
+709 -5
View File
@@ -3,6 +3,11 @@ Audio Fetcher module - abstraction layer for fetching audio files.
This module provides a clean interface for searching and downloading audio files
using flacfetch, replacing the previous direct yt-dlp usage.
Supports two modes:
1. Local mode: Uses flacfetch library directly (requires torrent client, etc.)
2. Remote mode: Uses a remote flacfetch HTTP API server when FLACFETCH_API_URL
and FLACFETCH_API_KEY environment variables are set.
"""
import logging
@@ -11,11 +16,19 @@ import signal
import sys
import tempfile
import threading
import time
from abc import ABC, abstractmethod
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FuturesTimeoutError
from dataclasses import dataclass, asdict, field
from typing import List, Optional, Dict, Any
# Optional import for remote fetcher
try:
import httpx
HTTPX_AVAILABLE = True
except ImportError:
HTTPX_AVAILABLE = False
# Global flag to track if user requested cancellation via Ctrl+C
_interrupt_requested = False
@@ -868,26 +881,717 @@ class FlacFetchAudioFetcher(AudioFetcher):
FlacFetcher = FlacFetchAudioFetcher
class RemoteFlacFetchAudioFetcher(AudioFetcher):
"""
Audio fetcher implementation using remote flacfetch HTTP API.
This fetcher communicates with a dedicated flacfetch server that handles:
- BitTorrent downloads from private trackers (RED, OPS)
- YouTube downloads
- File streaming back to the client
Used when FLACFETCH_API_URL and FLACFETCH_API_KEY environment variables are set.
"""
def __init__(
self,
api_url: str,
api_key: str,
logger: Optional[logging.Logger] = None,
timeout: int = 60,
download_timeout: int = 600,
):
"""
Initialize the remote FlacFetch audio fetcher.
Args:
api_url: Base URL of flacfetch API server (e.g., http://10.0.0.5:8080)
api_key: API key for authentication
logger: Logger instance for output
timeout: Request timeout in seconds for search/status calls
download_timeout: Maximum wait time for downloads to complete
"""
if not HTTPX_AVAILABLE:
raise ImportError("httpx is required for remote flacfetch. Install with: pip install httpx")
self.api_url = api_url.rstrip('/')
self.api_key = api_key
self.logger = logger or logging.getLogger(__name__)
self.timeout = timeout
self.download_timeout = download_timeout
self._last_search_id: Optional[str] = None
self._last_search_results: List[Dict[str, Any]] = []
self.logger.info(f"[RemoteFlacFetcher] Initialized with API URL: {self.api_url}")
def _headers(self) -> Dict[str, str]:
"""Get request headers with authentication."""
return {
"X-API-Key": self.api_key,
"Content-Type": "application/json",
}
def _check_health(self) -> bool:
"""Check if the remote flacfetch service is healthy."""
try:
with httpx.Client() as client:
resp = client.get(
f"{self.api_url}/health",
headers=self._headers(),
timeout=10,
)
if resp.status_code == 200:
data = resp.json()
status = data.get("status", "unknown")
self.logger.debug(f"[RemoteFlacFetcher] Health check: {status}")
return status in ["healthy", "degraded"]
return False
except Exception as e:
self.logger.warning(f"[RemoteFlacFetcher] Health check failed: {e}")
return False
def search(self, artist: str, title: str) -> List[AudioSearchResult]:
"""
Search for audio matching the given artist and title via remote API.
Args:
artist: The artist name to search for
title: The track title to search for
Returns:
List of AudioSearchResult objects
Raises:
NoResultsError: If no results are found
AudioFetcherError: For other errors
"""
self.logger.info(f"[RemoteFlacFetcher] Searching for: {artist} - {title}")
try:
with httpx.Client() as client:
resp = client.post(
f"{self.api_url}/search",
headers=self._headers(),
json={"artist": artist, "title": title},
timeout=self.timeout,
)
if resp.status_code == 404:
raise NoResultsError(f"No results found for: {artist} - {title}")
resp.raise_for_status()
data = resp.json()
self._last_search_id = data.get("search_id")
self._last_search_results = data.get("results", [])
if not self._last_search_results:
raise NoResultsError(f"No results found for: {artist} - {title}")
# Convert API results to AudioSearchResult objects
search_results = []
for i, result in enumerate(self._last_search_results):
search_results.append(
AudioSearchResult(
title=result.get("title", title),
artist=result.get("artist", artist),
url=result.get("download_url", "") or result.get("url", ""),
provider=result.get("provider", result.get("source_name", "Unknown")),
duration=result.get("duration_seconds", result.get("duration")),
quality=result.get("quality_str", result.get("quality")),
source_id=result.get("info_hash"),
index=i,
seeders=result.get("seeders"),
target_file=result.get("target_file"),
raw_result=result, # Store the full API result
)
)
self.logger.info(f"[RemoteFlacFetcher] Found {len(search_results)} results")
return search_results
except httpx.RequestError as e:
raise AudioFetcherError(f"Search request failed: {e}") from e
except httpx.HTTPStatusError as e:
if e.response.status_code == 404:
raise NoResultsError(f"No results found for: {artist} - {title}") from e
raise AudioFetcherError(f"Search failed: {e.response.status_code} - {e.response.text}") from e
def download(
self,
result: AudioSearchResult,
output_dir: str,
output_filename: Optional[str] = None,
) -> AudioFetchResult:
"""
Download audio from a search result via remote API.
Args:
result: The search result to download
output_dir: Directory to save the downloaded file
output_filename: Optional filename (without extension)
Returns:
AudioFetchResult with the downloaded file path
Raises:
DownloadError: If download fails
"""
if not self._last_search_id:
raise DownloadError("No search performed - call search() first")
# Ensure output directory exists
os.makedirs(output_dir, exist_ok=True)
# Generate filename if not provided
if output_filename is None:
output_filename = f"{result.artist} - {result.title}"
self.logger.info(f"[RemoteFlacFetcher] Downloading: {result.artist} - {result.title} from {result.provider}")
try:
# Start the download
with httpx.Client() as client:
resp = client.post(
f"{self.api_url}/download",
headers=self._headers(),
json={
"search_id": self._last_search_id,
"result_index": result.index,
"output_filename": output_filename,
# Don't set upload_to_gcs - we want local download
},
timeout=self.timeout,
)
resp.raise_for_status()
data = resp.json()
download_id = data.get("download_id")
if not download_id:
raise DownloadError("No download_id returned from API")
self.logger.info(f"[RemoteFlacFetcher] Download started: {download_id}")
# Wait for download to complete
filepath = self._wait_and_stream_download(
download_id=download_id,
output_dir=output_dir,
output_filename=output_filename,
)
self.logger.info(f"[RemoteFlacFetcher] Downloaded to: {filepath}")
return AudioFetchResult(
filepath=filepath,
artist=result.artist,
title=result.title,
provider=result.provider,
duration=result.duration,
quality=result.quality,
)
except httpx.RequestError as e:
raise DownloadError(f"Download request failed: {e}") from e
except httpx.HTTPStatusError as e:
raise DownloadError(f"Download failed: {e.response.status_code} - {e.response.text}") from e
def _wait_and_stream_download(
self,
download_id: str,
output_dir: str,
output_filename: str,
poll_interval: float = 2.0,
) -> str:
"""
Wait for a remote download to complete, then stream the file locally.
Args:
download_id: Download ID from /download endpoint
output_dir: Local directory to save file
output_filename: Local filename (without extension)
poll_interval: Seconds between status checks
Returns:
Path to the downloaded local file
Raises:
DownloadError: On download failure or timeout
UserCancelledError: If user presses Ctrl+C
"""
global _interrupt_requested
_interrupt_requested = False
# Set up signal handler for Ctrl+C
original_handler = signal.getsignal(signal.SIGINT)
def interrupt_handler(signum, frame):
global _interrupt_requested
_interrupt_requested = True
print("\nCancelling download... please wait", file=sys.stderr)
signal.signal(signal.SIGINT, interrupt_handler)
try:
elapsed = 0.0
last_progress = -1
while elapsed < self.download_timeout:
# Check for interrupt
if _interrupt_requested:
raise UserCancelledError("Download cancelled by user (Ctrl+C)")
# Check status
with httpx.Client() as client:
resp = client.get(
f"{self.api_url}/download/{download_id}/status",
headers=self._headers(),
timeout=10,
)
resp.raise_for_status()
status = resp.json()
download_status = status.get("status")
progress = status.get("progress", 0)
speed = status.get("download_speed_kbps", 0)
# Log progress updates
if int(progress) != last_progress:
if download_status == "downloading":
self.logger.info(f"[RemoteFlacFetcher] Progress: {progress:.1f}% ({speed:.1f} KB/s)")
elif download_status in ["uploading", "processing"]:
self.logger.info(f"[RemoteFlacFetcher] {download_status.capitalize()}...")
last_progress = int(progress)
if download_status in ["complete", "seeding"]:
# Download complete - now stream the file locally
self.logger.info(f"[RemoteFlacFetcher] Remote download complete, streaming to local...")
return self._stream_file_locally(download_id, output_dir, output_filename)
elif download_status == "failed":
error = status.get("error", "Unknown error")
raise DownloadError(f"Remote download failed: {error}")
elif download_status == "cancelled":
raise DownloadError("Download was cancelled on server")
time.sleep(poll_interval)
elapsed += poll_interval
raise DownloadError(f"Download timed out after {self.download_timeout}s")
finally:
# Restore original signal handler
signal.signal(signal.SIGINT, original_handler)
_interrupt_requested = False
def _stream_file_locally(
self,
download_id: str,
output_dir: str,
output_filename: str,
) -> str:
"""
Stream a completed download from the remote server to local disk.
Args:
download_id: Download ID
output_dir: Local directory to save file
output_filename: Local filename (without extension)
Returns:
Path to the downloaded local file
Raises:
DownloadError: On streaming failure
"""
try:
# Stream the file from the remote server
with httpx.Client() as client:
with client.stream(
"GET",
f"{self.api_url}/download/{download_id}/file",
headers=self._headers(),
timeout=300, # 5 minute timeout for file streaming
) as resp:
resp.raise_for_status()
# Get content-disposition header for filename/extension
content_disp = resp.headers.get("content-disposition", "")
# Try to extract extension from the server's filename
extension = ".flac" # Default
if "filename=" in content_disp:
import re
match = re.search(r'filename="?([^";\s]+)"?', content_disp)
if match:
server_filename = match.group(1)
_, ext = os.path.splitext(server_filename)
if ext:
extension = ext
# Also try content-type
content_type = resp.headers.get("content-type", "")
if "audio/mpeg" in content_type or "audio/mp3" in content_type:
extension = ".mp3"
elif "audio/wav" in content_type:
extension = ".wav"
elif "audio/x-flac" in content_type or "audio/flac" in content_type:
extension = ".flac"
elif "audio/mp4" in content_type or "audio/m4a" in content_type:
extension = ".m4a"
# Build local filepath
local_filepath = os.path.join(output_dir, f"{output_filename}{extension}")
# Stream to local file
total_bytes = 0
with open(local_filepath, "wb") as f:
for chunk in resp.iter_bytes(chunk_size=8192):
f.write(chunk)
total_bytes += len(chunk)
self.logger.info(f"[RemoteFlacFetcher] Streamed {total_bytes / 1024 / 1024:.1f} MB to {local_filepath}")
return local_filepath
except httpx.RequestError as e:
raise DownloadError(f"Failed to stream file: {e}") from e
except httpx.HTTPStatusError as e:
raise DownloadError(f"Failed to stream file: {e.response.status_code}") from e
def select_best(self, results: List[AudioSearchResult]) -> int:
"""
Select the best result from a list of search results.
For remote fetcher, we use simple heuristics since we don't have
access to flacfetch's internal ranking. Prefers:
1. Lossless sources (FLAC) over lossy
2. Higher seeders for torrents
3. First result otherwise (API typically returns sorted by quality)
Args:
results: List of AudioSearchResult objects from search()
Returns:
Index of the best result in the list
"""
if not results:
return 0
# Score each result
best_index = 0
best_score = -1
for i, result in enumerate(results):
score = 0
# Prefer lossless
quality = (result.quality or "").lower()
if "flac" in quality or "lossless" in quality:
score += 1000
elif "320" in quality:
score += 500
elif "256" in quality or "192" in quality:
score += 200
# Prefer higher seeders (for torrents)
if result.seeders:
score += min(result.seeders, 100) # Cap at 100 points
# Prefer non-YouTube sources (typically higher quality)
provider = (result.provider or "").lower()
if "youtube" not in provider:
score += 50
if score > best_score:
best_score = score
best_index = i
return best_index
def search_and_download(
self,
artist: str,
title: str,
output_dir: str,
output_filename: Optional[str] = None,
auto_select: bool = False,
) -> AudioFetchResult:
"""
Search for audio and download it in one operation via remote API.
Args:
artist: The artist name to search for
title: The track title to search for
output_dir: Directory to save the downloaded file
output_filename: Optional filename (without extension)
auto_select: If True, automatically select the best result
Returns:
AudioFetchResult with the downloaded file path
Raises:
NoResultsError: If no results are found
DownloadError: If download fails
UserCancelledError: If user cancels
"""
# Search
results = self.search(artist, title)
if auto_select:
# Auto mode: select best result
best_index = self.select_best(results)
selected = results[best_index]
self.logger.info(f"[RemoteFlacFetcher] Auto-selected: {selected.title} from {selected.provider}")
else:
# Interactive mode: present options to user
selected = self._interactive_select(results, artist, title)
# Download
return self.download(selected, output_dir, output_filename)
def _convert_api_result_for_release(self, api_result: dict) -> dict:
"""
Convert API SearchResultItem format to format expected by Release.from_dict().
The flacfetch API returns:
- provider: source name (RED, OPS, YouTube)
- quality: display string (e.g., "FLAC 16bit CD")
- quality_data: structured dict with format, bit_depth, media, etc.
But Release.from_dict() expects:
- source_name: provider name
- quality: dict with format, bit_depth, media, etc.
This mirrors the convert_api_result_to_display() function in flacfetch-remote CLI.
"""
result = dict(api_result) # Copy to avoid modifying original
# Map provider to source_name
result["source_name"] = api_result.get("provider", "Unknown")
# Store original quality string as quality_str (used by display functions)
result["quality_str"] = api_result.get("quality", "")
# Map quality_data to quality (Release.from_dict expects quality to be a dict)
quality_data = api_result.get("quality_data")
if quality_data and isinstance(quality_data, dict):
result["quality"] = quality_data
else:
# Fallback: parse quality string to determine format
quality_str = api_result.get("quality", "").upper()
format_name = "OTHER"
media_name = "OTHER"
if "FLAC" in quality_str:
format_name = "FLAC"
elif "MP3" in quality_str:
format_name = "MP3"
elif "WAV" in quality_str:
format_name = "WAV"
if "CD" in quality_str:
media_name = "CD"
elif "WEB" in quality_str:
media_name = "WEB"
elif "VINYL" in quality_str:
media_name = "VINYL"
result["quality"] = {"format": format_name, "media": media_name}
# Copy is_lossless if available
if "is_lossless" in api_result:
result["is_lossless"] = api_result["is_lossless"]
return result
def _interactive_select(
self,
results: List[AudioSearchResult],
artist: str,
title: str,
) -> AudioSearchResult:
"""
Present search results to the user for interactive selection.
Uses flacfetch's built-in display functions if available, otherwise
falls back to basic text display.
Args:
results: List of AudioSearchResult objects
artist: The artist name being searched
title: The track title being searched
Returns:
The selected AudioSearchResult
Raises:
UserCancelledError: If user cancels selection
"""
# Try to use flacfetch's display functions with raw API results
try:
# Convert raw_result dicts back to Release objects for display
from flacfetch.core.models import Release
releases = []
for r in results:
if r.raw_result and isinstance(r.raw_result, dict):
# Convert API format to Release.from_dict() format
converted = self._convert_api_result_for_release(r.raw_result)
release = Release.from_dict(converted)
releases.append(release)
elif r.raw_result and hasattr(r.raw_result, 'title'):
# It's already a Release object
releases.append(r.raw_result)
if releases:
from flacfetch.interface.cli import CLIHandler
handler = CLIHandler(target_artist=artist)
selected_release = handler.select_release(releases)
if selected_release is None:
raise UserCancelledError("Selection cancelled by user")
# Find the matching AudioSearchResult by index
# CLIHandler returns the release at the selected index
for i, release in enumerate(releases):
if release == selected_release:
return results[i]
# Fallback: try matching by download_url
for r in results:
if r.raw_result == selected_release or (
isinstance(r.raw_result, dict) and
r.raw_result.get("download_url") == getattr(selected_release, "download_url", None)
):
return r
except (ImportError, AttributeError, TypeError) as e:
self.logger.debug(f"[RemoteFlacFetcher] Falling back to basic display: {e}")
# Fallback to basic display
return self._basic_interactive_select(results, artist, title)
def _basic_interactive_select(
self,
results: List[AudioSearchResult],
artist: str,
title: str,
) -> AudioSearchResult:
"""
Basic fallback for interactive selection without rich formatting.
Args:
results: List of AudioSearchResult objects
artist: The artist name being searched
title: The track title being searched
Returns:
The selected AudioSearchResult
Raises:
UserCancelledError: If user cancels selection
"""
print(f"\nFound {len(results)} releases:\n")
for i, result in enumerate(results, 1):
# Try to get lossless info from raw_result (API response)
is_lossless = False
if result.raw_result and isinstance(result.raw_result, dict):
is_lossless = result.raw_result.get("is_lossless", False)
elif result.quality:
is_lossless = "flac" in result.quality.lower() or "lossless" in result.quality.lower()
format_indicator = "[LOSSLESS]" if is_lossless else "[lossy]"
quality = f"({result.quality})" if result.quality else ""
provider = f"[{result.provider}]" if result.provider else ""
seeders = f"Seeders: {result.seeders}" if result.seeders else ""
duration = ""
if result.duration:
mins, secs = divmod(result.duration, 60)
duration = f"[{int(mins)}:{int(secs):02d}]"
print(f"{i}. {format_indicator} {provider} {result.artist}: {result.title} {quality} {duration} {seeders}")
print()
while True:
try:
choice = input(f"Select a release (1-{len(results)}, 0 to cancel): ").strip()
if choice == "0":
raise UserCancelledError("Selection cancelled by user")
choice_num = int(choice)
if 1 <= choice_num <= len(results):
selected = results[choice_num - 1]
self.logger.info(f"[RemoteFlacFetcher] User selected option {choice_num}")
return selected
else:
print(f"Please enter a number between 0 and {len(results)}")
except ValueError:
print("Please enter a valid number")
except (KeyboardInterrupt, EOFError):
print("\nCancelled")
raise UserCancelledError("Selection cancelled by user (Ctrl+C)")
# Alias for shorter name
RemoteFlacFetcher = RemoteFlacFetchAudioFetcher
def create_audio_fetcher(
logger: Optional[logging.Logger] = None,
red_api_key: Optional[str] = None,
red_api_url: Optional[str] = None,
ops_api_key: Optional[str] = None,
ops_api_url: Optional[str] = None,
flacfetch_api_url: Optional[str] = None,
flacfetch_api_key: Optional[str] = None,
) -> AudioFetcher:
"""
Factory function to create an appropriate AudioFetcher instance.
If FLACFETCH_API_URL and FLACFETCH_API_KEY environment variables are set
(or passed as arguments), returns a RemoteFlacFetchAudioFetcher that uses
the remote flacfetch HTTP API server.
Otherwise, returns a local FlacFetchAudioFetcher that uses the flacfetch
library directly.
Args:
logger: Logger instance for output
red_api_key: API key for RED tracker (optional)
red_api_url: Base URL for RED tracker API (optional, required if using RED)
ops_api_key: API key for OPS tracker (optional)
ops_api_url: Base URL for OPS tracker API (optional, required if using OPS)
red_api_key: API key for RED tracker (optional, for local mode)
red_api_url: Base URL for RED tracker API (optional, for local mode)
ops_api_key: API key for OPS tracker (optional, for local mode)
ops_api_url: Base URL for OPS tracker API (optional, for local mode)
flacfetch_api_url: URL of remote flacfetch API server (optional)
flacfetch_api_key: API key for remote flacfetch server (optional)
Returns:
An AudioFetcher instance
An AudioFetcher instance (remote or local depending on configuration)
"""
# Check for remote flacfetch API configuration
api_url = flacfetch_api_url or os.environ.get("FLACFETCH_API_URL")
api_key = flacfetch_api_key or os.environ.get("FLACFETCH_API_KEY")
if api_url and api_key:
# Use remote flacfetch API
if logger:
logger.info(f"Using remote flacfetch API at: {api_url}")
return RemoteFlacFetchAudioFetcher(
api_url=api_url,
api_key=api_key,
logger=logger,
)
elif api_url and not api_key:
if logger:
logger.warning("FLACFETCH_API_URL is set but FLACFETCH_API_KEY is not - falling back to local mode")
elif api_key and not api_url:
if logger:
logger.warning("FLACFETCH_API_KEY is set but FLACFETCH_API_URL is not - falling back to local mode")
# Use local flacfetch library
return FlacFetchAudioFetcher(
logger=logger,
red_api_key=red_api_key,
@@ -654,7 +654,31 @@ class KaraokeFinalise:
else:
self.logger.warning(f"Unsupported file extension: {current_ext}")
raise Exception("No suitable files found for processing.")
raise Exception(
"No suitable files found for processing.\n"
"\n"
"WHAT THIS MEANS:\n"
"The finalisation step requires a '(With Vocals).mkv' video file, which is created "
"during the lyrics transcription phase. This file contains the karaoke video with "
"synchronized lyrics overlay.\n"
"\n"
"COMMON CAUSES:\n"
"1. Transcription provider not configured - No AUDIOSHAKE_API_TOKEN or RUNPOD_API_KEY set\n"
"2. Transcription failed - Check logs above for API errors or timeout messages\n"
"3. Invalid API credentials - Verify your API tokens are correct and active\n"
"4. Network issues - Unable to reach transcription service\n"
"5. Running in wrong directory - Make sure you're in the track output folder\n"
"\n"
"TROUBLESHOOTING STEPS:\n"
"1. Check environment variables:\n"
" - AUDIOSHAKE_API_TOKEN (for AudioShake transcription)\n"
" - RUNPOD_API_KEY + WHISPER_RUNPOD_ID (for Whisper transcription)\n"
"2. Review the log output above for transcription errors\n"
"3. Try running with --log_level debug for more detailed output\n"
"4. If you don't need synchronized lyrics, use --skip-lyrics for instrumental-only karaoke\n"
"\n"
"See README.md 'Transcription Providers' and 'Troubleshooting' sections for more details."
)
def choose_instrumental_audio_file(self, base_name):
self.logger.info(f"Choosing instrumental audio file to use as karaoke audio...")
+84
View File
@@ -167,6 +167,76 @@ class LyricsProcessor:
return processed_lines
def _check_transcription_providers(self) -> dict:
"""
Check which transcription providers are configured and return their status.
Returns:
dict with 'configured' (list of provider names) and 'missing' (list of missing configs)
"""
load_dotenv()
configured = []
missing = []
# Check AudioShake
audioshake_token = os.getenv("AUDIOSHAKE_API_TOKEN")
if audioshake_token:
configured.append("AudioShake")
self.logger.debug("AudioShake transcription provider: configured")
else:
missing.append("AudioShake (AUDIOSHAKE_API_TOKEN)")
self.logger.debug("AudioShake transcription provider: not configured (missing AUDIOSHAKE_API_TOKEN)")
# Check Whisper via RunPod
runpod_key = os.getenv("RUNPOD_API_KEY")
whisper_id = os.getenv("WHISPER_RUNPOD_ID")
if runpod_key and whisper_id:
configured.append("Whisper (RunPod)")
self.logger.debug("Whisper transcription provider: configured")
elif runpod_key:
missing.append("Whisper (missing WHISPER_RUNPOD_ID)")
self.logger.debug("Whisper transcription provider: partially configured (missing WHISPER_RUNPOD_ID)")
elif whisper_id:
missing.append("Whisper (missing RUNPOD_API_KEY)")
self.logger.debug("Whisper transcription provider: partially configured (missing RUNPOD_API_KEY)")
else:
missing.append("Whisper (RUNPOD_API_KEY + WHISPER_RUNPOD_ID)")
self.logger.debug("Whisper transcription provider: not configured")
return {"configured": configured, "missing": missing}
def _build_transcription_provider_error_message(self, missing_providers: list) -> str:
"""Build a helpful error message when no transcription providers are configured."""
return (
"No transcription providers configured!\n"
"\n"
"Karaoke video generation requires at least one transcription provider to create "
"synchronized lyrics. Without a transcription provider, the system cannot generate "
"the word-level timing data needed for the karaoke video.\n"
"\n"
"AVAILABLE TRANSCRIPTION PROVIDERS:\n"
"\n"
"1. AudioShake (Recommended - Commercial, high-quality)\n"
" - Set environment variable: AUDIOSHAKE_API_TOKEN=your_token\n"
" - Get an API key at: https://www.audioshake.ai/\n"
"\n"
"2. Whisper via RunPod (Open-source alternative)\n"
" - Set environment variables:\n"
" RUNPOD_API_KEY=your_key\n"
" WHISPER_RUNPOD_ID=your_endpoint_id\n"
" - Set up a Whisper endpoint at: https://www.runpod.io/\n"
"\n"
"ALTERNATIVES:\n"
"\n"
"- Use --skip-lyrics flag to generate instrumental-only karaoke (no synchronized lyrics)\n"
"- Use --lyrics_file to provide pre-timed lyrics (still needs transcription for timing)\n"
"\n"
f"Missing provider configurations: {', '.join(missing_providers)}\n"
"\n"
"See README.md 'Transcription Providers' section for detailed setup instructions."
)
def transcribe_lyrics(self, input_audio_wav, artist, title, track_output_dir, lyrics_artist=None, lyrics_title=None):
"""
Transcribe lyrics for a track.
@@ -178,6 +248,9 @@ class LyricsProcessor:
track_output_dir: Output directory path
lyrics_artist: Artist name for lyrics processing (defaults to artist if None)
lyrics_title: Title for lyrics processing (defaults to title if None)
Raises:
ValueError: If transcription is enabled but no providers are configured
"""
# Use original artist/title for filename generation
filename_artist = artist
@@ -241,6 +314,17 @@ class LyricsProcessor:
"padded_audio_filepath": None, # Original padded audio may not exist
}
# Check transcription provider configuration if transcription is not being skipped
# Do this AFTER checking for existing files, since existing files don't need transcription
if not self.skip_transcription:
provider_status = self._check_transcription_providers()
if provider_status["configured"]:
self.logger.info(f"Transcription providers configured: {', '.join(provider_status['configured'])}")
else:
error_msg = self._build_transcription_provider_error_message(provider_status["missing"])
raise ValueError(error_msg)
# Create lyrics directory if it doesn't exist
os.makedirs(lyrics_dir, exist_ok=True)
self.logger.info(f"Created lyrics directory: {lyrics_dir}")
@@ -394,7 +394,24 @@ class LyricsTranscriber:
def transcribe(self) -> None:
"""Run transcription using all available transcribers."""
self.logger.info(f"Starting transcription with providers: {list(self.transcribers.keys())}")
provider_names = list(self.transcribers.keys())
if not provider_names:
self.logger.warning(
"Starting transcription with providers: [] - NO TRANSCRIPTION PROVIDERS CONFIGURED!\n"
"\n"
"This means no word-level timing data will be generated, and synchronized karaoke "
"lyrics cannot be created. The output will lack the '(With Vocals).mkv' video file.\n"
"\n"
"To enable transcription, configure at least one provider:\n"
" - AudioShake: Set AUDIOSHAKE_API_TOKEN environment variable\n"
" - Whisper/RunPod: Set RUNPOD_API_KEY and WHISPER_RUNPOD_ID environment variables\n"
"\n"
"See README.md 'Transcription Providers' section for detailed setup instructions."
)
else:
self.logger.info(f"Starting transcription with providers: {provider_names}")
self._log_provider_configuration_status()
for name, transcriber_info in self.transcribers.items():
self.logger.info(f"Running transcription with {name}")
@@ -407,7 +424,33 @@ class LyricsTranscriber:
self.logger.debug(f"Transcription completed for {name}")
if not self.results.transcription_results:
self.logger.warning("No successful transcriptions from any provider")
self.logger.warning(
"No successful transcriptions from any provider. "
"Check that your API tokens are valid and the services are accessible."
)
def _log_provider_configuration_status(self) -> None:
"""Log detailed configuration status for each potential transcription provider."""
self.logger.debug("Transcription provider configuration status:")
# AudioShake status
if self.transcriber_config.audioshake_api_token:
self.logger.debug(" - AudioShake: CONFIGURED (API token provided)")
else:
self.logger.debug(" - AudioShake: NOT CONFIGURED (missing AUDIOSHAKE_API_TOKEN)")
# Whisper/RunPod status
has_runpod_key = bool(self.transcriber_config.runpod_api_key)
has_whisper_id = bool(self.transcriber_config.whisper_runpod_id)
if has_runpod_key and has_whisper_id:
self.logger.debug(" - Whisper (RunPod): CONFIGURED (API key and endpoint ID provided)")
elif has_runpod_key:
self.logger.debug(" - Whisper (RunPod): PARTIALLY CONFIGURED (missing WHISPER_RUNPOD_ID)")
elif has_whisper_id:
self.logger.debug(" - Whisper (RunPod): PARTIALLY CONFIGURED (missing RUNPOD_API_KEY)")
else:
self.logger.debug(" - Whisper (RunPod): NOT CONFIGURED (missing RUNPOD_API_KEY and WHISPER_RUNPOD_ID)")
def correct_lyrics(self) -> None:
"""Run lyrics correction using transcription and internet lyrics."""
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.75.33"
version = "0.75.37"
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"
+733 -2
View File
@@ -1,7 +1,8 @@
"""
Unit tests for audio_fetcher module.
Tests cover the AudioFetcher abstraction layer and FlacFetchAudioFetcher implementation.
Tests cover the AudioFetcher abstraction layer, FlacFetchAudioFetcher implementation,
and RemoteFlacFetchAudioFetcher for remote API access.
"""
import pytest
@@ -19,7 +20,9 @@ from karaoke_gen.audio_fetcher import (
DownloadError,
UserCancelledError,
FlacFetchAudioFetcher,
RemoteFlacFetchAudioFetcher,
create_audio_fetcher,
HTTPX_AVAILABLE,
)
import karaoke_gen.audio_fetcher as audio_fetcher_module
@@ -944,11 +947,13 @@ class TestFlacFetcherAlias:
class TestCreateAudioFetcher:
"""Tests for create_audio_fetcher factory function."""
@patch.dict(os.environ, {"FLACFETCH_API_URL": "", "FLACFETCH_API_KEY": ""}, clear=False)
def test_creates_flacfetch_fetcher(self):
"""Test factory creates FlacFetchAudioFetcher."""
"""Test factory creates FlacFetchAudioFetcher when no remote config."""
fetcher = create_audio_fetcher()
assert isinstance(fetcher, FlacFetchAudioFetcher)
@patch.dict(os.environ, {"FLACFETCH_API_URL": "", "FLACFETCH_API_KEY": ""}, clear=False)
def test_passes_parameters(self):
"""Test factory passes parameters to constructor."""
logger = MagicMock()
@@ -1650,3 +1655,729 @@ class TestTransmissionCleanup:
fetcher._cleanup_transmission_torrents(mock_selected)
mock_constructor.assert_called_once_with(host='remote-host', port=9999, timeout=5)
# ============================================================================
# Tests for RemoteFlacFetchAudioFetcher
# ============================================================================
class TestRemoteFlacFetchAudioFetcherInit:
"""Tests for RemoteFlacFetchAudioFetcher initialization."""
def test_init_with_required_params(self):
"""Test initialization with required API URL and key."""
fetcher = RemoteFlacFetchAudioFetcher(
api_url="http://localhost:8080",
api_key="test_key",
)
assert fetcher.api_url == "http://localhost:8080"
assert fetcher.api_key == "test_key"
assert fetcher.timeout == 60
assert fetcher.download_timeout == 600
def test_init_strips_trailing_slash_from_url(self):
"""Test that trailing slashes are removed from API URL."""
fetcher = RemoteFlacFetchAudioFetcher(
api_url="http://localhost:8080/",
api_key="test_key",
)
assert fetcher.api_url == "http://localhost:8080"
def test_init_with_custom_timeouts(self):
"""Test initialization with custom timeout values."""
fetcher = RemoteFlacFetchAudioFetcher(
api_url="http://localhost:8080",
api_key="test_key",
timeout=30,
download_timeout=300,
)
assert fetcher.timeout == 30
assert fetcher.download_timeout == 300
def test_init_with_custom_logger(self):
"""Test initialization with custom logger."""
logger = MagicMock(spec=logging.Logger)
fetcher = RemoteFlacFetchAudioFetcher(
api_url="http://localhost:8080",
api_key="test_key",
logger=logger,
)
assert fetcher.logger == logger
@pytest.mark.skipif(not HTTPX_AVAILABLE, reason="httpx not installed")
class TestRemoteFlacFetcherSearch:
"""Tests for RemoteFlacFetchAudioFetcher search functionality."""
@pytest.fixture
def fetcher(self):
"""Create a RemoteFlacFetchAudioFetcher instance."""
return RemoteFlacFetchAudioFetcher(
api_url="http://localhost:8080",
api_key="test_key",
)
@patch('httpx.Client')
def test_search_success(self, mock_client_class, fetcher):
"""Test successful search returns AudioSearchResult objects."""
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json.return_value = {
"search_id": "abc123",
"results": [
{
"title": "Test Song",
"artist": "Test Artist",
"provider": "YouTube",
"download_url": "https://example.com/song",
"duration_seconds": 180,
"quality_str": "320kbps",
},
{
"title": "Test Song",
"artist": "Test Artist",
"provider": "RED",
"download_url": "https://example.com/flac",
"duration_seconds": 180,
"quality_str": "FLAC 16bit",
"seeders": 50,
},
],
}
mock_response.raise_for_status = MagicMock()
mock_client = MagicMock()
mock_client.__enter__ = MagicMock(return_value=mock_client)
mock_client.__exit__ = MagicMock(return_value=False)
mock_client.post.return_value = mock_response
mock_client_class.return_value = mock_client
results = fetcher.search("Test Artist", "Test Song")
assert len(results) == 2
assert results[0].title == "Test Song"
assert results[0].provider == "YouTube"
assert results[0].index == 0
assert results[1].provider == "RED"
assert results[1].index == 1
assert results[1].seeders == 50
@patch('httpx.Client')
def test_search_no_results(self, mock_client_class, fetcher):
"""Test search raises NoResultsError when API returns 404."""
import httpx
mock_response = MagicMock()
mock_response.status_code = 404
mock_client = MagicMock()
mock_client.__enter__ = MagicMock(return_value=mock_client)
mock_client.__exit__ = MagicMock(return_value=False)
mock_client.post.return_value = mock_response
mock_client_class.return_value = mock_client
with pytest.raises(NoResultsError):
fetcher.search("Unknown Artist", "Unknown Song")
@patch('httpx.Client')
def test_search_empty_results(self, mock_client_class, fetcher):
"""Test search raises NoResultsError when results list is empty."""
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json.return_value = {
"search_id": "abc123",
"results": [],
}
mock_response.raise_for_status = MagicMock()
mock_client = MagicMock()
mock_client.__enter__ = MagicMock(return_value=mock_client)
mock_client.__exit__ = MagicMock(return_value=False)
mock_client.post.return_value = mock_response
mock_client_class.return_value = mock_client
with pytest.raises(NoResultsError):
fetcher.search("Artist", "Song")
@patch('httpx.Client')
def test_search_stores_search_id(self, mock_client_class, fetcher):
"""Test search stores search_id for subsequent download."""
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json.return_value = {
"search_id": "stored_id_123",
"results": [{"title": "Song", "artist": "Artist", "provider": "YouTube"}],
}
mock_response.raise_for_status = MagicMock()
mock_client = MagicMock()
mock_client.__enter__ = MagicMock(return_value=mock_client)
mock_client.__exit__ = MagicMock(return_value=False)
mock_client.post.return_value = mock_response
mock_client_class.return_value = mock_client
fetcher.search("Artist", "Song")
assert fetcher._last_search_id == "stored_id_123"
@pytest.mark.skipif(not HTTPX_AVAILABLE, reason="httpx not installed")
class TestRemoteFlacFetcherDownload:
"""Tests for RemoteFlacFetchAudioFetcher download functionality."""
@pytest.fixture
def fetcher(self):
"""Create a RemoteFlacFetchAudioFetcher instance with search completed."""
f = RemoteFlacFetchAudioFetcher(
api_url="http://localhost:8080",
api_key="test_key",
)
f._last_search_id = "search123"
return f
def test_download_without_search_raises_error(self):
"""Test download raises DownloadError if search wasn't called first."""
fetcher = RemoteFlacFetchAudioFetcher(
api_url="http://localhost:8080",
api_key="test_key",
)
search_result = AudioSearchResult(
title="Song", artist="Artist", url="url", provider="YouTube", index=0,
)
with pytest.raises(DownloadError, match="No search performed"):
fetcher.download(search_result, "/tmp")
@patch.object(RemoteFlacFetchAudioFetcher, '_wait_and_stream_download')
@patch('httpx.Client')
def test_download_success(self, mock_client_class, mock_wait_stream, fetcher, tmp_path):
"""Test successful download returns AudioFetchResult."""
# Mock download initiation
mock_response = MagicMock()
mock_response.json.return_value = {"download_id": "dl123"}
mock_response.raise_for_status = MagicMock()
mock_client = MagicMock()
mock_client.__enter__ = MagicMock(return_value=mock_client)
mock_client.__exit__ = MagicMock(return_value=False)
mock_client.post.return_value = mock_response
mock_client_class.return_value = mock_client
# Mock wait and stream
downloaded_path = str(tmp_path / "song.flac")
mock_wait_stream.return_value = downloaded_path
search_result = AudioSearchResult(
title="Test Song",
artist="Test Artist",
url="https://example.com/song",
provider="RED",
duration=180,
quality="FLAC",
index=0,
)
result = fetcher.download(search_result, str(tmp_path))
assert result.filepath == downloaded_path
assert result.artist == "Test Artist"
assert result.title == "Test Song"
assert result.provider == "RED"
@patch.object(RemoteFlacFetchAudioFetcher, '_wait_and_stream_download')
@patch('httpx.Client')
def test_download_with_custom_filename(self, mock_client_class, mock_wait_stream, fetcher, tmp_path):
"""Test download uses custom filename when provided."""
mock_response = MagicMock()
mock_response.json.return_value = {"download_id": "dl123"}
mock_response.raise_for_status = MagicMock()
mock_client = MagicMock()
mock_client.__enter__ = MagicMock(return_value=mock_client)
mock_client.__exit__ = MagicMock(return_value=False)
mock_client.post.return_value = mock_response
mock_client_class.return_value = mock_client
mock_wait_stream.return_value = str(tmp_path / "custom.flac")
search_result = AudioSearchResult(
title="Song", artist="Artist", url="url", provider="YouTube", index=0,
)
fetcher.download(search_result, str(tmp_path), output_filename="custom_name")
# Verify custom filename was sent to API
call_args = mock_client.post.call_args
assert call_args[1]["json"]["output_filename"] == "custom_name"
@pytest.mark.skipif(not HTTPX_AVAILABLE, reason="httpx not installed")
class TestRemoteFlacFetcherSelectBest:
"""Tests for RemoteFlacFetchAudioFetcher select_best functionality."""
@pytest.fixture
def fetcher(self):
"""Create a RemoteFlacFetchAudioFetcher instance."""
return RemoteFlacFetchAudioFetcher(
api_url="http://localhost:8080",
api_key="test_key",
)
def test_select_best_prefers_flac(self, fetcher):
"""Test select_best prefers FLAC quality over lossy."""
results = [
AudioSearchResult(
title="Song", artist="Artist", url="url1", provider="YouTube",
quality="320kbps", index=0,
),
AudioSearchResult(
title="Song", artist="Artist", url="url2", provider="RED",
quality="FLAC 16bit", index=1,
),
]
best_index = fetcher.select_best(results)
assert best_index == 1 # FLAC should win
def test_select_best_prefers_lossless_keyword(self, fetcher):
"""Test select_best recognizes 'lossless' keyword."""
results = [
AudioSearchResult(
title="Song", artist="Artist", url="url1", provider="YouTube",
quality="256kbps", index=0,
),
AudioSearchResult(
title="Song", artist="Artist", url="url2", provider="OPS",
quality="Lossless CD", index=1,
),
]
best_index = fetcher.select_best(results)
assert best_index == 1
def test_select_best_considers_seeders(self, fetcher):
"""Test select_best considers seeder count."""
results = [
AudioSearchResult(
title="Song", artist="Artist", url="url1", provider="RED",
quality="FLAC", seeders=5, index=0,
),
AudioSearchResult(
title="Song", artist="Artist", url="url2", provider="RED",
quality="FLAC", seeders=50, index=1,
),
]
best_index = fetcher.select_best(results)
assert best_index == 1 # More seeders
def test_select_best_prefers_non_youtube(self, fetcher):
"""Test select_best prefers tracker sources over YouTube."""
results = [
AudioSearchResult(
title="Song", artist="Artist", url="url1", provider="YouTube",
quality="320kbps", index=0,
),
AudioSearchResult(
title="Song", artist="Artist", url="url2", provider="RED",
quality="320kbps", index=1,
),
]
best_index = fetcher.select_best(results)
assert best_index == 1 # Non-YouTube preferred
def test_select_best_empty_list(self, fetcher):
"""Test select_best returns 0 for empty list."""
assert fetcher.select_best([]) == 0
def test_select_best_handles_none_quality(self, fetcher):
"""Test select_best handles results with None quality."""
results = [
AudioSearchResult(
title="Song", artist="Artist", url="url", provider="YouTube",
quality=None, index=0,
),
]
# Should not raise
best_index = fetcher.select_best(results)
assert best_index == 0
@pytest.mark.skipif(not HTTPX_AVAILABLE, reason="httpx not installed")
class TestRemoteFlacFetcherSearchAndDownload:
"""Tests for RemoteFlacFetchAudioFetcher search_and_download functionality."""
@pytest.fixture
def fetcher(self):
"""Create a RemoteFlacFetchAudioFetcher instance."""
return RemoteFlacFetchAudioFetcher(
api_url="http://localhost:8080",
api_key="test_key",
)
@patch.object(RemoteFlacFetchAudioFetcher, 'download')
@patch.object(RemoteFlacFetchAudioFetcher, 'search')
def test_search_and_download_auto_select(self, mock_search, mock_download, fetcher, tmp_path):
"""Test search_and_download with auto_select=True."""
# Mock search results
mock_search.return_value = [
AudioSearchResult(
title="Song", artist="Artist", url="url1", provider="YouTube",
quality="320kbps", index=0,
),
AudioSearchResult(
title="Song", artist="Artist", url="url2", provider="RED",
quality="FLAC", index=1,
),
]
# Mock download
mock_download.return_value = AudioFetchResult(
filepath="/path/to/song.flac",
artist="Artist",
title="Song",
provider="RED",
)
result = fetcher.search_and_download(
artist="Artist",
title="Song",
output_dir=str(tmp_path),
auto_select=True,
)
# Should auto-select FLAC (index 1)
mock_download.assert_called_once()
selected = mock_download.call_args[0][0]
assert selected.quality == "FLAC"
@patch.object(RemoteFlacFetchAudioFetcher, 'download')
@patch.object(RemoteFlacFetchAudioFetcher, '_interactive_select')
@patch.object(RemoteFlacFetchAudioFetcher, 'search')
def test_search_and_download_interactive(self, mock_search, mock_interactive, mock_download, fetcher, tmp_path):
"""Test search_and_download with interactive selection."""
results = [
AudioSearchResult(
title="Song", artist="Artist", url="url", provider="YouTube", index=0,
),
]
mock_search.return_value = results
mock_interactive.return_value = results[0]
mock_download.return_value = AudioFetchResult(
filepath="/path/to/song.mp3",
artist="Artist",
title="Song",
provider="YouTube",
)
fetcher.search_and_download(
artist="Artist",
title="Song",
output_dir=str(tmp_path),
auto_select=False,
)
mock_interactive.assert_called_once()
@pytest.mark.skipif(not HTTPX_AVAILABLE, reason="httpx not installed")
class TestRemoteFlacFetcherConvertApiResult:
"""Tests for RemoteFlacFetchAudioFetcher._convert_api_result_for_release method."""
@pytest.fixture
def fetcher(self):
"""Create a RemoteFlacFetchAudioFetcher instance."""
return RemoteFlacFetchAudioFetcher(
api_url="http://localhost:8080",
api_key="test_key",
)
def test_maps_provider_to_source_name(self, fetcher):
"""Test that provider field is mapped to source_name."""
api_result = {
"provider": "RED",
"title": "Test Song",
"artist": "Test Artist",
"quality": "FLAC 16bit CD",
"quality_data": {"format": "FLAC", "bit_depth": 16, "media": "CD"},
}
converted = fetcher._convert_api_result_for_release(api_result)
assert converted["source_name"] == "RED"
assert converted["provider"] == "RED" # Original preserved
def test_maps_quality_data_to_quality(self, fetcher):
"""Test that quality_data is mapped to quality dict for Release.from_dict()."""
api_result = {
"provider": "OPS",
"title": "Test Song",
"quality": "FLAC 24bit WEB",
"quality_data": {"format": "FLAC", "bit_depth": 24, "media": "WEB", "sample_rate": 96000},
}
converted = fetcher._convert_api_result_for_release(api_result)
assert isinstance(converted["quality"], dict)
assert converted["quality"]["format"] == "FLAC"
assert converted["quality"]["bit_depth"] == 24
assert converted["quality"]["media"] == "WEB"
assert converted["quality"]["sample_rate"] == 96000
def test_stores_original_quality_as_quality_str(self, fetcher):
"""Test that original quality string is stored as quality_str."""
api_result = {
"provider": "RED",
"quality": "FLAC 16bit CD",
"quality_data": {"format": "FLAC", "bit_depth": 16, "media": "CD"},
}
converted = fetcher._convert_api_result_for_release(api_result)
assert converted["quality_str"] == "FLAC 16bit CD"
def test_handles_missing_quality_data(self, fetcher):
"""Test fallback when quality_data is missing."""
api_result = {
"provider": "YouTube",
"quality": "MP3 320kbps",
# No quality_data
}
converted = fetcher._convert_api_result_for_release(api_result)
assert isinstance(converted["quality"], dict)
assert converted["quality"]["format"] == "MP3"
assert converted["quality_str"] == "MP3 320kbps"
def test_handles_none_quality_data(self, fetcher):
"""Test fallback when quality_data is None."""
api_result = {
"provider": "YouTube",
"quality": "FLAC",
"quality_data": None,
}
converted = fetcher._convert_api_result_for_release(api_result)
assert isinstance(converted["quality"], dict)
assert converted["quality"]["format"] == "FLAC"
def test_parses_flac_from_quality_string(self, fetcher):
"""Test that FLAC format is parsed from quality string."""
api_result = {"provider": "Unknown", "quality": "FLAC 16bit"}
converted = fetcher._convert_api_result_for_release(api_result)
assert converted["quality"]["format"] == "FLAC"
def test_parses_mp3_from_quality_string(self, fetcher):
"""Test that MP3 format is parsed from quality string."""
api_result = {"provider": "Unknown", "quality": "MP3 320kbps"}
converted = fetcher._convert_api_result_for_release(api_result)
assert converted["quality"]["format"] == "MP3"
def test_parses_media_from_quality_string(self, fetcher):
"""Test that media type is parsed from quality string."""
api_result = {"provider": "Unknown", "quality": "FLAC CD"}
converted = fetcher._convert_api_result_for_release(api_result)
assert converted["quality"]["media"] == "CD"
def test_parses_web_media_from_quality_string(self, fetcher):
"""Test that WEB media type is parsed from quality string."""
api_result = {"provider": "Unknown", "quality": "FLAC WEB"}
converted = fetcher._convert_api_result_for_release(api_result)
assert converted["quality"]["media"] == "WEB"
def test_preserves_is_lossless_flag(self, fetcher):
"""Test that is_lossless flag is preserved from API result."""
api_result = {
"provider": "RED",
"quality": "FLAC 16bit CD",
"quality_data": {"format": "FLAC"},
"is_lossless": True,
}
converted = fetcher._convert_api_result_for_release(api_result)
assert converted["is_lossless"] is True
def test_does_not_modify_original(self, fetcher):
"""Test that original dict is not modified."""
api_result = {
"provider": "RED",
"quality": "FLAC 16bit CD",
}
original_quality = api_result["quality"]
converted = fetcher._convert_api_result_for_release(api_result)
# Original should not have source_name added
assert "source_name" not in api_result
assert api_result["quality"] == original_quality
def test_handles_youtube_result(self, fetcher):
"""Test conversion of YouTube-style API result."""
api_result = {
"provider": "YouTube",
"title": "Test Video",
"artist": "Test Channel",
"channel": "Test Channel",
"quality": "MP3 320kbps",
"quality_data": {"format": "MP3", "bitrate": 320},
"is_lossless": False,
"view_count": 1000000,
"duration_seconds": 180,
}
converted = fetcher._convert_api_result_for_release(api_result)
assert converted["source_name"] == "YouTube"
assert converted["quality"]["format"] == "MP3"
assert converted["quality"]["bitrate"] == 320
assert converted["channel"] == "Test Channel"
assert converted["view_count"] == 1000000
@pytest.mark.skipif(not HTTPX_AVAILABLE, reason="httpx not installed")
class TestRemoteFlacFetcherInteractiveSelect:
"""Tests for RemoteFlacFetchAudioFetcher interactive selection."""
@pytest.fixture
def fetcher(self):
"""Create a RemoteFlacFetchAudioFetcher instance."""
return RemoteFlacFetchAudioFetcher(
api_url="http://localhost:8080",
api_key="test_key",
)
@patch('builtins.input', return_value='1')
def test_basic_interactive_select_success(self, mock_input, fetcher, capsys):
"""Test basic interactive selection returns selected result."""
results = [
AudioSearchResult(
title="Song 1", artist="Artist", url="url1", provider="YouTube",
quality="320kbps", index=0,
),
AudioSearchResult(
title="Song 2", artist="Artist", url="url2", provider="RED",
quality="FLAC", index=1,
),
]
selected = fetcher._basic_interactive_select(results, "Artist", "Song")
assert selected == results[0]
# Check output shows options
captured = capsys.readouterr()
assert "Found 2 releases" in captured.out
@patch('builtins.input', return_value='0')
def test_basic_interactive_select_cancel(self, mock_input, fetcher):
"""Test interactive selection raises UserCancelledError on cancel."""
results = [
AudioSearchResult(
title="Song", artist="Artist", url="url", provider="YouTube", index=0,
),
]
with pytest.raises(UserCancelledError):
fetcher._basic_interactive_select(results, "Artist", "Song")
@patch('builtins.input', side_effect=KeyboardInterrupt)
def test_basic_interactive_select_keyboard_interrupt(self, mock_input, fetcher):
"""Test interactive selection handles Ctrl+C."""
results = [
AudioSearchResult(
title="Song", artist="Artist", url="url", provider="YouTube", index=0,
),
]
with pytest.raises(UserCancelledError):
fetcher._basic_interactive_select(results, "Artist", "Song")
class TestRemoteFlacFetcherAlias:
"""Tests for RemoteFlacFetcher alias."""
def test_remote_flacfetcher_alias_exists(self):
"""Test RemoteFlacFetcher alias is available."""
from karaoke_gen.audio_fetcher import RemoteFlacFetcher
assert RemoteFlacFetcher is not None
def test_remote_flacfetcher_is_remoteflacfetchaudiofetcher(self):
"""Test RemoteFlacFetcher is the same as RemoteFlacFetchAudioFetcher."""
from karaoke_gen.audio_fetcher import RemoteFlacFetcher
assert RemoteFlacFetcher is RemoteFlacFetchAudioFetcher
class TestCreateAudioFetcherRemoteSelection:
"""Tests for create_audio_fetcher factory selecting remote vs local."""
@patch.dict(os.environ, {"FLACFETCH_API_URL": "http://localhost:8080", "FLACFETCH_API_KEY": "test_key"})
def test_creates_remote_fetcher_from_env(self):
"""Test factory creates RemoteFlacFetchAudioFetcher when env vars are set."""
fetcher = create_audio_fetcher()
assert isinstance(fetcher, RemoteFlacFetchAudioFetcher)
assert fetcher.api_url == "http://localhost:8080"
assert fetcher.api_key == "test_key"
def test_creates_remote_fetcher_from_args(self):
"""Test factory creates RemoteFlacFetchAudioFetcher when args are passed."""
fetcher = create_audio_fetcher(
flacfetch_api_url="http://custom:8080",
flacfetch_api_key="custom_key",
)
assert isinstance(fetcher, RemoteFlacFetchAudioFetcher)
assert fetcher.api_url == "http://custom:8080"
assert fetcher.api_key == "custom_key"
@patch.dict(os.environ, {"FLACFETCH_API_URL": "http://localhost:8080"}, clear=False)
def test_falls_back_to_local_without_api_key(self):
"""Test factory falls back to local when only URL is set."""
# Clear FLACFETCH_API_KEY if it exists
with patch.dict(os.environ, {"FLACFETCH_API_KEY": ""}, clear=False):
fetcher = create_audio_fetcher()
assert isinstance(fetcher, FlacFetchAudioFetcher)
@patch.dict(os.environ, {"FLACFETCH_API_KEY": "test_key"}, clear=False)
def test_falls_back_to_local_without_api_url(self):
"""Test factory falls back to local when only key is set."""
# Clear FLACFETCH_API_URL if it exists
with patch.dict(os.environ, {"FLACFETCH_API_URL": ""}, clear=False):
fetcher = create_audio_fetcher()
assert isinstance(fetcher, FlacFetchAudioFetcher)
@patch.dict(os.environ, {}, clear=True)
def test_creates_local_fetcher_by_default(self):
"""Test factory creates local fetcher when no remote config."""
fetcher = create_audio_fetcher()
assert isinstance(fetcher, FlacFetchAudioFetcher)
@patch.dict(os.environ, {"FLACFETCH_API_URL": "http://localhost:8080", "FLACFETCH_API_KEY": "test_key"})
def test_remote_fetcher_gets_logger(self):
"""Test factory passes logger to remote fetcher."""
logger = MagicMock(spec=logging.Logger)
fetcher = create_audio_fetcher(logger=logger)
assert isinstance(fetcher, RemoteFlacFetchAudioFetcher)
assert fetcher.logger == logger
def test_args_override_env_vars(self):
"""Test explicit args override environment variables."""
with patch.dict(os.environ, {"FLACFETCH_API_URL": "http://env:8080", "FLACFETCH_API_KEY": "env_key"}):
fetcher = create_audio_fetcher(
flacfetch_api_url="http://arg:9090",
flacfetch_api_key="arg_key",
)
assert isinstance(fetcher, RemoteFlacFetchAudioFetcher)
assert fetcher.api_url == "http://arg:9090"
assert fetcher.api_key == "arg_key"
+4 -2
View File
@@ -224,7 +224,8 @@ class TestLyricsProcessorIntegration:
patch('os.path.exists', return_value=False), \
patch('os.makedirs'), \
patch('shutil.copy2'), \
patch('karaoke_gen.lyrics_processor.load_dotenv'):
patch('karaoke_gen.lyrics_processor.load_dotenv'), \
patch.dict(os.environ, {"AUDIOSHAKE_API_TOKEN": "test_token"}):
mock_transcriber_instance = MagicMock()
mock_transcriber_instance.process.return_value = mock_result
@@ -258,7 +259,8 @@ class TestLyricsProcessorIntegration:
patch('os.path.exists', return_value=False), \
patch('os.makedirs'), \
patch('shutil.copy2'), \
patch('karaoke_gen.lyrics_processor.load_dotenv'):
patch('karaoke_gen.lyrics_processor.load_dotenv'), \
patch.dict(os.environ, {"AUDIOSHAKE_API_TOKEN": "test_token"}):
mock_transcriber_instance = MagicMock()
mock_transcriber_instance.process.return_value = mock_result
+152
View File
@@ -315,3 +315,155 @@ class TestLyrics:
with pytest.raises(Exception, match=f"No input audio file found in {track_output_dir}"):
basic_karaoke_gen.file_handler.backup_existing_outputs(track_output_dir, artist, title)
class TestTranscriptionProviderValidation:
"""Tests for transcription provider validation and error messaging."""
def test_check_transcription_providers_audioshake_configured(self, basic_karaoke_gen):
"""Test provider check when AudioShake is configured."""
with patch.dict(os.environ, {"AUDIOSHAKE_API_TOKEN": "test_token"}, clear=False), \
patch('karaoke_gen.lyrics_processor.load_dotenv'):
result = basic_karaoke_gen.lyrics_processor._check_transcription_providers()
assert "AudioShake" in result["configured"]
def test_check_transcription_providers_whisper_configured(self, basic_karaoke_gen):
"""Test provider check when Whisper is configured."""
with patch.dict(os.environ, {"RUNPOD_API_KEY": "test_key", "WHISPER_RUNPOD_ID": "test_id"}, clear=False), \
patch('karaoke_gen.lyrics_processor.load_dotenv'):
result = basic_karaoke_gen.lyrics_processor._check_transcription_providers()
assert "Whisper (RunPod)" in result["configured"]
def test_check_transcription_providers_both_configured(self, basic_karaoke_gen):
"""Test provider check when both providers are configured."""
with patch.dict(os.environ, {
"AUDIOSHAKE_API_TOKEN": "test_token",
"RUNPOD_API_KEY": "test_key",
"WHISPER_RUNPOD_ID": "test_id"
}, clear=False), \
patch('karaoke_gen.lyrics_processor.load_dotenv'):
result = basic_karaoke_gen.lyrics_processor._check_transcription_providers()
assert "AudioShake" in result["configured"]
assert "Whisper (RunPod)" in result["configured"]
def test_check_transcription_providers_none_configured(self, basic_karaoke_gen):
"""Test provider check when no providers are configured."""
with patch.dict(os.environ, {}, clear=True), \
patch('karaoke_gen.lyrics_processor.load_dotenv'):
result = basic_karaoke_gen.lyrics_processor._check_transcription_providers()
assert len(result["configured"]) == 0
assert len(result["missing"]) > 0
def test_check_transcription_providers_whisper_partial_key_only(self, basic_karaoke_gen):
"""Test provider check when only RunPod API key is set."""
with patch.dict(os.environ, {"RUNPOD_API_KEY": "test_key"}, clear=True), \
patch('karaoke_gen.lyrics_processor.load_dotenv'):
result = basic_karaoke_gen.lyrics_processor._check_transcription_providers()
assert "Whisper (RunPod)" not in result["configured"]
# Should show partial configuration message
assert any("WHISPER_RUNPOD_ID" in msg for msg in result["missing"])
def test_check_transcription_providers_whisper_partial_id_only(self, basic_karaoke_gen):
"""Test provider check when only Whisper RunPod ID is set."""
with patch.dict(os.environ, {"WHISPER_RUNPOD_ID": "test_id"}, clear=True), \
patch('karaoke_gen.lyrics_processor.load_dotenv'):
result = basic_karaoke_gen.lyrics_processor._check_transcription_providers()
assert "Whisper (RunPod)" not in result["configured"]
# Should show partial configuration message
assert any("RUNPOD_API_KEY" in msg for msg in result["missing"])
def test_build_transcription_provider_error_message(self, basic_karaoke_gen):
"""Test error message building."""
missing = ["AudioShake (AUDIOSHAKE_API_TOKEN)", "Whisper (RUNPOD_API_KEY + WHISPER_RUNPOD_ID)"]
error_msg = basic_karaoke_gen.lyrics_processor._build_transcription_provider_error_message(missing)
# Check key elements are in the message
assert "No transcription providers configured" in error_msg
assert "AudioShake" in error_msg
assert "Whisper" in error_msg
assert "AUDIOSHAKE_API_TOKEN" in error_msg
assert "RUNPOD_API_KEY" in error_msg
assert "--skip-lyrics" in error_msg
assert "README.md" in error_msg
def test_transcribe_lyrics_raises_when_no_providers(self, basic_karaoke_gen, temp_dir):
"""Test that transcribe_lyrics raises ValueError when no providers configured."""
track_output_dir = os.path.join(temp_dir, "track")
os.makedirs(track_output_dir, exist_ok=True)
# Make sure skip_transcription is False
basic_karaoke_gen.lyrics_processor.skip_transcription = False
with patch.dict(os.environ, {}, clear=True), \
patch('os.path.exists', return_value=False), \
patch('karaoke_gen.lyrics_processor.load_dotenv'):
with pytest.raises(ValueError, match="No transcription providers configured"):
basic_karaoke_gen.lyrics_processor.transcribe_lyrics(
"/path/to/audio.wav", "Artist", "Title", track_output_dir
)
def test_transcribe_lyrics_skips_validation_when_files_exist(self, basic_karaoke_gen, temp_dir):
"""Test that existing files bypass provider validation."""
track_output_dir = os.path.join(temp_dir, "track")
os.makedirs(track_output_dir, exist_ok=True)
artist = "Test Artist"
title = "Test Title"
sanitized_artist = sanitize_filename(artist)
sanitized_title = sanitize_filename(title)
# Create existing files
parent_video_path = os.path.join(track_output_dir, f"{sanitized_artist} - {sanitized_title} (With Vocals).mkv")
parent_lrc_path = os.path.join(track_output_dir, f"{sanitized_artist} - {sanitized_title} (Karaoke).lrc")
with open(parent_video_path, "w") as f:
f.write("mock video")
with open(parent_lrc_path, "w") as f:
f.write("[00:01.00]Test lyrics")
# No providers configured, but existing files should work
with patch.dict(os.environ, {}, clear=True), \
patch('karaoke_gen.lyrics_processor.load_dotenv'):
# Should NOT raise - existing files bypass validation
result = basic_karaoke_gen.lyrics_processor.transcribe_lyrics(
"/path/to/audio.wav", artist, title, track_output_dir
)
assert result["lrc_filepath"] == parent_lrc_path
assert result["ass_filepath"] == parent_video_path
def test_transcribe_lyrics_skips_validation_when_transcription_disabled(self, basic_karaoke_gen, temp_dir):
"""Test that provider validation is skipped when skip_transcription=True."""
track_output_dir = os.path.join(temp_dir, "track")
os.makedirs(track_output_dir, exist_ok=True)
# Set skip_transcription to True
basic_karaoke_gen.lyrics_processor.skip_transcription = True
# Mock the LyricsTranscriber
mock_result = MagicMock()
mock_result.lrc_filepath = "/path/to/output.lrc"
mock_result.ass_filepath = None
mock_result.video_filepath = None
mock_result.transcription_corrected = None
with patch.dict(os.environ, {}, clear=True), \
patch('os.path.exists', return_value=False), \
patch('os.makedirs'), \
patch('shutil.copy2'), \
patch('karaoke_gen.lyrics_processor.load_dotenv'), \
patch('karaoke_gen.lyrics_processor.LyricsTranscriber') as mock_transcriber:
mock_instance = MagicMock()
mock_instance.process.return_value = mock_result
mock_transcriber.return_value = mock_instance
# Should NOT raise - skip_transcription bypasses validation
result = basic_karaoke_gen.lyrics_processor.transcribe_lyrics(
"/path/to/audio.wav", "Artist", "Title", track_output_dir
)
# Verify transcriber was called
mock_transcriber.assert_called_once()