mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-24 08:05:00 +09:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f99d6c1fb4 | ||
|
|
f8a45bfbd2 |
No files matched your search
@@ -1,54 +1,79 @@
|
||||
"""
|
||||
Audio search service for finding and downloading audio files.
|
||||
|
||||
This service integrates with karaoke_gen.audio_fetcher (which wraps flacfetch)
|
||||
to search for audio from various sources (YouTube, music trackers, etc.)
|
||||
and download the selected audio file.
|
||||
|
||||
This is a thin wrapper that adds backend-specific functionality:
|
||||
- Caching raw results for API-based selection flow
|
||||
- Firestore-compatible serialization
|
||||
- Singleton pattern for service lifecycle
|
||||
This service integrates with flacfetch to search for audio from various sources
|
||||
(YouTube, music trackers, etc.) and download the selected audio file.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
from typing import List, Optional
|
||||
|
||||
# Import shared classes from karaoke_gen.audio_fetcher - single source of truth
|
||||
# Note: Import directly from audio_fetcher module, not karaoke_gen.__init__
|
||||
# to avoid pulling in heavier dependencies like lyrics_transcriber
|
||||
from karaoke_gen.audio_fetcher import (
|
||||
FlacFetcher,
|
||||
AudioSearchResult,
|
||||
AudioFetchResult,
|
||||
AudioFetcherError,
|
||||
NoResultsError,
|
||||
DownloadError,
|
||||
)
|
||||
import tempfile
|
||||
from dataclasses import dataclass, asdict
|
||||
from typing import List, Optional, Dict, Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# Re-export exception under backend's naming convention for compatibility
|
||||
AudioSearchError = AudioFetcherError
|
||||
@dataclass
|
||||
class AudioSearchResult:
|
||||
"""
|
||||
Represents a single search result for audio.
|
||||
|
||||
This is a serializable representation of a search result that can be
|
||||
stored in Firestore and sent to clients.
|
||||
"""
|
||||
title: str
|
||||
artist: str
|
||||
provider: str
|
||||
url: str
|
||||
duration: Optional[int] = None # Duration in seconds
|
||||
quality: Optional[str] = None # e.g., "FLAC", "320kbps", etc.
|
||||
source_id: Optional[str] = None # Unique ID from the source
|
||||
index: int = 0 # Index in the results list (for selection)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Convert to dict for JSON serialization."""
|
||||
return asdict(self)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict[str, Any]) -> "AudioSearchResult":
|
||||
"""Create from dict."""
|
||||
return cls(**data)
|
||||
|
||||
|
||||
# Also alias AudioFetchResult as AudioDownloadResult for backwards compatibility
|
||||
AudioDownloadResult = AudioFetchResult
|
||||
@dataclass
|
||||
class AudioDownloadResult:
|
||||
"""Result of downloading an audio file."""
|
||||
filepath: str
|
||||
artist: str
|
||||
title: str
|
||||
provider: str
|
||||
duration: Optional[int] = None
|
||||
quality: Optional[str] = None
|
||||
|
||||
|
||||
class AudioSearchError(Exception):
|
||||
"""Base exception for audio search errors."""
|
||||
pass
|
||||
|
||||
|
||||
class NoResultsError(AudioSearchError):
|
||||
"""Raised when no search results are found."""
|
||||
pass
|
||||
|
||||
|
||||
class DownloadError(AudioSearchError):
|
||||
"""Raised when download fails."""
|
||||
pass
|
||||
|
||||
|
||||
class AudioSearchService:
|
||||
"""
|
||||
Service for searching and downloading audio files.
|
||||
Service for searching and downloading audio files using flacfetch.
|
||||
|
||||
This is a thin wrapper around karaoke_gen.audio_fetcher.FlacFetcher that adds
|
||||
backend-specific functionality:
|
||||
- Caches raw results for API-based selection (client picks by index)
|
||||
- Provides Firestore-compatible serialization
|
||||
- Manages service lifecycle as singleton
|
||||
|
||||
The actual flacfetch integration is in karaoke_gen.audio_fetcher.FlacFetcher,
|
||||
which is shared between local CLI and cloud backend.
|
||||
This service is used by the backend to:
|
||||
1. Search for audio by artist/title
|
||||
2. Return results for user selection
|
||||
3. Download the selected audio to a local file
|
||||
"""
|
||||
|
||||
# Sentinel value to indicate "use environment variable"
|
||||
@@ -68,27 +93,60 @@ class AudioSearchService:
|
||||
"""
|
||||
# Use environment variables if not explicitly provided
|
||||
if redacted_api_key is self._USE_ENV:
|
||||
redacted_api_key = os.environ.get("REDACTED_API_KEY")
|
||||
self._redacted_api_key = os.environ.get("REDACTED_API_KEY")
|
||||
else:
|
||||
self._redacted_api_key = redacted_api_key
|
||||
|
||||
if ops_api_key is self._USE_ENV:
|
||||
ops_api_key = os.environ.get("OPS_API_KEY")
|
||||
self._ops_api_key = os.environ.get("OPS_API_KEY")
|
||||
else:
|
||||
self._ops_api_key = ops_api_key
|
||||
|
||||
self._manager = None
|
||||
self._raw_results = {} # Cache raw results for download
|
||||
|
||||
def _get_manager(self):
|
||||
"""Lazily initialize and return the FetchManager."""
|
||||
if self._manager is None:
|
||||
try:
|
||||
from flacfetch.core.manager import FetchManager
|
||||
from flacfetch.providers.youtube import YouTubeProvider
|
||||
except ImportError as e:
|
||||
logger.error(f"flacfetch not installed: {e}")
|
||||
raise AudioSearchError(
|
||||
"flacfetch library is not installed. "
|
||||
"Install with: pip install flacfetch"
|
||||
) from e
|
||||
|
||||
self._manager = FetchManager()
|
||||
|
||||
# Add providers based on available API keys
|
||||
if self._redacted_api_key:
|
||||
try:
|
||||
from flacfetch.providers.redacted import RedactedProvider
|
||||
self._manager.add_provider(RedactedProvider(api_key=self._redacted_api_key))
|
||||
logger.debug("Added Redacted provider")
|
||||
except ImportError:
|
||||
logger.warning("Redacted provider not available")
|
||||
|
||||
if self._ops_api_key:
|
||||
try:
|
||||
from flacfetch.providers.ops import OPSProvider
|
||||
self._manager.add_provider(OPSProvider(api_key=self._ops_api_key))
|
||||
logger.debug("Added OPS provider")
|
||||
except ImportError:
|
||||
logger.warning("OPS provider not available")
|
||||
|
||||
# Always add YouTube as a fallback provider
|
||||
self._manager.add_provider(YouTubeProvider())
|
||||
logger.debug("Added YouTube provider")
|
||||
|
||||
# Delegate to shared FlacFetcher implementation
|
||||
self._fetcher = FlacFetcher(
|
||||
redacted_api_key=redacted_api_key,
|
||||
ops_api_key=ops_api_key,
|
||||
)
|
||||
|
||||
# Cache search results for API-based selection flow
|
||||
# Key: index, Value: AudioSearchResult (with raw_result)
|
||||
self._cached_results: List[AudioSearchResult] = []
|
||||
return self._manager
|
||||
|
||||
def search(self, artist: str, title: str) -> List[AudioSearchResult]:
|
||||
"""
|
||||
Search for audio matching the given artist and title.
|
||||
|
||||
Results are cached internally for later download via download().
|
||||
|
||||
Args:
|
||||
artist: The artist name to search for
|
||||
title: The track title to search for
|
||||
@@ -98,24 +156,49 @@ class AudioSearchService:
|
||||
|
||||
Raises:
|
||||
NoResultsError: If no results are found
|
||||
AudioSearchError: For other errors (e.g., flacfetch not installed)
|
||||
AudioSearchError: For other errors
|
||||
"""
|
||||
try:
|
||||
# Delegate to shared FlacFetcher
|
||||
results = self._fetcher.search(artist, title)
|
||||
|
||||
# Cache results for later download
|
||||
self._cached_results = results
|
||||
|
||||
logger.info(f"Found {len(results)} results for: {artist} - {title}")
|
||||
return results
|
||||
|
||||
except (NoResultsError, AudioFetcherError):
|
||||
# Re-raise these as-is
|
||||
raise
|
||||
from flacfetch.core.models import TrackQuery
|
||||
except ImportError as e:
|
||||
raise AudioSearchError("flacfetch not installed") from e
|
||||
|
||||
manager = self._get_manager()
|
||||
query = TrackQuery(artist=artist, title=title)
|
||||
|
||||
logger.info(f"Searching for audio: {artist} - {title}")
|
||||
|
||||
try:
|
||||
results = manager.search(query)
|
||||
except Exception as e:
|
||||
logger.error(f"Search failed: {e}")
|
||||
raise AudioSearchError(f"Search failed: {e}") from e
|
||||
|
||||
if not results:
|
||||
raise NoResultsError(f"No results found for: {artist} - {title}")
|
||||
|
||||
# Convert to our AudioSearchResult format and cache raw results
|
||||
search_results = []
|
||||
self._raw_results.clear()
|
||||
|
||||
for i, result in enumerate(results):
|
||||
search_result = AudioSearchResult(
|
||||
title=getattr(result, "title", title),
|
||||
artist=getattr(result, "artist", artist),
|
||||
provider=getattr(result, "provider", "Unknown"),
|
||||
url=getattr(result, "url", ""),
|
||||
duration=getattr(result, "duration", None),
|
||||
quality=getattr(result, "quality", None),
|
||||
source_id=getattr(result, "id", str(i)),
|
||||
index=i,
|
||||
)
|
||||
search_results.append(search_result)
|
||||
|
||||
# Cache raw result for later download
|
||||
self._raw_results[i] = result
|
||||
|
||||
logger.info(f"Found {len(search_results)} results for: {artist} - {title}")
|
||||
return search_results
|
||||
|
||||
def select_best(self, results: List[AudioSearchResult]) -> int:
|
||||
"""
|
||||
@@ -129,7 +212,26 @@ class AudioSearchService:
|
||||
Returns:
|
||||
Index of the best result
|
||||
"""
|
||||
return self._fetcher.select_best(results)
|
||||
if not results:
|
||||
return 0
|
||||
|
||||
manager = self._get_manager()
|
||||
|
||||
# Get raw results for the indices we have
|
||||
raw_results = [self._raw_results.get(r.index) for r in results if r.index in self._raw_results]
|
||||
|
||||
if raw_results:
|
||||
try:
|
||||
best = manager.select_best(raw_results)
|
||||
# Find index of best result
|
||||
for i, raw in enumerate(raw_results):
|
||||
if raw == best:
|
||||
return results[i].index
|
||||
except Exception as e:
|
||||
logger.warning(f"select_best failed, using first result: {e}")
|
||||
|
||||
# Fallback: return first result
|
||||
return results[0].index if results else 0
|
||||
|
||||
def download(
|
||||
self,
|
||||
@@ -138,13 +240,7 @@ class AudioSearchService:
|
||||
output_filename: Optional[str] = None,
|
||||
) -> AudioDownloadResult:
|
||||
"""
|
||||
Download audio from a cached search result.
|
||||
|
||||
This method uses the cached results from the last search() call.
|
||||
The API flow is:
|
||||
1. Client calls search() -> gets list of results
|
||||
2. Client picks an index
|
||||
3. Client calls download(index) -> gets downloaded file
|
||||
Download audio from a search result.
|
||||
|
||||
Args:
|
||||
result_index: Index of the result to download (from search results)
|
||||
@@ -155,25 +251,51 @@ class AudioSearchService:
|
||||
AudioDownloadResult with the downloaded file path
|
||||
|
||||
Raises:
|
||||
DownloadError: If download fails or no cached result for index
|
||||
DownloadError: If download fails
|
||||
"""
|
||||
if result_index < 0 or result_index >= len(self._cached_results):
|
||||
raise DownloadError(
|
||||
f"No cached result for index {result_index}. "
|
||||
f"Available indices: 0-{len(self._cached_results) - 1}. "
|
||||
"Run search() first."
|
||||
if result_index not in self._raw_results:
|
||||
raise DownloadError(f"No cached result for index {result_index}. Run search() first.")
|
||||
|
||||
raw_result = self._raw_results[result_index]
|
||||
manager = self._get_manager()
|
||||
|
||||
# Ensure output directory exists
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
# Get metadata from raw result
|
||||
artist = getattr(raw_result, "artist", "Unknown")
|
||||
title = getattr(raw_result, "title", "Unknown")
|
||||
provider = getattr(raw_result, "provider", "Unknown")
|
||||
|
||||
# Generate filename if not provided
|
||||
if output_filename is None:
|
||||
output_filename = f"{artist} - {title}"
|
||||
|
||||
logger.info(f"Downloading: {artist} - {title} from {provider}")
|
||||
|
||||
try:
|
||||
filepath = manager.download(
|
||||
raw_result,
|
||||
output_path=output_dir,
|
||||
output_filename=output_filename,
|
||||
)
|
||||
|
||||
result = self._cached_results[result_index]
|
||||
|
||||
logger.info(f"Downloading: {result.artist} - {result.title} from {result.provider}")
|
||||
|
||||
# Delegate to shared FlacFetcher
|
||||
fetch_result = self._fetcher.download(result, output_dir, output_filename)
|
||||
|
||||
logger.info(f"Downloaded to: {fetch_result.filepath}")
|
||||
|
||||
return fetch_result
|
||||
|
||||
if filepath is None:
|
||||
raise DownloadError(f"Download returned no file path for: {artist} - {title}")
|
||||
|
||||
logger.info(f"Downloaded to: {filepath}")
|
||||
|
||||
return AudioDownloadResult(
|
||||
filepath=filepath,
|
||||
artist=artist,
|
||||
title=title,
|
||||
provider=provider,
|
||||
duration=getattr(raw_result, "duration", None),
|
||||
quality=getattr(raw_result, "quality", None),
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
raise DownloadError(f"Failed to download {artist} - {title}: {e}") from e
|
||||
|
||||
def search_and_download_auto(
|
||||
self,
|
||||
@@ -206,11 +328,7 @@ class AudioSearchService:
|
||||
|
||||
# Select best
|
||||
best_index = self.select_best(results)
|
||||
best_result = results[best_index]
|
||||
logger.info(
|
||||
f"Auto-selected result {best_index}: "
|
||||
f"{best_result.artist} - {best_result.title} ({best_result.provider})"
|
||||
)
|
||||
logger.info(f"Auto-selected result {best_index}: {results[best_index].artist} - {results[best_index].title} ({results[best_index].provider})")
|
||||
|
||||
# Download
|
||||
return self.download(best_index, output_dir, output_filename)
|
||||
@@ -226,3 +344,5 @@ def get_audio_search_service() -> AudioSearchService:
|
||||
if _audio_search_service is None:
|
||||
_audio_search_service = AudioSearchService()
|
||||
return _audio_search_service
|
||||
|
||||
|
||||
@@ -99,11 +99,7 @@ class TestJobStatusAudioSearchStates:
|
||||
|
||||
|
||||
class TestAudioSearchResult:
|
||||
"""Test AudioSearchResult dataclass.
|
||||
|
||||
AudioSearchResult is now imported from karaoke_gen.audio_fetcher.
|
||||
These tests verify the backend can use it correctly.
|
||||
"""
|
||||
"""Test AudioSearchResult dataclass."""
|
||||
|
||||
def test_create_audio_search_result(self):
|
||||
"""Test creating an AudioSearchResult."""
|
||||
@@ -144,8 +140,6 @@ class TestAudioSearchResult:
|
||||
assert data['provider'] == "YouTube"
|
||||
assert data['url'] == "https://youtube.com/watch?v=abc123"
|
||||
assert data['index'] == 0
|
||||
# raw_result should NOT be in serialized dict
|
||||
assert 'raw_result' not in data
|
||||
|
||||
def test_from_dict(self):
|
||||
"""Test creating from dict."""
|
||||
@@ -166,7 +160,6 @@ class TestAudioSearchResult:
|
||||
assert result.artist == "ABBA"
|
||||
assert result.provider == "YouTube"
|
||||
assert result.index == 0
|
||||
assert result.raw_result is None # Not set from dict
|
||||
|
||||
|
||||
class TestAudioSearchServiceInit:
|
||||
@@ -178,9 +171,10 @@ class TestAudioSearchServiceInit:
|
||||
# Pass explicit None to override environment
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
|
||||
# Service should have a FlacFetcher internally
|
||||
assert service._fetcher is not None
|
||||
assert service._cached_results == []
|
||||
# When explicitly passed None, it should be None (not from env)
|
||||
assert service._redacted_api_key is None
|
||||
assert service._ops_api_key is None
|
||||
assert service._manager is None
|
||||
|
||||
def test_init_with_keys(self):
|
||||
"""Test initialization with API keys."""
|
||||
@@ -189,40 +183,41 @@ class TestAudioSearchServiceInit:
|
||||
ops_api_key="test_ops_key",
|
||||
)
|
||||
|
||||
# Keys are passed to FlacFetcher
|
||||
assert service._fetcher._redacted_api_key == "test_redacted_key"
|
||||
assert service._fetcher._ops_api_key == "test_ops_key"
|
||||
assert service._redacted_api_key == "test_redacted_key"
|
||||
assert service._ops_api_key == "test_ops_key"
|
||||
|
||||
def test_init_reads_from_environment(self):
|
||||
"""Test initialization reads keys from environment variables."""
|
||||
import os
|
||||
|
||||
# Just test that the service can be initialized
|
||||
service = AudioSearchService()
|
||||
|
||||
# The service should have a FlacFetcher
|
||||
assert service._fetcher is not None
|
||||
# The service should have API keys from env or None
|
||||
assert service._manager is None # Not yet initialized
|
||||
|
||||
|
||||
class TestAudioSearchServiceSearch:
|
||||
"""Test AudioSearchService.search() method."""
|
||||
|
||||
def test_search_returns_results(self):
|
||||
@patch('backend.services.audio_search_service.AudioSearchService._get_manager')
|
||||
def test_search_returns_results(self, mock_get_manager):
|
||||
"""Test search returns AudioSearchResult list."""
|
||||
# Create mock result
|
||||
mock_result = AudioSearchResult(
|
||||
title="Waterloo",
|
||||
artist="ABBA",
|
||||
provider="YouTube",
|
||||
url="https://youtube.com/watch?v=abc123",
|
||||
duration=180,
|
||||
quality="FLAC",
|
||||
source_id="abc123",
|
||||
index=0,
|
||||
)
|
||||
# Mock the flacfetch result
|
||||
mock_result = Mock()
|
||||
mock_result.title = "Waterloo"
|
||||
mock_result.artist = "ABBA"
|
||||
mock_result.provider = "YouTube"
|
||||
mock_result.url = "https://youtube.com/watch?v=abc123"
|
||||
mock_result.duration = 180
|
||||
mock_result.quality = "FLAC"
|
||||
mock_result.id = "abc123"
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service._fetcher = Mock()
|
||||
service._fetcher.search.return_value = [mock_result]
|
||||
mock_manager = Mock()
|
||||
mock_manager.search.return_value = [mock_result]
|
||||
mock_get_manager.return_value = mock_manager
|
||||
|
||||
service = AudioSearchService()
|
||||
results = service.search("ABBA", "Waterloo")
|
||||
|
||||
assert len(results) == 1
|
||||
@@ -231,36 +226,40 @@ class TestAudioSearchServiceSearch:
|
||||
assert results[0].provider == "YouTube"
|
||||
assert results[0].index == 0
|
||||
|
||||
def test_search_no_results_raises_error(self):
|
||||
@patch('backend.services.audio_search_service.AudioSearchService._get_manager')
|
||||
def test_search_no_results_raises_error(self, mock_get_manager):
|
||||
"""Test search raises NoResultsError when no results."""
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service._fetcher = Mock()
|
||||
service._fetcher.search.side_effect = NoResultsError("No results found")
|
||||
mock_manager = Mock()
|
||||
mock_manager.search.return_value = []
|
||||
mock_get_manager.return_value = mock_manager
|
||||
|
||||
service = AudioSearchService()
|
||||
|
||||
with pytest.raises(NoResultsError) as exc_info:
|
||||
service.search("Unknown Artist", "Unknown Song")
|
||||
|
||||
assert "No results found" in str(exc_info.value)
|
||||
|
||||
def test_search_multiple_results(self):
|
||||
@patch('backend.services.audio_search_service.AudioSearchService._get_manager')
|
||||
def test_search_multiple_results(self, mock_get_manager):
|
||||
"""Test search returns multiple results with correct indices."""
|
||||
mock_results = []
|
||||
for i in range(3):
|
||||
mock_results.append(AudioSearchResult(
|
||||
title=f"Song {i}",
|
||||
artist="Artist",
|
||||
provider=["YouTube", "Redacted", "OPS"][i],
|
||||
url=f"https://example.com/{i}",
|
||||
duration=180 + i * 10,
|
||||
quality=["320kbps", "FLAC", "FLAC"][i],
|
||||
source_id=str(i),
|
||||
index=i,
|
||||
))
|
||||
mock_result = Mock()
|
||||
mock_result.title = f"Song {i}"
|
||||
mock_result.artist = "Artist"
|
||||
mock_result.provider = ["YouTube", "Redacted", "OPS"][i]
|
||||
mock_result.url = f"https://example.com/{i}"
|
||||
mock_result.duration = 180 + i * 10
|
||||
mock_result.quality = ["320kbps", "FLAC", "FLAC"][i]
|
||||
mock_result.id = str(i)
|
||||
mock_results.append(mock_result)
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service._fetcher = Mock()
|
||||
service._fetcher.search.return_value = mock_results
|
||||
mock_manager = Mock()
|
||||
mock_manager.search.return_value = mock_results
|
||||
mock_get_manager.return_value = mock_manager
|
||||
|
||||
service = AudioSearchService()
|
||||
results = service.search("Artist", "Song")
|
||||
|
||||
assert len(results) == 3
|
||||
@@ -272,39 +271,34 @@ class TestAudioSearchServiceSearch:
|
||||
class TestAudioSearchServiceSelectBest:
|
||||
"""Test AudioSearchService.select_best() method."""
|
||||
|
||||
def test_select_best_delegates_to_fetcher(self):
|
||||
"""Test select_best uses FlacFetcher's select_best."""
|
||||
mock_results = [
|
||||
AudioSearchResult(
|
||||
title="Waterloo",
|
||||
artist="ABBA",
|
||||
provider="YouTube",
|
||||
url="https://youtube.com/watch?v=abc123",
|
||||
index=0,
|
||||
),
|
||||
AudioSearchResult(
|
||||
title="Waterloo",
|
||||
artist="ABBA",
|
||||
provider="Redacted",
|
||||
url="https://example.com/456",
|
||||
index=1,
|
||||
),
|
||||
]
|
||||
@patch('backend.services.audio_search_service.AudioSearchService._get_manager')
|
||||
def test_select_best_uses_manager(self, mock_get_manager):
|
||||
"""Test select_best uses flacfetch's select_best."""
|
||||
# First need to do a search to populate cache
|
||||
mock_result = Mock()
|
||||
mock_result.title = "Waterloo"
|
||||
mock_result.artist = "ABBA"
|
||||
mock_result.provider = "YouTube"
|
||||
mock_result.url = "https://youtube.com/watch?v=abc123"
|
||||
mock_result.duration = 180
|
||||
mock_result.quality = "FLAC"
|
||||
mock_result.id = "abc123"
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service._fetcher = Mock()
|
||||
service._fetcher.select_best.return_value = 1
|
||||
mock_manager = Mock()
|
||||
mock_manager.search.return_value = [mock_result]
|
||||
mock_manager.select_best.return_value = mock_result
|
||||
mock_get_manager.return_value = mock_manager
|
||||
|
||||
best_index = service.select_best(mock_results)
|
||||
service = AudioSearchService()
|
||||
results = service.search("ABBA", "Waterloo")
|
||||
|
||||
assert best_index == 1
|
||||
service._fetcher.select_best.assert_called_once_with(mock_results)
|
||||
best_index = service.select_best(results)
|
||||
|
||||
assert best_index == 0
|
||||
|
||||
def test_select_best_empty_list_returns_zero(self):
|
||||
"""Test select_best returns 0 for empty list."""
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service._fetcher = Mock()
|
||||
service._fetcher.select_best.return_value = 0
|
||||
service = AudioSearchService()
|
||||
|
||||
best_index = service.select_best([])
|
||||
|
||||
@@ -314,18 +308,24 @@ class TestAudioSearchServiceSelectBest:
|
||||
class TestAudioSearchServiceDownload:
|
||||
"""Test AudioSearchService.download() method."""
|
||||
|
||||
def test_download_without_search_raises_error(self):
|
||||
@patch('backend.services.audio_search_service.AudioSearchService._get_manager')
|
||||
def test_download_without_search_raises_error(self, mock_get_manager):
|
||||
"""Test download without prior search raises error."""
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
mock_manager = Mock()
|
||||
mock_get_manager.return_value = mock_manager
|
||||
|
||||
service = AudioSearchService()
|
||||
|
||||
with pytest.raises(DownloadError) as exc_info:
|
||||
service.download(0, "/tmp")
|
||||
|
||||
assert "No cached result" in str(exc_info.value)
|
||||
|
||||
def test_download_after_search(self):
|
||||
@patch('backend.services.audio_search_service.AudioSearchService._get_manager')
|
||||
def test_download_after_search(self, mock_get_manager):
|
||||
"""Test download after search works."""
|
||||
import tempfile
|
||||
import os
|
||||
|
||||
# Create a temp file to simulate downloaded file
|
||||
temp_dir = tempfile.mkdtemp()
|
||||
@@ -333,32 +333,23 @@ class TestAudioSearchServiceDownload:
|
||||
with open(temp_file, 'w') as f:
|
||||
f.write("test")
|
||||
|
||||
mock_result = AudioSearchResult(
|
||||
title="Waterloo",
|
||||
artist="ABBA",
|
||||
provider="YouTube",
|
||||
url="https://youtube.com/watch?v=abc123",
|
||||
duration=180,
|
||||
quality="FLAC",
|
||||
source_id="abc123",
|
||||
index=0,
|
||||
)
|
||||
mock_result = Mock()
|
||||
mock_result.title = "Waterloo"
|
||||
mock_result.artist = "ABBA"
|
||||
mock_result.provider = "YouTube"
|
||||
mock_result.url = "https://youtube.com/watch?v=abc123"
|
||||
mock_result.duration = 180
|
||||
mock_result.quality = "FLAC"
|
||||
mock_result.id = "abc123"
|
||||
|
||||
mock_fetch_result = AudioDownloadResult(
|
||||
filepath=temp_file,
|
||||
artist="ABBA",
|
||||
title="Waterloo",
|
||||
provider="YouTube",
|
||||
duration=180,
|
||||
quality="FLAC",
|
||||
)
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service._fetcher = Mock()
|
||||
service._fetcher.search.return_value = [mock_result]
|
||||
service._fetcher.download.return_value = mock_fetch_result
|
||||
mock_manager = Mock()
|
||||
mock_manager.search.return_value = [mock_result]
|
||||
mock_manager.download.return_value = temp_file
|
||||
mock_get_manager.return_value = mock_manager
|
||||
|
||||
service = AudioSearchService()
|
||||
service.search("ABBA", "Waterloo")
|
||||
|
||||
result = service.download(0, temp_dir)
|
||||
|
||||
assert result.filepath == temp_file
|
||||
@@ -369,27 +360,6 @@ class TestAudioSearchServiceDownload:
|
||||
# Cleanup
|
||||
os.remove(temp_file)
|
||||
os.rmdir(temp_dir)
|
||||
|
||||
def test_download_invalid_index_raises_error(self):
|
||||
"""Test download with invalid index raises error."""
|
||||
mock_result = AudioSearchResult(
|
||||
title="Waterloo",
|
||||
artist="ABBA",
|
||||
provider="YouTube",
|
||||
url="https://youtube.com/watch?v=abc123",
|
||||
index=0,
|
||||
)
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service._fetcher = Mock()
|
||||
service._fetcher.search.return_value = [mock_result]
|
||||
|
||||
service.search("ABBA", "Waterloo")
|
||||
|
||||
with pytest.raises(DownloadError) as exc_info:
|
||||
service.download(99, "/tmp")
|
||||
|
||||
assert "No cached result for index 99" in str(exc_info.value)
|
||||
|
||||
|
||||
class TestGetAudioSearchService:
|
||||
@@ -414,86 +384,3 @@ class TestGetAudioSearchService:
|
||||
assert service1 is service2
|
||||
|
||||
|
||||
class TestFlacfetchIntegration:
|
||||
"""
|
||||
Integration tests that verify flacfetch imports work correctly.
|
||||
|
||||
These tests ensure the backend code is compatible with the installed
|
||||
flacfetch version and would catch issues like renamed classes.
|
||||
|
||||
Note: Some tests are marked with pytest.importorskip for flacfetch
|
||||
since it may not be installed in all test environments (e.g., CI).
|
||||
"""
|
||||
|
||||
def test_flacfetch_imports_work(self):
|
||||
"""Test that all flacfetch imports in audio_search_service work.
|
||||
|
||||
This test would have caught the YouTubeProvider -> YoutubeProvider rename.
|
||||
"""
|
||||
flacfetch = pytest.importorskip("flacfetch")
|
||||
|
||||
# These imports match what karaoke_gen.audio_fetcher does
|
||||
from flacfetch.core.manager import FetchManager
|
||||
from flacfetch.providers.youtube import YoutubeProvider
|
||||
from flacfetch.core.models import TrackQuery
|
||||
|
||||
# Verify the classes exist and are callable
|
||||
assert FetchManager is not None
|
||||
assert YoutubeProvider is not None
|
||||
assert TrackQuery is not None
|
||||
|
||||
def test_karaoke_gen_audio_fetcher_imports_work(self):
|
||||
"""Test that karaoke_gen.audio_fetcher imports work.
|
||||
|
||||
Since backend now imports from karaoke_gen, this is the critical test.
|
||||
This should work even without flacfetch installed (lazy import).
|
||||
"""
|
||||
from karaoke_gen.audio_fetcher import (
|
||||
FlacFetcher,
|
||||
AudioSearchResult,
|
||||
AudioFetchResult,
|
||||
AudioFetcherError,
|
||||
NoResultsError,
|
||||
DownloadError,
|
||||
)
|
||||
|
||||
assert FlacFetcher is not None
|
||||
assert AudioSearchResult is not None
|
||||
assert AudioFetchResult is not None
|
||||
assert AudioFetcherError is not None
|
||||
assert NoResultsError is not None
|
||||
assert DownloadError is not None
|
||||
|
||||
def test_audio_search_service_can_initialize_fetcher(self):
|
||||
"""Test AudioSearchService can initialize its FlacFetcher.
|
||||
|
||||
This verifies the actual initialization code path works.
|
||||
"""
|
||||
pytest.importorskip("flacfetch")
|
||||
|
||||
service = AudioSearchService(
|
||||
redacted_api_key=None,
|
||||
ops_api_key=None,
|
||||
)
|
||||
|
||||
# Verify FlacFetcher was initialized
|
||||
assert service._fetcher is not None
|
||||
|
||||
# FlacFetcher can initialize its manager (tests actual flacfetch)
|
||||
manager = service._fetcher._get_manager()
|
||||
assert manager is not None
|
||||
|
||||
def test_shared_classes_are_same_as_karaoke_gen(self):
|
||||
"""Verify backend uses the same classes as karaoke_gen."""
|
||||
from karaoke_gen.audio_fetcher import (
|
||||
AudioSearchResult as KGAudioSearchResult,
|
||||
AudioFetchResult as KGAudioFetchResult,
|
||||
NoResultsError as KGNoResultsError,
|
||||
DownloadError as KGDownloadError,
|
||||
)
|
||||
|
||||
# These should be the exact same classes, not copies
|
||||
assert AudioSearchResult is KGAudioSearchResult
|
||||
assert AudioDownloadResult is KGAudioFetchResult
|
||||
assert NoResultsError is KGNoResultsError
|
||||
assert DownloadError is KGDownloadError
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
# Codecov Configuration
|
||||
# Docs: https://docs.codecov.com/docs/codecovyml-reference
|
||||
|
||||
coverage:
|
||||
# Coverage value precision (2 decimal places)
|
||||
precision: 2
|
||||
round: down
|
||||
# Green range starts at 70% (our target)
|
||||
range: "70...100"
|
||||
|
||||
status:
|
||||
# Project-level coverage status check
|
||||
project:
|
||||
default:
|
||||
target: 70% # Pass if coverage >= 70%
|
||||
threshold: 2% # Allow 2% drop without failing
|
||||
if_ci_failed: error
|
||||
|
||||
# Patch coverage (new/changed lines only)
|
||||
patch:
|
||||
default:
|
||||
target: 70% # New code should also meet 70%
|
||||
threshold: 5% # More lenient for patches
|
||||
|
||||
# Disable PR comments entirely since we're satisfied with 70%+ coverage
|
||||
# Status checks will still appear on the PR
|
||||
comment: false
|
||||
|
||||
# Alternative: Uncomment below to only comment when coverage changes
|
||||
# comment:
|
||||
# layout: "diff, flags, files"
|
||||
# behavior: default
|
||||
# require_changes: true # Only comment if coverage actually changes
|
||||
# require_base: true # Require base report to exist
|
||||
|
||||
@@ -1,141 +0,0 @@
|
||||
# Refactor: Unify Audio Fetcher Code
|
||||
|
||||
**Created:** 2025-12-20
|
||||
**Completed:** 2025-12-20
|
||||
**Priority:** MEDIUM (prevents future bugs like YouTubeProvider -> YoutubeProvider)
|
||||
**Status:** ✅ Completed
|
||||
|
||||
## Problem
|
||||
|
||||
The codebase has **two separate implementations** of flacfetch integration:
|
||||
1. `karaoke_gen/audio_fetcher.py` - Used by local CLI
|
||||
2. `backend/services/audio_search_service.py` - Used by cloud backend
|
||||
|
||||
This violates DRY and caused a bug where the backend's import wasn't updated when flacfetch renamed `YouTubeProvider` to `YoutubeProvider`.
|
||||
|
||||
## Current State
|
||||
|
||||
### Duplicated Code
|
||||
|
||||
| Component | Local (`audio_fetcher.py`) | Backend (`audio_search_service.py`) |
|
||||
|-----------|---------------------------|-------------------------------------|
|
||||
| `_get_manager()` | ✅ 40 lines | ❌ 35 lines (copy) |
|
||||
| Provider setup | ✅ Redacted, OPS, YouTube | ❌ Same, diverged |
|
||||
| `search()` | ✅ Full implementation | ❌ Similar, diverged |
|
||||
| `download()` | ✅ With downloaders | ⚠️ Different, simpler |
|
||||
| `AudioSearchResult` | ✅ Dataclass | ❌ Duplicate, different fields |
|
||||
| `AudioDownloadResult` | ✅ (`AudioFetchResult`) | ❌ Duplicate |
|
||||
| Exceptions | ✅ 4 types | ❌ 3 types, different names |
|
||||
|
||||
### Drift Examples
|
||||
- Backend missing `raw_result` field on `AudioSearchResult`
|
||||
- Backend has `index` field, local doesn't
|
||||
- Backend exceptions inherit from `AudioSearchError`, local from `AudioFetcherError`
|
||||
- Backend missing `UserCancelledError`
|
||||
- Backend missing downloader registration (TorrentDownloader, YoutubeDownloader)
|
||||
|
||||
## Proposed Solution
|
||||
|
||||
### Option 1: Backend imports from karaoke_gen (Recommended)
|
||||
|
||||
The backend already depends on `karaoke_gen` (installed via `pip install -e .` in Dockerfile).
|
||||
|
||||
```python
|
||||
# backend/services/audio_search_service.py - REFACTORED
|
||||
|
||||
from karaoke_gen.audio_fetcher import (
|
||||
FlacFetcher,
|
||||
AudioSearchResult,
|
||||
AudioFetchResult,
|
||||
AudioFetcherError,
|
||||
NoResultsError,
|
||||
DownloadError,
|
||||
)
|
||||
|
||||
class AudioSearchService:
|
||||
"""
|
||||
Thin wrapper around karaoke_gen.audio_fetcher.FlacFetcher.
|
||||
|
||||
Adds backend-specific functionality:
|
||||
- Firestore serialization (to_dict/from_dict)
|
||||
- GCS integration for downloads
|
||||
- Job state management
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
redacted_api_key: Optional[str] = None,
|
||||
ops_api_key: Optional[str] = None,
|
||||
):
|
||||
self._fetcher = FlacFetcher(
|
||||
redacted_api_key=redacted_api_key,
|
||||
ops_api_key=ops_api_key,
|
||||
)
|
||||
|
||||
def search(self, artist: str, title: str) -> List[AudioSearchResult]:
|
||||
"""Delegate to FlacFetcher.search()."""
|
||||
return self._fetcher.search(artist, title)
|
||||
|
||||
def select_best(self, results: List[AudioSearchResult]) -> int:
|
||||
"""Delegate to FlacFetcher.select_best()."""
|
||||
return self._fetcher.select_best(results)
|
||||
|
||||
def download(
|
||||
self,
|
||||
result: AudioSearchResult,
|
||||
output_dir: str,
|
||||
output_filename: Optional[str] = None,
|
||||
) -> AudioFetchResult:
|
||||
"""Delegate to FlacFetcher.download()."""
|
||||
return self._fetcher.download(result, output_dir, output_filename)
|
||||
```
|
||||
|
||||
### Changes Required to karaoke_gen.audio_fetcher
|
||||
|
||||
1. **Add `to_dict()` method to `AudioSearchResult`** - For Firestore serialization
|
||||
2. **Add `from_dict()` classmethod** - For deserialization
|
||||
3. **Ensure `select_best()` is a standalone method** - Currently buried in interactive flow
|
||||
4. **Export all public classes from `__init__.py`**
|
||||
|
||||
### Changes Required to backend
|
||||
|
||||
1. **Remove duplicate dataclasses** - Use imports from karaoke_gen
|
||||
2. **Remove duplicate `_get_manager()`** - Delegate to FlacFetcher
|
||||
3. **Remove duplicate exception classes** - Use karaoke_gen exceptions
|
||||
4. **Update tests** - Point to real classes, not mocks
|
||||
|
||||
## Benefits
|
||||
|
||||
1. **Single source of truth** - Bug fixes apply everywhere
|
||||
2. **No more drift** - Dataclasses, exceptions stay in sync
|
||||
3. **Better test coverage** - karaoke_gen has integration tests for flacfetch imports
|
||||
4. **Less code to maintain** - Backend becomes thin wrapper
|
||||
|
||||
## Migration Steps
|
||||
|
||||
1. [x] Add `to_dict()` / `from_dict()` to `AudioSearchResult` in karaoke_gen
|
||||
2. [x] Extract `select_best()` as standalone method in FlacFetcher
|
||||
3. [x] Update karaoke_gen `__init__.py` exports (with lazy imports)
|
||||
4. [x] Refactor backend to import from karaoke_gen
|
||||
5. [x] Update backend tests
|
||||
6. [x] Delete duplicate code from backend (~150 lines removed)
|
||||
7. [x] Add integration test that catches import divergence
|
||||
|
||||
## Related Files
|
||||
|
||||
- `karaoke_gen/audio_fetcher.py` - Source of truth (keep)
|
||||
- `backend/services/audio_search_service.py` - Refactor to thin wrapper
|
||||
- `backend/api/routes/audio_search.py` - Update imports
|
||||
- `backend/tests/test_audio_search.py` - Update tests
|
||||
|
||||
## Estimated Effort
|
||||
|
||||
- **Time:** 2-4 hours
|
||||
- **Risk:** Low (well-defined changes, good test coverage)
|
||||
- **Dependencies:** None
|
||||
|
||||
## Related Architecture Docs
|
||||
|
||||
- `docs/01-reference/ARCHITECTURE.md` - "LyricsTranscriber Integration" section shows similar pattern
|
||||
- `docs/00-current-plan/SCALABLE-ARCHITECTURE-PLAN.md` - "Shared pipeline architecture" goal
|
||||
|
||||
+1
-32
@@ -4,35 +4,4 @@ import warnings
|
||||
warnings.filterwarnings("ignore", category=SyntaxWarning, module="pydub.*")
|
||||
warnings.filterwarnings("ignore", category=SyntaxWarning, module="syrics.*")
|
||||
|
||||
# Lazy imports to avoid loading heavy dependencies when not needed.
|
||||
# KaraokePrep has many dependencies (lyrics_transcriber, etc.) which may not
|
||||
# be available in all contexts (e.g., backend which only needs audio_fetcher).
|
||||
#
|
||||
# Use explicit imports instead:
|
||||
# from karaoke_gen.karaoke_gen import KaraokePrep
|
||||
# from karaoke_gen.audio_fetcher import FlacFetcher, AudioSearchResult, ...
|
||||
|
||||
__all__ = [
|
||||
"KaraokePrep",
|
||||
# Audio fetcher
|
||||
"FlacFetcher",
|
||||
"AudioSearchResult",
|
||||
"AudioFetchResult",
|
||||
"AudioFetcherError",
|
||||
"NoResultsError",
|
||||
"DownloadError",
|
||||
"UserCancelledError",
|
||||
]
|
||||
|
||||
|
||||
def __getattr__(name):
|
||||
"""Lazy import for heavy modules."""
|
||||
if name == "KaraokePrep":
|
||||
from .karaoke_gen import KaraokePrep
|
||||
return KaraokePrep
|
||||
elif name in ("FlacFetcher", "AudioSearchResult", "AudioFetchResult",
|
||||
"AudioFetcherError", "NoResultsError", "DownloadError",
|
||||
"UserCancelledError"):
|
||||
from . import audio_fetcher
|
||||
return getattr(audio_fetcher, name)
|
||||
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
||||
from .karaoke_gen import KaraokePrep
|
||||
@@ -13,8 +13,8 @@ import tempfile
|
||||
import threading
|
||||
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
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Optional
|
||||
|
||||
# Global flag to track if user requested cancellation via Ctrl+C
|
||||
_interrupt_requested = False
|
||||
@@ -22,11 +22,7 @@ _interrupt_requested = False
|
||||
|
||||
@dataclass
|
||||
class AudioSearchResult:
|
||||
"""Represents a single search result for audio.
|
||||
|
||||
Used by both local CLI and cloud backend. Supports serialization
|
||||
for Firestore storage via to_dict()/from_dict().
|
||||
"""
|
||||
"""Represents a single search result for audio."""
|
||||
|
||||
title: str
|
||||
artist: str
|
||||
@@ -35,49 +31,13 @@ class AudioSearchResult:
|
||||
duration: Optional[int] = None # Duration in seconds
|
||||
quality: Optional[str] = None # e.g., "FLAC", "320kbps", etc.
|
||||
source_id: Optional[str] = None # Unique ID from the source
|
||||
index: int = 0 # Index in the results list (for API selection)
|
||||
# Raw result object from the provider (for download) - not serialized
|
||||
raw_result: Optional[object] = field(default=None, repr=False)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Convert to dict for JSON/Firestore serialization.
|
||||
|
||||
Note: raw_result is excluded as it's not serializable.
|
||||
"""
|
||||
return {
|
||||
"title": self.title,
|
||||
"artist": self.artist,
|
||||
"url": self.url,
|
||||
"provider": self.provider,
|
||||
"duration": self.duration,
|
||||
"quality": self.quality,
|
||||
"source_id": self.source_id,
|
||||
"index": self.index,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict[str, Any]) -> "AudioSearchResult":
|
||||
"""Create from dict (e.g., from Firestore)."""
|
||||
return cls(
|
||||
title=data.get("title", ""),
|
||||
artist=data.get("artist", ""),
|
||||
url=data.get("url", ""),
|
||||
provider=data.get("provider", "Unknown"),
|
||||
duration=data.get("duration"),
|
||||
quality=data.get("quality"),
|
||||
source_id=data.get("source_id"),
|
||||
index=data.get("index", 0),
|
||||
raw_result=None, # Not stored in serialized form
|
||||
)
|
||||
# Raw result object from the provider (for download)
|
||||
raw_result: Optional[object] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class AudioFetchResult:
|
||||
"""Result of an audio fetch operation.
|
||||
|
||||
Used by both local CLI and cloud backend. Supports serialization
|
||||
for Firestore storage via to_dict()/from_dict().
|
||||
"""
|
||||
"""Result of an audio fetch operation."""
|
||||
|
||||
filepath: str
|
||||
artist: str
|
||||
@@ -85,22 +45,6 @@ class AudioFetchResult:
|
||||
provider: str
|
||||
duration: Optional[int] = None
|
||||
quality: Optional[str] = None
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Convert to dict for JSON/Firestore serialization."""
|
||||
return asdict(self)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict[str, Any]) -> "AudioFetchResult":
|
||||
"""Create from dict (e.g., from Firestore)."""
|
||||
return cls(
|
||||
filepath=data.get("filepath", ""),
|
||||
artist=data.get("artist", ""),
|
||||
title=data.get("title", ""),
|
||||
provider=data.get("provider", "Unknown"),
|
||||
duration=data.get("duration"),
|
||||
quality=data.get("quality"),
|
||||
)
|
||||
|
||||
|
||||
class AudioFetcherError(Exception):
|
||||
@@ -216,8 +160,6 @@ class FlacFetchAudioFetcher(AudioFetcher):
|
||||
|
||||
This provides access to multiple audio sources including private music trackers
|
||||
and YouTube, with intelligent prioritization of high-quality sources.
|
||||
|
||||
Also exported as FlacFetcher for shorter name.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -310,7 +252,7 @@ class FlacFetchAudioFetcher(AudioFetcher):
|
||||
|
||||
# Convert to our AudioSearchResult format
|
||||
search_results = []
|
||||
for i, result in enumerate(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
|
||||
@@ -324,7 +266,6 @@ class FlacFetchAudioFetcher(AudioFetcher):
|
||||
duration=getattr(result, "duration_seconds", None),
|
||||
quality=quality_str,
|
||||
source_id=getattr(result, "info_hash", None),
|
||||
index=i, # Set index for API selection
|
||||
raw_result=result,
|
||||
)
|
||||
)
|
||||
@@ -388,40 +329,6 @@ class FlacFetchAudioFetcher(AudioFetcher):
|
||||
except Exception as e:
|
||||
raise DownloadError(f"Failed to download {result.artist} - {result.title}: {e}") from e
|
||||
|
||||
def select_best(self, results: List[AudioSearchResult]) -> int:
|
||||
"""
|
||||
Select the best result from a list of search results.
|
||||
|
||||
Uses flacfetch's built-in quality ranking to determine the best source.
|
||||
This is useful for automated/non-interactive usage.
|
||||
|
||||
Args:
|
||||
results: List of AudioSearchResult objects from search()
|
||||
|
||||
Returns:
|
||||
Index of the best result in the list
|
||||
"""
|
||||
if not results:
|
||||
return 0
|
||||
|
||||
manager = self._get_manager()
|
||||
|
||||
# Get raw results that have raw_result set
|
||||
raw_results = [r.raw_result for r in results if r.raw_result is not None]
|
||||
|
||||
if raw_results:
|
||||
try:
|
||||
best = manager.select_best(raw_results)
|
||||
# Find index of best result
|
||||
for i, r in enumerate(results):
|
||||
if r.raw_result == best:
|
||||
return i
|
||||
except Exception as e:
|
||||
self.logger.warning(f"select_best failed, using first result: {e}")
|
||||
|
||||
# Fallback: return first result
|
||||
return 0
|
||||
|
||||
def search_and_download(
|
||||
self,
|
||||
artist: str,
|
||||
@@ -691,10 +598,6 @@ class FlacFetchAudioFetcher(AudioFetcher):
|
||||
raise UserCancelledError("Selection cancelled by user (Ctrl+C)")
|
||||
|
||||
|
||||
# Alias for shorter name - used by backend and other consumers
|
||||
FlacFetcher = FlacFetchAudioFetcher
|
||||
|
||||
|
||||
def create_audio_fetcher(
|
||||
logger: Optional[logging.Logger] = None,
|
||||
redacted_api_key: Optional[str] = None,
|
||||
|
||||
Generated
+401
-397
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.73.0"
|
||||
version = "0.72.0"
|
||||
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
|
||||
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
|
||||
license = "MIT"
|
||||
|
||||
@@ -41,7 +41,6 @@ class TestAudioSearchResult:
|
||||
assert result.duration is None
|
||||
assert result.quality is None
|
||||
assert result.source_id is None
|
||||
assert result.index == 0 # Default index
|
||||
assert result.raw_result is None
|
||||
|
||||
def test_full_creation(self):
|
||||
@@ -55,147 +54,13 @@ class TestAudioSearchResult:
|
||||
duration=240,
|
||||
quality="FLAC",
|
||||
source_id="123456",
|
||||
index=5,
|
||||
raw_result=raw,
|
||||
)
|
||||
assert result.duration == 240
|
||||
assert result.quality == "FLAC"
|
||||
assert result.source_id == "123456"
|
||||
assert result.index == 5
|
||||
assert result.raw_result == raw
|
||||
|
||||
def test_to_dict_basic(self):
|
||||
"""Test to_dict with minimal fields."""
|
||||
result = AudioSearchResult(
|
||||
title="Test Song",
|
||||
artist="Test Artist",
|
||||
url="https://example.com/song",
|
||||
provider="YouTube",
|
||||
)
|
||||
data = result.to_dict()
|
||||
|
||||
assert data["title"] == "Test Song"
|
||||
assert data["artist"] == "Test Artist"
|
||||
assert data["url"] == "https://example.com/song"
|
||||
assert data["provider"] == "YouTube"
|
||||
assert data["duration"] is None
|
||||
assert data["quality"] is None
|
||||
assert data["source_id"] is None
|
||||
assert data["index"] == 0
|
||||
# raw_result should NOT be in serialized dict
|
||||
assert "raw_result" not in data
|
||||
|
||||
def test_to_dict_full(self):
|
||||
"""Test to_dict with all fields populated."""
|
||||
raw = {"some": "data"}
|
||||
result = AudioSearchResult(
|
||||
title="Test Song",
|
||||
artist="Test Artist",
|
||||
url="https://example.com/song",
|
||||
provider="Redacted",
|
||||
duration=240,
|
||||
quality="FLAC 24bit",
|
||||
source_id="abc123",
|
||||
index=3,
|
||||
raw_result=raw,
|
||||
)
|
||||
data = result.to_dict()
|
||||
|
||||
assert data["title"] == "Test Song"
|
||||
assert data["artist"] == "Test Artist"
|
||||
assert data["url"] == "https://example.com/song"
|
||||
assert data["provider"] == "Redacted"
|
||||
assert data["duration"] == 240
|
||||
assert data["quality"] == "FLAC 24bit"
|
||||
assert data["source_id"] == "abc123"
|
||||
assert data["index"] == 3
|
||||
# raw_result should NOT be in serialized dict
|
||||
assert "raw_result" not in data
|
||||
|
||||
def test_from_dict_basic(self):
|
||||
"""Test from_dict with minimal fields."""
|
||||
data = {
|
||||
"title": "Test Song",
|
||||
"artist": "Test Artist",
|
||||
"url": "https://example.com/song",
|
||||
"provider": "YouTube",
|
||||
}
|
||||
result = AudioSearchResult.from_dict(data)
|
||||
|
||||
assert result.title == "Test Song"
|
||||
assert result.artist == "Test Artist"
|
||||
assert result.url == "https://example.com/song"
|
||||
assert result.provider == "YouTube"
|
||||
assert result.duration is None
|
||||
assert result.quality is None
|
||||
assert result.source_id is None
|
||||
assert result.index == 0 # Default
|
||||
assert result.raw_result is None # Always None from dict
|
||||
|
||||
def test_from_dict_full(self):
|
||||
"""Test from_dict with all fields."""
|
||||
data = {
|
||||
"title": "Test Song",
|
||||
"artist": "Test Artist",
|
||||
"url": "https://example.com/song",
|
||||
"provider": "Redacted",
|
||||
"duration": 240,
|
||||
"quality": "FLAC 24bit",
|
||||
"source_id": "abc123",
|
||||
"index": 7,
|
||||
}
|
||||
result = AudioSearchResult.from_dict(data)
|
||||
|
||||
assert result.title == "Test Song"
|
||||
assert result.artist == "Test Artist"
|
||||
assert result.url == "https://example.com/song"
|
||||
assert result.provider == "Redacted"
|
||||
assert result.duration == 240
|
||||
assert result.quality == "FLAC 24bit"
|
||||
assert result.source_id == "abc123"
|
||||
assert result.index == 7
|
||||
assert result.raw_result is None # Never restored from dict
|
||||
|
||||
def test_from_dict_with_defaults(self):
|
||||
"""Test from_dict uses defaults for missing fields."""
|
||||
data = {}
|
||||
result = AudioSearchResult.from_dict(data)
|
||||
|
||||
assert result.title == ""
|
||||
assert result.artist == ""
|
||||
assert result.url == ""
|
||||
assert result.provider == "Unknown"
|
||||
assert result.index == 0
|
||||
assert result.raw_result is None
|
||||
|
||||
def test_roundtrip_serialization(self):
|
||||
"""Test to_dict -> from_dict roundtrip preserves data."""
|
||||
original = AudioSearchResult(
|
||||
title="Test Song",
|
||||
artist="Test Artist",
|
||||
url="https://example.com/song",
|
||||
provider="Redacted",
|
||||
duration=240,
|
||||
quality="FLAC",
|
||||
source_id="abc123",
|
||||
index=2,
|
||||
raw_result={"will": "be lost"},
|
||||
)
|
||||
|
||||
data = original.to_dict()
|
||||
restored = AudioSearchResult.from_dict(data)
|
||||
|
||||
assert restored.title == original.title
|
||||
assert restored.artist == original.artist
|
||||
assert restored.url == original.url
|
||||
assert restored.provider == original.provider
|
||||
assert restored.duration == original.duration
|
||||
assert restored.quality == original.quality
|
||||
assert restored.source_id == original.source_id
|
||||
assert restored.index == original.index
|
||||
# raw_result is NOT preserved
|
||||
assert restored.raw_result is None
|
||||
|
||||
|
||||
class TestAudioFetchResult:
|
||||
"""Tests for AudioFetchResult dataclass."""
|
||||
@@ -228,111 +93,6 @@ class TestAudioFetchResult:
|
||||
assert result.duration == 180
|
||||
assert result.quality == "FLAC 24bit"
|
||||
|
||||
def test_to_dict_basic(self):
|
||||
"""Test to_dict with minimal fields."""
|
||||
result = AudioFetchResult(
|
||||
filepath="/path/to/song.flac",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
provider="YouTube",
|
||||
)
|
||||
data = result.to_dict()
|
||||
|
||||
assert data["filepath"] == "/path/to/song.flac"
|
||||
assert data["artist"] == "Test Artist"
|
||||
assert data["title"] == "Test Song"
|
||||
assert data["provider"] == "YouTube"
|
||||
assert data["duration"] is None
|
||||
assert data["quality"] is None
|
||||
|
||||
def test_to_dict_full(self):
|
||||
"""Test to_dict with all fields populated."""
|
||||
result = AudioFetchResult(
|
||||
filepath="/path/to/song.flac",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
provider="Redacted",
|
||||
duration=180,
|
||||
quality="FLAC 24bit",
|
||||
)
|
||||
data = result.to_dict()
|
||||
|
||||
assert data["filepath"] == "/path/to/song.flac"
|
||||
assert data["artist"] == "Test Artist"
|
||||
assert data["title"] == "Test Song"
|
||||
assert data["provider"] == "Redacted"
|
||||
assert data["duration"] == 180
|
||||
assert data["quality"] == "FLAC 24bit"
|
||||
|
||||
def test_from_dict_basic(self):
|
||||
"""Test from_dict with minimal fields."""
|
||||
data = {
|
||||
"filepath": "/path/to/song.flac",
|
||||
"artist": "Test Artist",
|
||||
"title": "Test Song",
|
||||
"provider": "YouTube",
|
||||
}
|
||||
result = AudioFetchResult.from_dict(data)
|
||||
|
||||
assert result.filepath == "/path/to/song.flac"
|
||||
assert result.artist == "Test Artist"
|
||||
assert result.title == "Test Song"
|
||||
assert result.provider == "YouTube"
|
||||
assert result.duration is None
|
||||
assert result.quality is None
|
||||
|
||||
def test_from_dict_full(self):
|
||||
"""Test from_dict with all fields."""
|
||||
data = {
|
||||
"filepath": "/path/to/song.flac",
|
||||
"artist": "Test Artist",
|
||||
"title": "Test Song",
|
||||
"provider": "Redacted",
|
||||
"duration": 180,
|
||||
"quality": "FLAC 24bit",
|
||||
}
|
||||
result = AudioFetchResult.from_dict(data)
|
||||
|
||||
assert result.filepath == "/path/to/song.flac"
|
||||
assert result.artist == "Test Artist"
|
||||
assert result.title == "Test Song"
|
||||
assert result.provider == "Redacted"
|
||||
assert result.duration == 180
|
||||
assert result.quality == "FLAC 24bit"
|
||||
|
||||
def test_from_dict_with_defaults(self):
|
||||
"""Test from_dict uses defaults for missing fields."""
|
||||
data = {}
|
||||
result = AudioFetchResult.from_dict(data)
|
||||
|
||||
assert result.filepath == ""
|
||||
assert result.artist == ""
|
||||
assert result.title == ""
|
||||
assert result.provider == "Unknown"
|
||||
assert result.duration is None
|
||||
assert result.quality is None
|
||||
|
||||
def test_roundtrip_serialization(self):
|
||||
"""Test to_dict -> from_dict roundtrip preserves data."""
|
||||
original = AudioFetchResult(
|
||||
filepath="/path/to/song.flac",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
provider="Redacted",
|
||||
duration=180,
|
||||
quality="FLAC 24bit",
|
||||
)
|
||||
|
||||
data = original.to_dict()
|
||||
restored = AudioFetchResult.from_dict(data)
|
||||
|
||||
assert restored.filepath == original.filepath
|
||||
assert restored.artist == original.artist
|
||||
assert restored.title == original.title
|
||||
assert restored.provider == original.provider
|
||||
assert restored.duration == original.duration
|
||||
assert restored.quality == original.quality
|
||||
|
||||
|
||||
class TestExceptions:
|
||||
"""Tests for custom exceptions."""
|
||||
@@ -668,167 +428,6 @@ class TestFlacFetchAudioFetcher:
|
||||
captured = capsys.readouterr()
|
||||
assert "Cancelled" in captured.out
|
||||
|
||||
@patch('karaoke_gen.audio_fetcher.FlacFetchAudioFetcher._get_manager')
|
||||
def test_select_best_returns_index(self, mock_get_manager, fetcher):
|
||||
"""Test select_best returns the index of the best result."""
|
||||
# Create mock raw results
|
||||
raw_result_1 = MagicMock()
|
||||
raw_result_2 = MagicMock()
|
||||
raw_result_3 = MagicMock()
|
||||
|
||||
# Create AudioSearchResults with raw_result
|
||||
results = [
|
||||
AudioSearchResult(
|
||||
title="Song 1", artist="Artist", url="url1", provider="YouTube",
|
||||
index=0, raw_result=raw_result_1,
|
||||
),
|
||||
AudioSearchResult(
|
||||
title="Song 2", artist="Artist", url="url2", provider="Redacted",
|
||||
index=1, raw_result=raw_result_2,
|
||||
),
|
||||
AudioSearchResult(
|
||||
title="Song 3", artist="Artist", url="url3", provider="OPS",
|
||||
index=2, raw_result=raw_result_3,
|
||||
),
|
||||
]
|
||||
|
||||
# Mock manager.select_best to return the second raw result (index 1)
|
||||
mock_manager = MagicMock()
|
||||
mock_manager.select_best.return_value = raw_result_2
|
||||
mock_get_manager.return_value = mock_manager
|
||||
|
||||
# Execute
|
||||
best_index = fetcher.select_best(results)
|
||||
|
||||
# Verify
|
||||
assert best_index == 1
|
||||
mock_manager.select_best.assert_called_once()
|
||||
|
||||
@patch('karaoke_gen.audio_fetcher.FlacFetchAudioFetcher._get_manager')
|
||||
def test_select_best_empty_list(self, mock_get_manager, fetcher):
|
||||
"""Test select_best returns 0 for empty list."""
|
||||
best_index = fetcher.select_best([])
|
||||
assert best_index == 0
|
||||
|
||||
@patch('karaoke_gen.audio_fetcher.FlacFetchAudioFetcher._get_manager')
|
||||
def test_select_best_single_result(self, mock_get_manager, fetcher):
|
||||
"""Test select_best returns 0 for single result."""
|
||||
raw_result = MagicMock()
|
||||
results = [
|
||||
AudioSearchResult(
|
||||
title="Song", artist="Artist", url="url", provider="YouTube",
|
||||
index=0, raw_result=raw_result,
|
||||
),
|
||||
]
|
||||
|
||||
mock_manager = MagicMock()
|
||||
mock_manager.select_best.return_value = raw_result
|
||||
mock_get_manager.return_value = mock_manager
|
||||
|
||||
best_index = fetcher.select_best(results)
|
||||
|
||||
assert best_index == 0
|
||||
|
||||
@patch('karaoke_gen.audio_fetcher.FlacFetchAudioFetcher._get_manager')
|
||||
def test_select_best_without_raw_results(self, mock_get_manager, fetcher):
|
||||
"""Test select_best returns 0 when results have no raw_result."""
|
||||
results = [
|
||||
AudioSearchResult(
|
||||
title="Song 1", artist="Artist", url="url1", provider="YouTube",
|
||||
index=0, raw_result=None,
|
||||
),
|
||||
AudioSearchResult(
|
||||
title="Song 2", artist="Artist", url="url2", provider="Redacted",
|
||||
index=1, raw_result=None,
|
||||
),
|
||||
]
|
||||
|
||||
mock_manager = MagicMock()
|
||||
mock_get_manager.return_value = mock_manager
|
||||
|
||||
best_index = fetcher.select_best(results)
|
||||
|
||||
# Should return 0 as fallback since no raw results
|
||||
assert best_index == 0
|
||||
|
||||
@patch('karaoke_gen.audio_fetcher.FlacFetchAudioFetcher._get_manager')
|
||||
def test_select_best_handles_exception(self, mock_get_manager, fetcher):
|
||||
"""Test select_best returns 0 when manager.select_best raises exception."""
|
||||
raw_result = MagicMock()
|
||||
results = [
|
||||
AudioSearchResult(
|
||||
title="Song", artist="Artist", url="url", provider="YouTube",
|
||||
index=0, raw_result=raw_result,
|
||||
),
|
||||
]
|
||||
|
||||
mock_manager = MagicMock()
|
||||
mock_manager.select_best.side_effect = Exception("Some error")
|
||||
mock_get_manager.return_value = mock_manager
|
||||
|
||||
# Should not raise, should return 0 as fallback
|
||||
best_index = fetcher.select_best(results)
|
||||
|
||||
assert best_index == 0
|
||||
|
||||
@patch('karaoke_gen.audio_fetcher.FlacFetchAudioFetcher._get_manager')
|
||||
def test_search_sets_index_on_results(self, mock_get_manager, fetcher):
|
||||
"""Test search() sets the correct index on each result."""
|
||||
# Create multiple mock results
|
||||
mock_results = []
|
||||
for i in range(3):
|
||||
mock_result = MagicMock()
|
||||
mock_result.title = f"Song {i}"
|
||||
mock_result.artist = "Artist"
|
||||
mock_result.download_url = f"https://example.com/{i}"
|
||||
mock_result.source_name = "YouTube"
|
||||
mock_result.duration_seconds = 180
|
||||
mock_result.quality = None
|
||||
mock_result.info_hash = str(i)
|
||||
mock_results.append(mock_result)
|
||||
|
||||
mock_manager = MagicMock()
|
||||
mock_manager.search.return_value = mock_results
|
||||
mock_get_manager.return_value = mock_manager
|
||||
|
||||
results = fetcher.search("Artist", "Song")
|
||||
|
||||
# Verify indices are set correctly
|
||||
assert len(results) == 3
|
||||
assert results[0].index == 0
|
||||
assert results[1].index == 1
|
||||
assert results[2].index == 2
|
||||
|
||||
|
||||
class TestFlacFetcherAlias:
|
||||
"""Tests for FlacFetcher alias."""
|
||||
|
||||
def test_flacfetcher_alias_exists(self):
|
||||
"""Test FlacFetcher alias is available."""
|
||||
from karaoke_gen.audio_fetcher import FlacFetcher
|
||||
assert FlacFetcher is not None
|
||||
|
||||
def test_flacfetcher_is_flacfetchaudiofetcher(self):
|
||||
"""Test FlacFetcher is the same as FlacFetchAudioFetcher."""
|
||||
from karaoke_gen.audio_fetcher import FlacFetcher
|
||||
assert FlacFetcher is FlacFetchAudioFetcher
|
||||
|
||||
def test_flacfetcher_can_instantiate(self):
|
||||
"""Test FlacFetcher alias can be used to create instances."""
|
||||
from karaoke_gen.audio_fetcher import FlacFetcher
|
||||
fetcher = FlacFetcher()
|
||||
assert isinstance(fetcher, FlacFetchAudioFetcher)
|
||||
|
||||
def test_flacfetcher_with_parameters(self):
|
||||
"""Test FlacFetcher alias passes parameters correctly."""
|
||||
from karaoke_gen.audio_fetcher import FlacFetcher
|
||||
fetcher = FlacFetcher(
|
||||
redacted_api_key="test_key",
|
||||
ops_api_key="ops_key",
|
||||
)
|
||||
assert fetcher._redacted_api_key == "test_key"
|
||||
assert fetcher._ops_api_key == "ops_key"
|
||||
|
||||
|
||||
class TestCreateAudioFetcher:
|
||||
"""Tests for create_audio_fetcher factory function."""
|
||||
|
||||
Reference in new issue
Block a user