Compare commits

...
Author SHA1 Message Date
Andrew Beveridge 6951de03b3 fix: use full file path for content type detection in style uploads
The _get_content_type method was being called with just the extension
(e.g., '.json') instead of the full path. Path('.json').suffix returns
empty string because it's interpreted as a hidden file, not an extension.

This caused style_params.json uploads to use 'application/octet-stream'
instead of 'application/json', resulting in 403 errors from GCS because
the content type didn't match the signed URL.

Bump version to 0.75.49
2025-12-25 09:45:15 -05:00
Andrew Beveridge f1d3423e9d fix: Add mutagen dependency for LRCLIB track duration matching
Also adds tests for search_audio with style file uploads.

The LRCLIB lyrics provider uses mutagen to get track duration from
audio files for more accurate lyrics matching. Without it, the provider
falls back to the search API which may return less accurate matches.

Warning previously seen in logs:
"Could not determine track duration: No module named 'mutagen'"
2025-12-25 08:26:11 -05:00
Andrew Beveridge 82475a8b03 feat: Add style file upload support to audio search mode
Previously, audio search mode (`karaoke-gen-remote` without a file argument)
did not support style parameters. Jobs would fail with "Missing required
style parameters" when --style_params_json was specified.

Changes:
- Add StyleFileRequest and StyleUploadUrl models to audio_search.py
- Add style_files field to AudioSearchRequest
- Generate signed upload URLs for style files in search response
- Update CLI search_audio() to:
  - Parse style_params.json and extract referenced asset files
  - Include style file metadata in API request
  - Upload style files to signed URLs after receiving response

This enables full style customization for audio search mode, matching
the feature parity of file upload mode.
2025-12-25 08:09:30 -05:00
Andrew Beveridge 8c2be7bfe2 fix: Preserve static auth token during refresh_auth
When using KARAOKE_GEN_AUTH_TOKEN env var for authentication,
refresh_auth() was incorrectly trying to get a new gcloud identity
token, which would overwrite the valid static admin token.

This caused "Authentication failed: Invalid token" errors after
the review step completed, preventing the CLI from continuing
to monitor the job.

Now refresh_auth() checks if KARAOKE_GEN_AUTH_TOKEN is set and
keeps that token instead of trying to refresh via gcloud.
2025-12-25 07:57:12 -05:00
Andrew Beveridge b7e157ec15 fix: Handle remote flacfetch API results correctly for rich display
The remote flacfetch API returns dicts directly, while local flacfetch
returns Release objects. Both audio_search.py and audio_fetcher.py
were trying to call .to_dict() on the raw_result, which failed silently
when it was already a dict from the remote API.

This fix:
- Checks if raw_result is already a dict (remote API) vs Release object (local)
- Uses the dict directly instead of calling .to_dict()
- Handles quality_data field correctly (remote uses 'quality_data', local uses 'quality')

This enables proper display of tracker results with album type, format,
year, label, etc. in the karaoke-gen-remote CLI.
2025-12-25 00:10:34 -05:00
Andrew Beveridge 722ec69cda fix: render_video_worker temp directory scope bug causing FileNotFoundError
The with tempfile.TemporaryDirectory() block was ending prematurely,
causing all subsequent code to run with a deleted temp directory.
This caused 'No such file or directory' errors when trying to download
files into the temp directory.

Fixed by properly indenting all code that uses temp_dir to be inside
the with block.
2025-12-24 22:53:38 -05:00
Andrew Beveridge ☄️ 67b0601811 Merge pull request #58 from nomadkaraoke/feature/categorized-audio-search-display
feat: Add GDrive validator Cloud Function for daily validation
2025-12-24 22:07:34 -05:00
Andrew Beveridge 97a0c642f1 fix: Address CodeRabbit review comments
- Fix README schedule time (6 AM Pacific -> 9 PM EST)
- Use underscore for unused credentials variable
- Use logger.exception for better tracebacks
- Log failures when error notification fails
2025-12-24 21:37:55 -05:00
Andrew Beveridge 71dadc71a2 chore: Update GDrive validator schedule to 9 PM EST
- Change schedule from 6 AM Pacific to 9 PM Eastern
- Merge latest main
2025-12-24 21:30:59 -05:00
Andrew Beveridge e81ecbbbba Merge remote-tracking branch 'origin/main' into feature/categorized-audio-search-display 2025-12-24 21:28:10 -05:00
Andrew Beveridge 6897d20358 Improved cursor rules 2025-12-24 21:19:50 -05:00
Andrew Beveridge af09ee4b50 feat: Add GDrive validator Cloud Function with daily notifications
- Add Cloud Function to validate Nomad Karaoke public GDrive folder
- Check for duplicate sequence numbers, invalid filenames, and gaps
- Send Pushbullet notification on issues or daily summary (configurable)
- Cloud Scheduler triggers daily at 6 AM Pacific
- NOTIFY_ON_SUCCESS env var toggles daily summary notifications
- Includes proper service account with Drive API access
2025-12-24 17:39:44 -05:00
Andrew Beveridge ☄️ 634bb3a11c Merge pull request #57 from nomadkaraoke/feature/categorized-audio-search-display
feat: Add categorized audio search display to remote CLI
2025-12-24 11:04:46 -05:00
Andrew Beveridge 79cc552226 test: Add tests for categorized audio display methods
Add 9 tests for the new categorized display functionality:
- test_convert_to_release_objects_* (3 tests)
- test_find_original_index_* (5 tests)
- test_convert_api_result_to_release_dict

This increases test coverage to meet the 70% threshold.

Bump version: 0.75.39 → 0.75.40
2025-12-24 03:17:14 -05:00
Andrew Beveridge f579f0ce71 fix: Require flacfetch >=0.9.0 for categorization features
Update flacfetch dependency to >=0.9.0 which includes the
categorize_releases module used by the new categorized display.

Bump version: 0.75.38 → 0.75.39
2025-12-24 03:08:44 -05:00
Andrew Beveridge 682f5ef432 feat: Add categorized audio search display to remote CLI
Update remote CLI's handle_audio_selection() to use flacfetch's new
categorized display for large result sets (10+ results). Results are
now grouped into categories: Top Seeded, Album Releases, Hi-Res 24-bit,
Singles, Live Versions, etc.

Changes:
- Add imports for categorize_releases, TrackQuery, print_categorized_releases
- Add _convert_to_release_objects() helper method
- Update handle_audio_selection() to use categorized display for 10+ results
- Support 'more' command to show full flat list when in categorized mode
- Add _find_original_index() to map selection back to API index

This gives remote CLI users the same improved search UX as local CLI users
following the flacfetch PR #4 updates.

Bump version: 0.75.37 → 0.75.38
2025-12-24 02:44:38 -05:00
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
20 changed files with 3646 additions and 322 deletions

No files matched your search

+20 -3
View File
@@ -1,14 +1,31 @@
---
description: Infrastructure as Code requirements using Pulumi
alwaysApply: true
---
# Infrastructure Changes
All Google Cloud infrastructure (IAM, Cloud Storage, Cloud Run, Secret Manager, Artifact Registry, etc.) must be managed via Pulumi in the `infrastructure/` folder.
All Google Cloud infrastructure (IAM, Cloud Storage, Cloud Run, Secret Manager, Artifact Registry, etc.) must be managed via **Pulumi IaC** in the `infrastructure/` folder.
## Rules
- **Reading/querying** with `gcloud` CLI is fine
- **Creating or modifying** resources must go through IaC — never use `gcloud` or the Console to make changes
- **Reading/querying** with `gcloud` CLI is fine for investigation and debugging
- **Temporary changes** via `gcloud` CLI or Console are acceptable for urgent fixes or experimentation, but **must be cleaned up** and properly codified in the IaC afterward
- **Permanent changes** must go through Pulumi — never leave `gcloud` or Console changes as the final state
## Workflow
1. Make changes in `infrastructure/`
2. Run `pulumi preview` and verify the output
3. Run `pulumi up` to apply
## Authentication Issues
If you encounter any authentication issues with `gcloud` or `pulumi` (e.g., expired tokens, permission errors), **stop and notify the user** so they can run the appropriate auth commands in their external terminal:
```bash
gcloud auth login
gcloud auth application-default login
```
Do not attempt to work around auth issues or make assumptions about credentials.
+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
+109 -5
View File
@@ -36,8 +36,21 @@ from backend.config import get_settings
from backend.version import VERSION
from backend.api.dependencies import require_auth
from backend.services.auth_service import UserType
from pathlib import Path
logger = logging.getLogger(__name__)
# Valid style file types (from file_upload.py)
STYLE_FILE_TYPES = {
'style_params': {'.json'},
'style_intro_background': {'.jpg', '.jpeg', '.png'},
'style_karaoke_background': {'.jpg', '.jpeg', '.png'},
'style_end_background': {'.jpg', '.jpeg', '.png'},
'style_font': {'.ttf', '.otf'},
'style_cdg_instrumental_background': {'.jpg', '.jpeg', '.png'},
'style_cdg_title_background': {'.jpg', '.jpeg', '.png'},
'style_cdg_outro_background': {'.jpg', '.jpeg', '.png'},
}
router = APIRouter(tags=["audio-search"])
# Initialize services
@@ -50,6 +63,20 @@ worker_service = get_worker_service()
# Pydantic models
# ============================================================================
class StyleFileRequest(BaseModel):
"""Information about a style file to be uploaded."""
filename: str = Field(..., description="Original filename with extension")
content_type: str = Field(..., description="MIME type of the file")
file_type: str = Field(..., description="Type of file: 'style_params', 'style_intro_background', 'style_karaoke_background', 'style_end_background', 'style_font', 'style_cdg_instrumental_background', 'style_cdg_title_background', 'style_cdg_outro_background'")
class StyleUploadUrl(BaseModel):
"""Signed URL for uploading a style file."""
file_type: str = Field(..., description="Type of file being uploaded")
gcs_path: str = Field(..., description="Destination path in GCS")
upload_url: str = Field(..., description="Signed URL to PUT the file to")
class AudioSearchRequest(BaseModel):
"""Request to search for audio by artist and title."""
artist: str = Field(..., description="Artist name to search for")
@@ -81,6 +108,10 @@ class AudioSearchRequest(BaseModel):
clean_instrumental_model: Optional[str] = Field(None, description="Model for clean instrumental separation")
backing_vocals_models: Optional[List[str]] = Field(None, description="Models for backing vocals separation")
other_stems_models: Optional[List[str]] = Field(None, description="Models for other stems")
# Style file uploads (optional)
# Style params JSON and related assets (background images, fonts)
style_files: Optional[List[StyleFileRequest]] = Field(None, description="Style files to upload (style_params JSON, backgrounds, fonts)")
class AudioSearchResultResponse(BaseModel):
@@ -129,6 +160,8 @@ class AudioSearchResponse(BaseModel):
results_count: int = 0
auto_download: bool = False
server_version: str
# Style file upload URLs (when style_files are specified in request)
style_upload_urls: Optional[List[StyleUploadUrl]] = None
class AudioSelectRequest(BaseModel):
@@ -421,6 +454,66 @@ async def search_audio(
'auto_download': body.auto_download,
})
# Handle style file uploads if provided
style_upload_urls: List[StyleUploadUrl] = []
style_assets = {}
if body.style_files:
logger.info(f"Processing {len(body.style_files)} style file uploads for job {job_id}")
for file_info in body.style_files:
# Validate file type
if file_info.file_type not in STYLE_FILE_TYPES:
raise HTTPException(
status_code=400,
detail=f"Invalid file type '{file_info.file_type}'. Must be one of: {', '.join(STYLE_FILE_TYPES.keys())}"
)
# Validate extension
ext = Path(file_info.filename).suffix.lower()
allowed_exts = STYLE_FILE_TYPES[file_info.file_type]
if ext not in allowed_exts:
raise HTTPException(
status_code=400,
detail=f"Invalid extension '{ext}' for {file_info.file_type}. Allowed: {', '.join(allowed_exts)}"
)
# Generate GCS path
if file_info.file_type == 'style_params':
gcs_path = f"uploads/{job_id}/style/style_params.json"
else:
# style_intro_background -> intro_background, etc.
asset_key = file_info.file_type.replace('style_', '')
gcs_path = f"uploads/{job_id}/style/{asset_key}{ext}"
# Generate signed upload URL
signed_url = storage_service.generate_signed_upload_url(
gcs_path,
content_type=file_info.content_type,
expiration_minutes=60
)
style_upload_urls.append(StyleUploadUrl(
file_type=file_info.file_type,
gcs_path=gcs_path,
upload_url=signed_url
))
# Track the expected asset paths
if file_info.file_type == 'style_params':
style_assets['style_params'] = gcs_path
else:
asset_key = file_info.file_type.replace('style_', '')
style_assets[asset_key] = gcs_path
# Update job with style asset expectations
style_update = {'style_assets': style_assets}
if 'style_params' in style_assets:
style_update['style_params_gcs_path'] = style_assets['style_params']
job_manager.update_job(job_id, style_update)
logger.info(f"Generated {len(style_upload_urls)} style upload URLs for job {job_id}")
# Transition to searching state
job_manager.transition_to_state(
job_id=job_id,
@@ -478,6 +571,7 @@ async def search_audio(
results_count=len(search_results),
auto_download=True,
server_version=VERSION,
style_upload_urls=style_upload_urls if style_upload_urls else None,
)
# Interactive mode: return results for user selection
@@ -492,12 +586,20 @@ async def search_audio(
result_responses = []
for r in search_results:
# Get full serialized data from raw_result if available
# raw_result can be either:
# - A dict (from remote flacfetch API)
# - A Release object (from local flacfetch)
raw_dict = {}
if r.raw_result:
try:
raw_dict = r.raw_result.to_dict()
except AttributeError:
pass # Not a Release object
if isinstance(r.raw_result, dict):
# Remote flacfetch API returns dicts directly
raw_dict = r.raw_result
else:
# Local flacfetch returns Release objects
try:
raw_dict = r.raw_result.to_dict()
except AttributeError:
pass # Not a Release object
result_responses.append(
AudioSearchResultResponse(
@@ -529,7 +631,8 @@ async def search_audio(
is_lossless=raw_dict.get('is_lossless'),
quality_str=raw_dict.get('quality_str'),
# Full quality object for Release.from_dict()
quality_data=raw_dict.get('quality'),
# Remote API uses 'quality_data', local uses 'quality' for the dict
quality_data=raw_dict.get('quality_data') or raw_dict.get('quality'),
)
)
@@ -541,6 +644,7 @@ async def search_audio(
results_count=len(search_results),
auto_download=False,
server_version=VERSION,
style_upload_urls=style_upload_urls if style_upload_urls else None,
)
except HTTPException:
+220 -222
View File
@@ -113,236 +113,234 @@ async def process_render_video(job_id: str) -> bool:
with tempfile.TemporaryDirectory() as temp_dir:
job_log.info(f"Created temp directory: {temp_dir}")
# 1. Download corrected corrections data
corrections_path = os.path.join(temp_dir, "corrections.json")
# Try updated corrections first (from human review), fall back to original
corrections_gcs_updated = f"jobs/{job_id}/lyrics/corrections_updated.json"
corrections_gcs_original = f"jobs/{job_id}/lyrics/corrections.json"
# Get GCS path from file_urls
corrections_url = job.file_urls.get('lyrics', {}).get('corrections_updated')
if not corrections_url:
corrections_url = job.file_urls.get('lyrics', {}).get('corrections')
if not corrections_url:
# Try direct GCS paths
if storage.file_exists(corrections_gcs_updated):
corrections_gcs = corrections_gcs_updated
elif storage.file_exists(corrections_gcs_original):
corrections_gcs = corrections_gcs_original
# Try updated corrections first (from human review), fall back to original
corrections_gcs_updated = f"jobs/{job_id}/lyrics/corrections_updated.json"
corrections_gcs_original = f"jobs/{job_id}/lyrics/corrections.json"
# Get GCS path from file_urls
corrections_url = job.file_urls.get('lyrics', {}).get('corrections_updated')
if not corrections_url:
corrections_url = job.file_urls.get('lyrics', {}).get('corrections')
if not corrections_url:
# Try direct GCS paths
if storage.file_exists(corrections_gcs_updated):
corrections_gcs = corrections_gcs_updated
elif storage.file_exists(corrections_gcs_original):
corrections_gcs = corrections_gcs_original
else:
raise FileNotFoundError(f"No corrections file found for job {job_id}")
else:
raise FileNotFoundError(f"No corrections file found for job {job_id}")
else:
# Extract GCS path from URL
corrections_gcs = _extract_gcs_path(corrections_url)
# 2. Load the ORIGINAL corrections (has full structure)
original_corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
original_corrections_path = os.path.join(temp_dir, "corrections_original.json")
job_log.info(f"Downloading original corrections from {original_corrections_gcs}")
logger.info(f"Job {job_id}: Downloading original corrections from {original_corrections_gcs}")
storage.download_file(original_corrections_gcs, original_corrections_path)
with open(original_corrections_path, 'r', encoding='utf-8') as f:
original_data = json.load(f)
# 3. Check if there are updated corrections (from review UI)
# The frontend sends only partial data: {corrections, corrected_segments}
updated_corrections_gcs = f"jobs/{job_id}/lyrics/corrections_updated.json"
if storage.file_exists(updated_corrections_gcs):
job_log.info("Found updated corrections from review, merging")
logger.info(f"Job {job_id}: Found updated corrections, merging")
updated_path = os.path.join(temp_dir, "corrections_updated.json")
storage.download_file(updated_corrections_gcs, updated_path)
# Extract GCS path from URL
corrections_gcs = _extract_gcs_path(corrections_url)
with open(updated_path, 'r', encoding='utf-8') as f:
updated_data = json.load(f)
# 2. Load the ORIGINAL corrections (has full structure)
original_corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
original_corrections_path = os.path.join(temp_dir, "corrections_original.json")
# Merge: update the original with the user's corrections
if 'corrections' in updated_data:
original_data['corrections'] = updated_data['corrections']
if 'corrected_segments' in updated_data:
original_data['corrected_segments'] = updated_data['corrected_segments']
job_log.info(f"Downloading original corrections from {original_corrections_gcs}")
logger.info(f"Job {job_id}: Downloading original corrections from {original_corrections_gcs}")
storage.download_file(original_corrections_gcs, original_corrections_path)
job_log.info("Merged user corrections into original data")
logger.info(f"Job {job_id}: Merged user corrections into original data")
# 4. Convert to CorrectionResult
correction_result = CorrectionResult.from_dict(original_data)
job_log.info(f"Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
logger.info(f"Job {job_id}: Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
# 3. Download audio file
audio_path = os.path.join(temp_dir, "audio.flac")
audio_gcs_path = job.input_media_gcs_path
if not audio_gcs_path:
raise FileNotFoundError(f"No input audio path for job {job_id}")
job_log.info(f"Downloading audio from {audio_gcs_path}")
logger.info(f"Job {job_id}: Downloading audio from {audio_gcs_path}")
storage.download_file(audio_gcs_path, audio_path)
job_log.info(f"Audio downloaded: {os.path.getsize(audio_path)} bytes")
# Check if corrections have countdown padding and pad audio if needed
# This ensures the audio matches the shifted timestamps in the corrections
countdown_processor = CountdownProcessor(cache_dir=temp_dir, logger=logger)
if countdown_processor.has_countdown(correction_result):
job_log.info("Detected countdown in corrections - creating padded audio for sync")
audio_path = countdown_processor.create_padded_audio_only(audio_path)
job_log.info(f"Padded audio created: {audio_path}")
else:
job_log.info("No countdown detected in corrections - using original audio")
# 4. Get or create styles using the unified style loader
job_log.info("Loading style configuration...")
job_log.info(f" job.style_params_gcs_path: {job.style_params_gcs_path}")
job_log.info(f" job.style_assets: {list(job.style_assets.keys()) if job.style_assets else 'None'}")
styles_path, style_data = load_styles_from_gcs(
style_params_gcs_path=job.style_params_gcs_path,
style_assets=job.style_assets,
temp_dir=temp_dir,
download_func=storage.download_file,
logger=job_log,
)
# 5. Configure OutputGenerator
output_dir = os.path.join(temp_dir, "output")
cache_dir = os.path.join(temp_dir, "cache")
os.makedirs(output_dir, exist_ok=True)
os.makedirs(cache_dir, exist_ok=True)
job_log.info(f"Using styles from: {styles_path}")
# Get subtitle offset from job (user-specified timing adjustment)
subtitle_offset = getattr(job, 'subtitle_offset_ms', 0) or 0
if subtitle_offset != 0:
job_log.info(f"Applying subtitle offset: {subtitle_offset}ms")
config = OutputConfig(
output_dir=output_dir,
cache_dir=cache_dir,
output_styles_json=styles_path,
render_video=True,
generate_cdg=False, # CDG optional, generated separately
generate_plain_text=True,
generate_lrc=True,
video_resolution="4k",
subtitle_offset_ms=subtitle_offset
)
job_log.info(f"OutputConfig: output_styles_json={config.output_styles_json}, render_video={config.render_video}")
output_generator = OutputGenerator(config, logger)
# 6. Generate outputs (video, LRC, ASS, etc.)
output_prefix = f"{job.artist or 'Unknown'} - {job.title or 'Unknown'}"
job_log.info(f"Generating outputs with prefix '{output_prefix}'")
logger.info(f"Job {job_id}: Generating outputs with prefix '{output_prefix}'")
outputs = output_generator.generate_outputs(
transcription_corrected=correction_result,
lyrics_results={}, # Reference lyrics already in correction_result
output_prefix=output_prefix,
audio_filepath=audio_path,
artist=job.artist,
title=job.title
)
# 7. Upload video to GCS
if outputs.video and os.path.exists(outputs.video):
video_size = os.path.getsize(outputs.video)
job_log.info(f"Video generated: {video_size} bytes")
video_gcs_path = f"jobs/{job_id}/videos/with_vocals.mkv"
video_url = storage.upload_file(outputs.video, video_gcs_path)
job_manager.update_file_url(job_id, 'videos', 'with_vocals', video_url)
job_log.info(f"Uploaded with_vocals.mkv to GCS")
logger.info(f"Job {job_id}: Uploaded with_vocals.mkv ({video_size} bytes)")
else:
job_log.error("Video generation failed - no output file produced!")
raise Exception("Video generation failed - no output file produced")
# 8. Upload LRC file
if outputs.lrc and os.path.exists(outputs.lrc):
lrc_gcs_path = f"jobs/{job_id}/lyrics/karaoke.lrc"
lrc_url = storage.upload_file(outputs.lrc, lrc_gcs_path)
job_manager.update_file_url(job_id, 'lyrics', 'lrc', lrc_url)
job_log.info("Uploaded karaoke.lrc")
logger.info(f"Job {job_id}: Uploaded karaoke.lrc")
# 9. Upload ASS subtitle file
if outputs.ass and os.path.exists(outputs.ass):
ass_gcs_path = f"jobs/{job_id}/lyrics/karaoke.ass"
ass_url = storage.upload_file(outputs.ass, ass_gcs_path)
job_manager.update_file_url(job_id, 'lyrics', 'ass', ass_url)
job_log.info("Uploaded karaoke.ass")
logger.info(f"Job {job_id}: Uploaded karaoke.ass")
# 10. Upload corrected text files
if outputs.corrected_txt and os.path.exists(outputs.corrected_txt):
txt_gcs_path = f"jobs/{job_id}/lyrics/corrected.txt"
txt_url = storage.upload_file(outputs.corrected_txt, txt_gcs_path)
job_manager.update_file_url(job_id, 'lyrics', 'corrected_txt', txt_url)
job_log.info("Uploaded corrected.txt")
logger.info(f"Job {job_id}: Uploaded corrected.txt")
# 11. Analyze backing vocals for intelligent instrumental selection
job_log.info("Analyzing backing vocals for instrumental selection...")
await _analyze_backing_vocals(job_id, job_manager, storage, job_log)
# 12. Transition based on prep_only flag and existing instrumental
if getattr(job, 'prep_only', False):
# Prep-only mode: stop here and mark as prep complete
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.PREP_COMPLETE,
progress=100,
message="Prep phase complete - download outputs to continue locally"
with open(original_corrections_path, 'r', encoding='utf-8') as f:
original_data = json.load(f)
# 3. Check if there are updated corrections (from review UI)
# The frontend sends only partial data: {corrections, corrected_segments}
updated_corrections_gcs = f"jobs/{job_id}/lyrics/corrections_updated.json"
if storage.file_exists(updated_corrections_gcs):
job_log.info("Found updated corrections from review, merging")
logger.info(f"Job {job_id}: Found updated corrections, merging")
updated_path = os.path.join(temp_dir, "corrections_updated.json")
storage.download_file(updated_corrections_gcs, updated_path)
with open(updated_path, 'r', encoding='utf-8') as f:
updated_data = json.load(f)
# Merge: update the original with the user's corrections
if 'corrections' in updated_data:
original_data['corrections'] = updated_data['corrections']
if 'corrected_segments' in updated_data:
original_data['corrected_segments'] = updated_data['corrected_segments']
job_log.info("Merged user corrections into original data")
logger.info(f"Job {job_id}: Merged user corrections into original data")
# 4. Convert to CorrectionResult
correction_result = CorrectionResult.from_dict(original_data)
job_log.info(f"Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
logger.info(f"Job {job_id}: Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
# 5. Download audio file
audio_path = os.path.join(temp_dir, "audio.flac")
audio_gcs_path = job.input_media_gcs_path
if not audio_gcs_path:
raise FileNotFoundError(f"No input audio path for job {job_id}")
job_log.info(f"Downloading audio from {audio_gcs_path}")
logger.info(f"Job {job_id}: Downloading audio from {audio_gcs_path}")
storage.download_file(audio_gcs_path, audio_path)
job_log.info(f"Audio downloaded: {os.path.getsize(audio_path)} bytes")
# Check if corrections have countdown padding and pad audio if needed
# This ensures the audio matches the shifted timestamps in the corrections
countdown_processor = CountdownProcessor(cache_dir=temp_dir, logger=logger)
if countdown_processor.has_countdown(correction_result):
job_log.info("Detected countdown in corrections - creating padded audio for sync")
audio_path = countdown_processor.create_padded_audio_only(audio_path)
job_log.info(f"Padded audio created: {audio_path}")
else:
job_log.info("No countdown detected in corrections - using original audio")
# 6. Get or create styles using the unified style loader
job_log.info("Loading style configuration...")
job_log.info(f" job.style_params_gcs_path: {job.style_params_gcs_path}")
job_log.info(f" job.style_assets: {list(job.style_assets.keys()) if job.style_assets else 'None'}")
styles_path, style_data = load_styles_from_gcs(
style_params_gcs_path=job.style_params_gcs_path,
style_assets=job.style_assets,
temp_dir=temp_dir,
download_func=storage.download_file,
logger=job_log,
)
job_log.info("=== RENDER VIDEO WORKER COMPLETE (PREP ONLY) ===")
duration = time.time() - start_time
root_span.set_attribute("duration_seconds", duration)
root_span.set_attribute("prep_only", True)
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s prep_only=true")
elif getattr(job, 'existing_instrumental_gcs_path', None):
# Existing instrumental provided - skip selection, auto-use it
# Store selection as 'custom' to indicate user-provided instrumental
job_manager.update_state_data(job_id, 'instrumental_selection', 'custom')
job_log.info("Existing instrumental provided - skipping selection, using user-provided file")
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.INSTRUMENTAL_SELECTED,
progress=82,
message="Using user-provided instrumental"
)
job_log.info("=== RENDER VIDEO WORKER COMPLETE (EXISTING INSTRUMENTAL) ===")
duration = time.time() - start_time
root_span.set_attribute("duration_seconds", duration)
root_span.set_attribute("existing_instrumental", True)
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s existing_instrumental=true")
# 7. Configure OutputGenerator
output_dir = os.path.join(temp_dir, "output")
cache_dir = os.path.join(temp_dir, "cache")
os.makedirs(output_dir, exist_ok=True)
os.makedirs(cache_dir, exist_ok=True)
# Trigger video worker directly since no user selection needed
from backend.workers.video_worker import run_video_worker
job_log.info("Triggering video worker for final encoding...")
await run_video_worker(job_id, job_manager, storage)
else:
# Normal mode: proceed to instrumental selection
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_INSTRUMENTAL_SELECTION,
progress=80,
message="Video rendered - select your instrumental"
job_log.info(f"Using styles from: {styles_path}")
# Get subtitle offset from job (user-specified timing adjustment)
subtitle_offset = getattr(job, 'subtitle_offset_ms', 0) or 0
if subtitle_offset != 0:
job_log.info(f"Applying subtitle offset: {subtitle_offset}ms")
config = OutputConfig(
output_dir=output_dir,
cache_dir=cache_dir,
output_styles_json=styles_path,
render_video=True,
generate_cdg=False, # CDG optional, generated separately
generate_plain_text=True,
generate_lrc=True,
video_resolution="4k",
subtitle_offset_ms=subtitle_offset
)
job_log.info("=== RENDER VIDEO WORKER COMPLETE ===")
duration = time.time() - start_time
root_span.set_attribute("duration_seconds", duration)
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s")
return True
job_log.info(f"OutputConfig: output_styles_json={config.output_styles_json}, render_video={config.render_video}")
output_generator = OutputGenerator(config, logger)
# 8. Generate outputs (video, LRC, ASS, etc.)
output_prefix = f"{job.artist or 'Unknown'} - {job.title or 'Unknown'}"
job_log.info(f"Generating outputs with prefix '{output_prefix}'")
logger.info(f"Job {job_id}: Generating outputs with prefix '{output_prefix}'")
outputs = output_generator.generate_outputs(
transcription_corrected=correction_result,
lyrics_results={}, # Reference lyrics already in correction_result
output_prefix=output_prefix,
audio_filepath=audio_path,
artist=job.artist,
title=job.title
)
# 9. Upload video to GCS
if outputs.video and os.path.exists(outputs.video):
video_size = os.path.getsize(outputs.video)
job_log.info(f"Video generated: {video_size} bytes")
video_gcs_path = f"jobs/{job_id}/videos/with_vocals.mkv"
video_url = storage.upload_file(outputs.video, video_gcs_path)
job_manager.update_file_url(job_id, 'videos', 'with_vocals', video_url)
job_log.info(f"Uploaded with_vocals.mkv to GCS")
logger.info(f"Job {job_id}: Uploaded with_vocals.mkv ({video_size} bytes)")
else:
job_log.error("Video generation failed - no output file produced!")
raise Exception("Video generation failed - no output file produced")
# 10. Upload LRC file
if outputs.lrc and os.path.exists(outputs.lrc):
lrc_gcs_path = f"jobs/{job_id}/lyrics/karaoke.lrc"
lrc_url = storage.upload_file(outputs.lrc, lrc_gcs_path)
job_manager.update_file_url(job_id, 'lyrics', 'lrc', lrc_url)
job_log.info("Uploaded karaoke.lrc")
logger.info(f"Job {job_id}: Uploaded karaoke.lrc")
# 11. Upload ASS subtitle file
if outputs.ass and os.path.exists(outputs.ass):
ass_gcs_path = f"jobs/{job_id}/lyrics/karaoke.ass"
ass_url = storage.upload_file(outputs.ass, ass_gcs_path)
job_manager.update_file_url(job_id, 'lyrics', 'ass', ass_url)
job_log.info("Uploaded karaoke.ass")
logger.info(f"Job {job_id}: Uploaded karaoke.ass")
# 12. Upload corrected text files
if outputs.corrected_txt and os.path.exists(outputs.corrected_txt):
txt_gcs_path = f"jobs/{job_id}/lyrics/corrected.txt"
txt_url = storage.upload_file(outputs.corrected_txt, txt_gcs_path)
job_manager.update_file_url(job_id, 'lyrics', 'corrected_txt', txt_url)
job_log.info("Uploaded corrected.txt")
logger.info(f"Job {job_id}: Uploaded corrected.txt")
# 13. Analyze backing vocals for intelligent instrumental selection
job_log.info("Analyzing backing vocals for instrumental selection...")
await _analyze_backing_vocals(job_id, job_manager, storage, job_log)
# 14. Transition based on prep_only flag and existing instrumental
if getattr(job, 'prep_only', False):
# Prep-only mode: stop here and mark as prep complete
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.PREP_COMPLETE,
progress=100,
message="Prep phase complete - download outputs to continue locally"
)
job_log.info("=== RENDER VIDEO WORKER COMPLETE (PREP ONLY) ===")
duration = time.time() - start_time
root_span.set_attribute("duration_seconds", duration)
root_span.set_attribute("prep_only", True)
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s prep_only=true")
elif getattr(job, 'existing_instrumental_gcs_path', None):
# Existing instrumental provided - skip selection, auto-use it
# Store selection as 'custom' to indicate user-provided instrumental
job_manager.update_state_data(job_id, 'instrumental_selection', 'custom')
job_log.info("Existing instrumental provided - skipping selection, using user-provided file")
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.INSTRUMENTAL_SELECTED,
progress=82,
message="Using user-provided instrumental"
)
job_log.info("=== RENDER VIDEO WORKER COMPLETE (EXISTING INSTRUMENTAL) ===")
duration = time.time() - start_time
root_span.set_attribute("duration_seconds", duration)
root_span.set_attribute("existing_instrumental", True)
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s existing_instrumental=true")
# Trigger video worker directly since no user selection needed
from backend.workers.video_worker import run_video_worker
job_log.info("Triggering video worker for final encoding...")
await run_video_worker(job_id, job_manager, storage)
else:
# Normal mode: proceed to instrumental selection
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_INSTRUMENTAL_SELECTION,
progress=80,
message="Video rendered - select your instrumental"
)
job_log.info("=== RENDER VIDEO WORKER COMPLETE ===")
duration = time.time() - start_time
root_span.set_attribute("duration_seconds", duration)
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s")
return True
except Exception as e:
duration = time.time() - start_time
+51 -1
View File
@@ -17,6 +17,8 @@ This Pulumi program manages:
- **Service Account**: For Cloud Run with appropriate IAM roles
- **Secrets**: Secret Manager secrets (you add the values)
- **IAM Bindings**: All necessary permissions
- **Cloud Function**: GDrive Validator for checking public share folder
- **Cloud Scheduler**: Daily trigger for GDrive validation
## Prerequisites
@@ -106,6 +108,10 @@ echo -n "https://your.red.url" | \
# Add OPS API key (for flacfetch audio search - private tracker)
echo -n "your-ops-api-key" | \
gcloud secrets versions add ops-api-key --data-file=-
# Add Pushbullet API key (for GDrive validator notifications)
echo -n "your-pushbullet-api-key" | \
gcloud secrets versions add pushbullet-api-key --data-file=-
```
Or use Pulumi config secrets:
@@ -205,10 +211,54 @@ If multiple people are working:
pulumi refresh # Sync state with actual cloud resources
```
## Deploying GDrive Validator
The GDrive Validator is a Cloud Function that runs daily to check for duplicate
sequence numbers, invalid filenames, and gaps in your public Google Drive folder.
### Initial Setup
1. Add your Pushbullet API key to Secret Manager:
```bash
echo -n "your-pushbullet-api-key" | \
gcloud secrets versions add pushbullet-api-key --data-file=-
```
2. Deploy the function:
```bash
cd functions/gdrive_validator
./deploy.sh
```
3. Test the function manually:
```bash
gcloud functions call gdrive-validator --region=us-central1
```
### How It Works
- Runs daily at 9 PM EST (6 PM Pacific) via Cloud Scheduler
- Lists all files in your Google Drive folder (CDG, MP4, MP4-720p subfolders)
- Checks for:
- Duplicate sequence numbers (e.g., two files with NOMAD-1107)
- Invalid filename formats (should be `NOMAD-XXXX - Artist - Title.ext`)
- Sequence gaps (with configurable known gaps)
- Sends Pushbullet notification if issues are found
- Returns JSON with validation results
### Configuration
The function uses environment variables:
- `GDRIVE_FOLDER_ID`: The Google Drive folder ID to validate (default: your public share)
- `PUSHBULLET_API_KEY`: From Secret Manager, for sending notifications
Known gaps are configured in `main.py` and should match your local `validate_and_sync.py`.
## Next Steps
1. Run `pulumi up` to create infrastructure
2. Add secret values
3. Build and deploy Cloud Run service
4. Update documentation to reference Pulumi workflow
4. Deploy GDrive validator function
5. Update documentation to reference Pulumi workflow
+129 -1
View File
@@ -12,10 +12,11 @@ Infrastructure includes:
- Cloud Tasks queues for worker coordination (Phase 1 scalability)
- Secret Manager secrets
- Cloud Run domain mapping
- Cloud Function for Google Drive validation (daily scheduled)
"""
import pulumi
import pulumi_gcp as gcp
from pulumi_gcp import storage, firestore, secretmanager, artifactregistry, cloudrun, serviceaccount, cloudtasks
from pulumi_gcp import storage, firestore, secretmanager, artifactregistry, cloudrun, serviceaccount, cloudtasks, cloudfunctions, cloudscheduler
# Get the current GCP project
project = gcp.organizations.get_project()
@@ -970,3 +971,130 @@ pulumi.export("queue_backlog_alert_id", queue_backlog_alert.name)
pulumi.export("memory_alert_id", memory_alert.name)
pulumi.export("service_unavailable_alert_id", service_unavailable_alert.name)
# ==================== Google Drive Validator Cloud Function ====================
# A lightweight Cloud Function that runs daily to validate the public Google Drive
# folder for duplicate sequence numbers, invalid filenames, and gaps.
# Sends Pushbullet notification if issues are detected.
# Pushbullet API key secret (for sending notifications)
pushbullet_api_key_secret = secretmanager.Secret(
"pushbullet-api-key",
secret_id="pushbullet-api-key",
replication=secretmanager.SecretReplicationArgs(
auto=secretmanager.SecretReplicationAutoArgs(),
),
)
# Service account for the validator Cloud Function
gdrive_validator_sa = serviceaccount.Account(
"gdrive-validator-sa",
account_id="gdrive-validator",
display_name="Google Drive Validator Function",
description="Service account for the GDrive validation Cloud Function",
)
# Grant the function access to Secret Manager (for Pushbullet API key)
gdrive_validator_secrets_iam = gcp.projects.IAMMember(
"gdrive-validator-secrets-access",
project=project_id,
role="roles/secretmanager.secretAccessor",
member=gdrive_validator_sa.email.apply(lambda email: f"serviceAccount:{email}"),
)
# Cloud Storage bucket for function source code
function_bucket = storage.Bucket(
"gdrive-validator-function-source",
name=f"gdrive-validator-source-{project_id}",
location="US-CENTRAL1",
force_destroy=True, # OK to delete since it just holds function code
uniform_bucket_level_access=True,
)
# Upload function source code as a ZIP archive
# Note: The actual upload is done via gcloud or Pulumi's archive resource
# For now, we reference the local directory - actual deployment uses gcloud
gdrive_validator_function = gcp.cloudfunctionsv2.Function(
"gdrive-validator-function",
name="gdrive-validator",
location="us-central1",
description="Validates Nomad Karaoke Google Drive folder for duplicates and issues",
build_config=gcp.cloudfunctionsv2.FunctionBuildConfigArgs(
runtime="python312",
entry_point="validate_gdrive",
source=gcp.cloudfunctionsv2.FunctionBuildConfigSourceArgs(
storage_source=gcp.cloudfunctionsv2.FunctionBuildConfigSourceStorageSourceArgs(
bucket=function_bucket.name,
object="gdrive-validator-source.zip",
),
),
),
service_config=gcp.cloudfunctionsv2.FunctionServiceConfigArgs(
available_memory="256M",
timeout_seconds=300, # 5 minutes should be plenty for listing files
min_instance_count=0,
max_instance_count=1,
service_account_email=gdrive_validator_sa.email,
environment_variables={
"GDRIVE_FOLDER_ID": "1laRKAyxo0v817SstfM5XkpbWiNKNAMSX",
# Set to "true" for daily summary notifications, "false" for issues-only
"NOTIFY_ON_SUCCESS": "true",
},
secret_environment_variables=[
gcp.cloudfunctionsv2.FunctionServiceConfigSecretEnvironmentVariableArgs(
key="PUSHBULLET_API_KEY",
project_id=project_id,
secret=pushbullet_api_key_secret.secret_id,
version="latest",
),
],
),
)
# Allow Cloud Scheduler to invoke the function
gdrive_validator_invoker = gcp.cloudfunctionsv2.FunctionIamMember(
"gdrive-validator-scheduler-invoker",
project=project_id,
location="us-central1",
cloud_function=gdrive_validator_function.name,
role="roles/cloudfunctions.invoker",
member=f"serviceAccount:service-{project.number}@gcp-sa-cloudscheduler.iam.gserviceaccount.com",
)
# Also allow the function's service account to invoke itself (for Cloud Scheduler)
gdrive_validator_sa_invoker = gcp.cloudfunctionsv2.FunctionIamMember(
"gdrive-validator-sa-invoker",
project=project_id,
location="us-central1",
cloud_function=gdrive_validator_function.name,
role="roles/cloudfunctions.invoker",
member=gdrive_validator_sa.email.apply(lambda email: f"serviceAccount:{email}"),
)
# Cloud Scheduler job to trigger validation daily at 6 AM Pacific
gdrive_validator_scheduler = cloudscheduler.Job(
"gdrive-validator-scheduler",
name="gdrive-validator-daily",
description="Daily validation of Nomad Karaoke Google Drive folder",
region="us-central1",
schedule="0 21 * * *", # 9:00 PM every day
time_zone="America/New_York",
http_target=cloudscheduler.JobHttpTargetArgs(
uri=gdrive_validator_function.url,
http_method="POST",
oidc_token=cloudscheduler.JobHttpTargetOidcTokenArgs(
service_account_email=gdrive_validator_sa.email,
),
),
retry_config=cloudscheduler.JobRetryConfigArgs(
retry_count=2,
min_backoff_duration="60s",
max_backoff_duration="300s",
),
)
# Export GDrive validator resources
pulumi.export("gdrive_validator_function_url", gdrive_validator_function.url)
pulumi.export("gdrive_validator_function_name", gdrive_validator_function.name)
pulumi.export("gdrive_validator_scheduler_name", gdrive_validator_scheduler.name)
pulumi.export("gdrive_validator_service_account", gdrive_validator_sa.email)
+68
View File
@@ -0,0 +1,68 @@
#!/bin/bash
# Deploy the GDrive Validator Cloud Function
#
# This script:
# 1. Creates a ZIP of the function source
# 2. Uploads it to GCS
# 3. Deploys the function via gcloud
#
# Prerequisites:
# - gcloud CLI authenticated
# - Pulumi infrastructure already deployed (creates the bucket)
#
# Usage:
# ./deploy.sh
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ID="${GOOGLE_CLOUD_PROJECT:-nomadkaraoke}"
REGION="us-central1"
FUNCTION_NAME="gdrive-validator"
BUCKET_NAME="gdrive-validator-source-${PROJECT_ID}"
echo "Deploying GDrive Validator Cloud Function..."
echo " Project: ${PROJECT_ID}"
echo " Region: ${REGION}"
echo " Function: ${FUNCTION_NAME}"
echo ""
# Change to function directory
cd "${SCRIPT_DIR}"
# Create ZIP of function source
echo "Creating source ZIP..."
rm -f /tmp/gdrive-validator-source.zip
zip -r /tmp/gdrive-validator-source.zip main.py requirements.txt
# Upload to GCS
echo "Uploading to GCS..."
gsutil cp /tmp/gdrive-validator-source.zip "gs://${BUCKET_NAME}/gdrive-validator-source.zip"
# Deploy the function
echo "Deploying function..."
gcloud functions deploy "${FUNCTION_NAME}" \
--gen2 \
--region="${REGION}" \
--runtime=python312 \
--source="gs://${BUCKET_NAME}/gdrive-validator-source.zip" \
--entry-point=validate_gdrive \
--trigger-http \
--memory=256MB \
--timeout=300s \
--min-instances=0 \
--max-instances=1 \
--service-account="gdrive-validator@${PROJECT_ID}.iam.gserviceaccount.com" \
--set-env-vars="GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX" \
--set-secrets="PUSHBULLET_API_KEY=pushbullet-api-key:latest" \
--project="${PROJECT_ID}"
echo ""
echo "Function deployed successfully!"
echo ""
echo "To test the function manually:"
echo " gcloud functions call ${FUNCTION_NAME} --region=${REGION} --project=${PROJECT_ID}"
echo ""
echo "Function URL:"
gcloud functions describe "${FUNCTION_NAME}" --region="${REGION}" --project="${PROJECT_ID}" --format='value(serviceConfig.uri)'
@@ -0,0 +1,451 @@
"""
Google Drive Validator Cloud Function
Validates the Nomad Karaoke public share folder for:
- Duplicate sequence numbers (NOMAD-XXXX)
- Invalid filename formats
- Sequence gaps (with configurable known gaps)
Sends Pushbullet notification if issues are detected.
Triggered daily via Cloud Scheduler.
"""
import os
import re
import json
import logging
from collections import defaultdict
from typing import Union
import functions_framework
import requests
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Configuration from environment variables
GDRIVE_FOLDER_ID = os.environ.get("GDRIVE_FOLDER_ID", "1laRKAyxo0v817SstfM5XkpbWiNKNAMSX")
PUSHBULLET_API_KEY = os.environ.get("PUSHBULLET_API_KEY", "")
# Set to "true" to receive daily summary even when no issues found
# Set to "false" to only receive notifications when issues are detected
NOTIFY_ON_SUCCESS = os.environ.get("NOTIFY_ON_SUCCESS", "true").lower() == "true"
# Known gaps configuration - matches the local validate_and_sync.py script
# Format: Directory name -> List of ranges (inclusive) or individual numbers to exclude
KNOWN_GAPS = {
"MP4": [
532
],
"MP4-720p": [
532
],
"CDG": [
(4, 6), # Early missing files
21, 30, 41, # Individual missing files
67, 79, 168, 195,
(197, 329), # Large historical gap
(331, 377), # Another large gap
381, 382,
(385, 387),
(393, 395),
397, 398, 399, 402,
439, 443, 451,
532, 556
]
}
def expand_gaps(gaps: list[Union[int, tuple]]) -> set[int]:
"""Convert a list of gaps (individual numbers or ranges) into a set of all excluded numbers."""
excluded = set()
for gap in gaps:
if isinstance(gap, tuple):
start, end = gap
excluded.update(range(start, end + 1))
else:
excluded.add(gap)
return excluded
# Pre-compute excluded numbers for each directory
EXCLUDED_NUMBERS = {
dir_name: expand_gaps(gaps)
for dir_name, gaps in KNOWN_GAPS.items()
}
def get_drive_service():
"""Create a Google Drive API service using default credentials."""
# In Cloud Functions, use Application Default Credentials
# The function's service account will be used automatically
from google.auth import default
credentials, _ = default(scopes=['https://www.googleapis.com/auth/drive.readonly'])
return build('drive', 'v3', credentials=credentials)
def list_folder_contents(service, folder_id: str) -> dict[str, list[str]]:
"""
List all files in a Google Drive folder and its subfolders.
Returns a dict mapping subfolder name to list of filenames.
Expected structure:
- CDG/ (contains .zip files)
- MP4/ (contains .mp4 files)
- MP4-720p/ (contains .mp4 files)
"""
results = {}
try:
# First, list the top-level subfolders (CDG, MP4, MP4-720p)
query = f"'{folder_id}' in parents and mimeType='application/vnd.google-apps.folder' and trashed=false"
response = service.files().list(
q=query,
fields="files(id, name)",
pageSize=100
).execute()
subfolders = response.get('files', [])
logger.info(f"Found {len(subfolders)} subfolders in root folder")
for folder in subfolders:
folder_name = folder['name']
folder_id_inner = folder['id']
# Only process expected folders
if folder_name not in ['CDG', 'MP4', 'MP4-720p']:
logger.warning(f"Unexpected folder: {folder_name}")
continue
# List all files in this subfolder
files = []
page_token = None
while True:
query = f"'{folder_id_inner}' in parents and trashed=false and mimeType!='application/vnd.google-apps.folder'"
response = service.files().list(
q=query,
fields="nextPageToken, files(name)",
pageSize=1000,
pageToken=page_token
).execute()
files.extend([f['name'] for f in response.get('files', [])])
page_token = response.get('nextPageToken')
if not page_token:
break
results[folder_name] = files
logger.info(f"Found {len(files)} files in {folder_name}/")
except HttpError:
logger.exception("Error accessing Google Drive")
raise
return results
# Files to ignore during validation (these are not karaoke files)
IGNORED_FILES = {
'.DS_Store',
'.keep',
'.gitkeep',
'kj-nomad.index.json',
'desktop.ini',
'Thumbs.db',
}
def should_ignore_file(filename: str) -> bool:
"""Check if a file should be ignored during validation."""
return filename in IGNORED_FILES or filename.startswith('.')
def validate_filename_format(filename: str) -> bool:
"""Check if filename matches the expected format: NOMAD-XXXX - Artist - Title.(mp4|zip)"""
if should_ignore_file(filename):
return True # Ignored files pass validation
pattern = r"^NOMAD-\d{4} - .+ - .+\.(mp4|zip)$"
return bool(re.match(pattern, filename))
def get_sequence_number(filename: str) -> int | None:
"""Extract sequence number from filename. Returns None if not found."""
match = re.match(r"NOMAD-(\d{4})", filename)
if match:
return int(match.group(1))
return None
def validate_files(files_by_folder: dict[str, list[str]]) -> dict:
"""
Validate all files and return a dict of issues found.
Returns:
{
'duplicates': {'MP4': {1107: ['file1.mp4', 'file2.mp4']}, ...},
'invalid_filenames': {'CDG': ['bad_file.json'], ...},
'gaps': {'MP4': [123, 124, 125], ...},
'summary': {'total_files': 3000, 'mp4': 1127, ...}
}
"""
issues = {
'duplicates': defaultdict(dict),
'invalid_filenames': defaultdict(list),
'gaps': defaultdict(list),
'summary': {}
}
total_files = 0
for folder_name, files in files_by_folder.items():
# Filter out ignored files for counting
karaoke_files = [f for f in files if not should_ignore_file(f)]
total_files += len(karaoke_files)
issues['summary'][folder_name.lower().replace('-', '_')] = len(karaoke_files)
# Check for invalid filenames (skip ignored files)
for filename in files:
if should_ignore_file(filename):
continue
if not validate_filename_format(filename):
issues['invalid_filenames'][folder_name].append(filename)
# Check for duplicate sequence numbers
seq_to_files = defaultdict(list)
valid_files = [f for f in files if not should_ignore_file(f) and validate_filename_format(f)]
for filename in valid_files:
seq_num = get_sequence_number(filename)
if seq_num is not None:
seq_to_files[seq_num].append(filename)
for seq_num, filenames in seq_to_files.items():
if len(filenames) > 1:
issues['duplicates'][folder_name][seq_num] = filenames
# Check for sequence gaps
if valid_files:
sequence_numbers = set()
for filename in valid_files:
seq_num = get_sequence_number(filename)
if seq_num is not None:
sequence_numbers.add(seq_num)
if sequence_numbers:
min_num = min(sequence_numbers)
max_num = max(sequence_numbers)
expected_range = set(range(min_num, max_num + 1))
excluded = EXCLUDED_NUMBERS.get(folder_name, set())
missing = sorted(expected_range - sequence_numbers - excluded)
if missing:
issues['gaps'][folder_name] = missing
issues['summary']['total'] = total_files
# Convert defaultdicts to regular dicts for cleaner output
issues['duplicates'] = dict(issues['duplicates'])
issues['invalid_filenames'] = dict(issues['invalid_filenames'])
issues['gaps'] = dict(issues['gaps'])
return issues
def has_issues(issues: dict) -> bool:
"""Check if there are any validation issues."""
return (
bool(issues['duplicates']) or
bool(issues['invalid_filenames']) or
bool(issues['gaps'])
)
def format_notification(issues: dict) -> tuple[str, str]:
"""Format issues into a Pushbullet notification (title, body)."""
title = "⚠️ Karaoke GDrive Validation Issues Found"
lines = []
issue_count = 0
# Duplicates
if issues['duplicates']:
lines.append("DUPLICATES:")
for folder, dupes in issues['duplicates'].items():
for seq_num, filenames in dupes.items():
issue_count += 1
lines.append(f" • {folder}: NOMAD-{seq_num:04d} appears {len(filenames)} times")
for f in filenames[:3]: # Limit to 3 examples
lines.append(f" - {f}")
if len(filenames) > 3:
lines.append(f" - ...and {len(filenames) - 3} more")
lines.append("")
# Invalid filenames
if issues['invalid_filenames']:
lines.append("INVALID FILENAMES:")
for folder, filenames in issues['invalid_filenames'].items():
for f in filenames[:5]: # Limit to 5 examples
issue_count += 1
lines.append(f" • {folder}: {f}")
if len(filenames) > 5:
lines.append(f" • ...and {len(filenames) - 5} more in {folder}")
lines.append("")
# Gaps (only show if not too many)
if issues['gaps']:
lines.append("SEQUENCE GAPS:")
for folder, missing in issues['gaps'].items():
if len(missing) <= 10:
issue_count += len(missing)
lines.append(f" • {folder}: missing {', '.join(map(str, missing))}")
else:
issue_count += len(missing)
lines.append(f" • {folder}: {len(missing)} gaps (first 5: {', '.join(map(str, missing[:5]))}...)")
lines.append("")
# Summary
summary = issues['summary']
lines.append(f"Checked: {summary.get('mp4', 0)} MP4, {summary.get('mp4_720p', 0)} 720p, {summary.get('cdg', 0)} CDG files")
body = f"{issue_count} issue(s) detected:\n\n" + "\n".join(lines)
return title, body
def send_pushbullet_notification(title: str, body: str) -> bool:
"""Send a notification via Pushbullet API."""
if not PUSHBULLET_API_KEY:
logger.warning("PUSHBULLET_API_KEY not set, skipping notification")
return False
try:
response = requests.post(
"https://api.pushbullet.com/v2/pushes",
headers={
"Access-Token": PUSHBULLET_API_KEY,
"Content-Type": "application/json"
},
json={
"type": "note",
"title": title,
"body": body
},
timeout=30
)
response.raise_for_status()
logger.info("Pushbullet notification sent successfully")
return True
except requests.RequestException:
logger.exception("Failed to send Pushbullet notification")
return False
@functions_framework.http
def validate_gdrive(request):
"""
HTTP Cloud Function entry point.
Validates the Google Drive folder and sends notifications if issues are found.
Returns JSON with validation results.
"""
logger.info("Starting Google Drive validation...")
try:
# Get Drive service
service = get_drive_service()
# List all files
files_by_folder = list_folder_contents(service, GDRIVE_FOLDER_ID)
if not files_by_folder:
logger.warning("No folders found in Google Drive")
return json.dumps({
"status": "warning",
"message": "No folders found in Google Drive folder"
}), 200, {"Content-Type": "application/json"}
# Validate files
issues = validate_files(files_by_folder)
# Check if there are any issues
if has_issues(issues):
logger.warning(f"Validation issues found: {issues}")
# Send Pushbullet notification
title, body = format_notification(issues)
notification_sent = send_pushbullet_notification(title, body)
return json.dumps({
"status": "issues_found",
"issues": issues,
"notification_sent": notification_sent
}), 200, {"Content-Type": "application/json"}
else:
logger.info("No validation issues found")
summary = issues['summary']
# Send daily summary notification if enabled
if NOTIFY_ON_SUCCESS:
title = "✅ Karaoke GDrive: All Clear"
body = (
f"Daily validation complete - no issues found.\n\n"
f"📊 Files checked:\n"
f" • {summary.get('mp4', 0):,} MP4 tracks\n"
f" • {summary.get('mp4_720p', 0):,} MP4-720p tracks\n"
f" • {summary.get('cdg', 0):,} CDG tracks\n"
f" • {summary.get('total', 0):,} total files\n\n"
f"✓ No duplicates\n"
f"✓ No invalid filenames\n"
f"✓ No sequence gaps"
)
notification_sent = send_pushbullet_notification(title, body)
else:
notification_sent = False
return json.dumps({
"status": "ok",
"message": "No validation issues found",
"summary": summary,
"notification_sent": notification_sent
}), 200, {"Content-Type": "application/json"}
except Exception as e:
logger.exception("Error during validation")
# Try to send error notification
try:
send_pushbullet_notification(
"❌ Karaoke GDrive Validator Error",
f"Validation failed with error:\n\n{e!s}"
)
except Exception as notify_err:
logger.warning("Failed to send error notification: %s", notify_err)
return json.dumps({
"status": "error",
"message": str(e)
}), 500, {"Content-Type": "application/json"}
# For local testing
if __name__ == "__main__":
import sys
# Set up test environment
os.environ.setdefault("GDRIVE_FOLDER_ID", "1laRKAyxo0v817SstfM5XkpbWiNKNAMSX")
print("Testing Google Drive validation...")
# Create a mock request
class MockRequest:
pass
result = validate_gdrive(MockRequest())
print(f"\nResult: {result}")
@@ -0,0 +1,10 @@
# Google Drive API
google-api-python-client>=2.100.0
google-auth>=2.23.0
# Cloud Functions framework
functions-framework>=3.0.0
# HTTP requests for Pushbullet API
requests>=2.31.0
+736 -19
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
@@ -63,22 +76,35 @@ class AudioSearchResult:
"target_file": self.target_file,
}
# If we have a raw_result (flacfetch Release), include its full data
# If we have a raw_result (flacfetch Release or dict), include its full data
# This enables rich display on the remote CLI
# raw_result can be either:
# - A dict (from remote flacfetch API)
# - A Release object (from local flacfetch)
if self.raw_result:
try:
release_dict = self.raw_result.to_dict()
# Merge Release fields into result (they may override basic fields)
for key in ['year', 'label', 'edition_info', 'release_type', 'channel',
'view_count', 'size_bytes', 'target_file_size', 'track_pattern',
'match_score', 'formatted_size', 'formatted_duration',
'formatted_views', 'is_lossless', 'quality_str', 'quality']:
if key in release_dict:
# Use 'quality_data' for the quality dict to avoid confusion with quality string
result_key = 'quality_data' if key == 'quality' else key
result[result_key] = release_dict[key]
except AttributeError:
pass # raw_result doesn't have to_dict() method
if isinstance(self.raw_result, dict):
# Remote flacfetch API returns dicts directly
release_dict = self.raw_result
else:
# Local flacfetch returns Release objects
try:
release_dict = self.raw_result.to_dict()
except AttributeError:
release_dict = {} # raw_result doesn't have to_dict() method
# Merge Release fields into result (they may override basic fields)
for key in ['year', 'label', 'edition_info', 'release_type', 'channel',
'view_count', 'size_bytes', 'target_file_size', 'track_pattern',
'match_score', 'formatted_size', 'formatted_duration',
'formatted_views', 'is_lossless', 'quality_str']:
if key in release_dict:
result[key] = release_dict[key]
# Handle quality dict - remote API uses 'quality_data', local uses 'quality'
if 'quality_data' in release_dict:
result['quality_data'] = release_dict['quality_data']
elif 'quality' in release_dict and isinstance(release_dict['quality'], dict):
result['quality_data'] = release_dict['quality']
return result
@@ -868,26 +894,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}")
+233 -11
View File
@@ -31,13 +31,16 @@ import webbrowser
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from typing import Any, Dict, Optional
from typing import Any, Dict, List, Optional
import requests
from .cli_args import create_parser, process_style_overrides, is_url, is_file
# Use flacfetch's shared display functions for consistent formatting
from flacfetch import print_releases, Release
from flacfetch.core.categorize import categorize_releases
from flacfetch.core.models import TrackQuery
from flacfetch.interface.cli import print_categorized_releases
class JobStatus(str, Enum):
@@ -137,7 +140,18 @@ class RemoteKaraokeClient:
return None
def refresh_auth(self) -> bool:
"""Refresh authentication token."""
"""Refresh authentication token.
Only refreshes if we're using a gcloud-based token. If the user
provided a static token via KARAOKE_GEN_AUTH_TOKEN, we keep that
since it doesn't expire like gcloud identity tokens.
"""
# Don't refresh if using a static admin token from env
if os.environ.get('KARAOKE_GEN_AUTH_TOKEN'):
# Already have a valid static token, no need to refresh
return True
# Try to refresh gcloud identity token
token = self._get_auth_token_from_gcloud()
if token:
self.config.auth_token = token
@@ -1192,6 +1206,7 @@ class RemoteKaraokeClient:
artist: Artist name to search for
title: Song title to search for
auto_download: Automatically select best audio source (skip interactive selection)
style_params_path: Path to style_params.json (optional)
... other args same as submit_job()
Returns:
@@ -1232,6 +1247,40 @@ class RemoteKaraokeClient:
if other_stems_models:
request_data['other_stems_models'] = other_stems_models
# Prepare style files for upload if provided
style_files = []
local_style_files: Dict[str, str] = {} # file_type -> local_path
if style_params_path and os.path.isfile(style_params_path):
self.logger.info(f"Parsing style configuration: {style_params_path}")
# Add the style_params.json itself
style_files.append({
'filename': Path(style_params_path).name,
'content_type': 'application/json',
'file_type': 'style_params'
})
local_style_files['style_params'] = style_params_path
# Parse style params to find referenced files (backgrounds, fonts)
style_assets = self._parse_style_params(style_params_path)
for asset_key, asset_path in style_assets.items():
if os.path.isfile(asset_path):
ext = Path(asset_path).suffix.lower()
content_type = self._get_content_type(ext)
style_files.append({
'filename': Path(asset_path).name,
'content_type': content_type,
'file_type': asset_key # e.g., 'style_intro_background'
})
local_style_files[asset_key] = asset_path
self.logger.info(f" Will upload style asset: {asset_key}")
if style_files:
request_data['style_files'] = style_files
self.logger.info(f"Including {len(style_files)} style files in request")
response = self._request('POST', '/api/audio-search/search', json=request_data)
if response.status_code == 404:
@@ -1248,7 +1297,52 @@ class RemoteKaraokeClient:
error_detail = response.text
raise RuntimeError(f"Error searching for audio: {error_detail}")
return response.json()
result = response.json()
# Upload style files if we have signed URLs
style_upload_urls = result.get('style_upload_urls', [])
if style_upload_urls and local_style_files:
self.logger.info(f"Uploading {len(style_upload_urls)} style files...")
for url_info in style_upload_urls:
file_type = url_info['file_type']
upload_url = url_info['upload_url']
local_path = local_style_files.get(file_type)
if not local_path:
self.logger.warning(f"No local file for {file_type}, skipping upload")
continue
self.logger.info(f" Uploading {file_type}: {Path(local_path).name}")
try:
with open(local_path, 'rb') as f:
file_content = f.read()
# Use the content type from the original file info, not re-derived
# This ensures it matches the signed URL which was generated with
# the same content type we specified in the request
content_type = self._get_content_type(local_path)
# Use PUT to upload directly to signed URL
upload_response = requests.put(
upload_url,
data=file_content,
headers={'Content-Type': content_type},
timeout=60
)
if upload_response.status_code not in (200, 201):
self.logger.error(f"Failed to upload {file_type}: {upload_response.status_code}")
else:
self.logger.info(f" ✓ Uploaded {file_type}")
except Exception as e:
self.logger.error(f"Error uploading {file_type}: {e}")
self.logger.info("Style file uploads complete")
return result
def get_audio_search_results(self, job_id: str) -> Dict[str, Any]:
"""Get audio search results for a job awaiting selection."""
@@ -1613,8 +1707,34 @@ class JobMonitor:
"quality_str": result.get('quality_str') or result.get('quality', ''),
}
def _convert_to_release_objects(self, release_dicts: List[Dict[str, Any]]) -> List[Release]:
"""
Convert API result dicts to Release objects for categorization.
Used by handle_audio_selection() to enable categorized display
for large result sets (10+ results).
Args:
release_dicts: List of dicts in Release-compatible format
Returns:
List of Release objects (skipping any that fail to convert)
"""
releases = []
for d in release_dicts:
try:
releases.append(Release.from_dict(d))
except Exception as e:
self.logger.debug(f"Failed to convert result to Release: {e}")
return releases
def handle_audio_selection(self, job_id: str) -> None:
"""Handle audio source selection interaction (Batch 5)."""
"""Handle audio source selection interaction (Batch 5).
For 10+ results, uses categorized display (grouped by Top Seeded,
Album Releases, Hi-Res, etc.) with a 'more' command to show full list.
For smaller result sets, uses flat list display.
"""
self.logger.info("=" * 60)
self.logger.info("AUDIO SOURCE SELECTION NEEDED")
self.logger.info("=" * 60)
@@ -1624,6 +1744,7 @@ class JobMonitor:
results_data = self.client.get_audio_search_results(job_id)
results = results_data.get('results', [])
artist = results_data.get('artist', 'Unknown')
title = results_data.get('title', 'Unknown')
if not results:
self.logger.error("No search results available")
@@ -1638,23 +1759,71 @@ class JobMonitor:
# This gives us the same rich, colorized output as the local CLI
release_dicts = [self._convert_api_result_to_release_dict(r) for r in results]
# Use flacfetch's shared display function
print_releases(release_dicts, target_artist=artist, use_colors=True)
# Convert to Release objects for categorization
release_objects = self._convert_to_release_objects(release_dicts)
# Use categorized display for large result sets (10+)
# This groups results into categories: Top Seeded, Album Releases, Hi-Res, etc.
use_categorized = len(release_objects) >= 10
if use_categorized:
# Create query for categorization
query = TrackQuery(artist=artist, title=title)
categorized = categorize_releases(release_objects, query)
# print_categorized_releases returns the flattened list of displayed releases
display_releases = print_categorized_releases(categorized, target_artist=artist, use_colors=True)
showing_categorized = True
else:
# Small result set - use simple flat list
print_releases(release_dicts, target_artist=artist, use_colors=True)
display_releases = release_objects
showing_categorized = False
selection_index = -1
while selection_index < 0:
try:
choice = input(f"\nSelect a release (1-{len(results)}, 0 to cancel): ").strip()
if showing_categorized:
prompt = f"\nSelect (1-{len(display_releases)}), 'more' for full list, 0 to cancel: "
else:
prompt = f"\nSelect a release (1-{len(display_releases)}, 0 to cancel): "
choice = input(prompt).strip().lower()
if choice == "0":
self.logger.info("Selection cancelled by user")
raise KeyboardInterrupt
# Handle 'more' command to show full flat list
if choice in ('more', 'm', 'all', 'a') and showing_categorized:
print("\n" + "=" * 60)
print("FULL LIST (all results)")
print("=" * 60 + "\n")
print_releases(release_dicts, target_artist=artist, use_colors=True)
display_releases = release_objects
showing_categorized = False
continue
choice_num = int(choice)
if 1 <= choice_num <= len(results):
selection_index = choice_num - 1
if 1 <= choice_num <= len(display_releases):
# Map selection back to original results index for API call
selected_release = display_releases[choice_num - 1]
# Find matching index in original results by download_url
selection_index = self._find_original_index(
selected_release, results, release_objects
)
if selection_index < 0:
# Fallback: use display index if mapping fails
self.logger.warning("Could not map selection to original index, using display index")
selection_index = choice_num - 1
else:
print(f"Please enter a number between 0 and {len(results)}")
print(f"Please enter a number between 0 and {len(display_releases)}")
except ValueError:
print("Please enter a valid number")
if showing_categorized:
print("Please enter a number or 'more'")
else:
print("Please enter a valid number")
except KeyboardInterrupt:
print()
raise
@@ -1672,6 +1841,58 @@ class JobMonitor:
except Exception as e:
self.logger.error(f"Error handling audio selection: {e}")
def _find_original_index(
self,
selected_release: Release,
original_results: List[Dict[str, Any]],
release_objects: List[Release],
) -> int:
"""
Map a selected Release back to its index in the original API results.
This is needed because categorized display may reorder results,
but the API selection endpoint needs the original index.
Args:
selected_release: The Release object user selected
original_results: Original API results (list of dicts)
release_objects: Release objects in same order as original_results
Returns:
Index in original_results, or -1 if not found
"""
# First try: match by object identity in release_objects
for i, release in enumerate(release_objects):
if release is selected_release:
return i
# Second try: match by download_url
selected_url = getattr(selected_release, 'download_url', None)
if selected_url:
for i, r in enumerate(original_results):
if r.get('url') == selected_url:
return i
# Third try: match by info_hash (for torrent sources)
selected_hash = getattr(selected_release, 'info_hash', None)
if selected_hash:
for i, r in enumerate(original_results):
if r.get('source_id') == selected_hash:
return i
# Fourth try: match by title + artist + provider
selected_title = getattr(selected_release, 'title', '')
selected_artist = getattr(selected_release, 'artist', '')
selected_source = getattr(selected_release, 'source_name', '')
for i, r in enumerate(original_results):
if (r.get('title') == selected_title and
r.get('artist') == selected_artist and
r.get('provider') == selected_source):
return i
return -1
def _open_instrumental_review_and_wait(self, job_id: str) -> None:
"""Open browser to instrumental review UI and wait for selection."""
@@ -2833,6 +3054,7 @@ def main():
artist=artist,
title=title,
auto_download=auto_download,
style_params_path=args.style_params_json,
enable_cdg=args.enable_cdg,
enable_txt=args.enable_txt,
brand_prefix=args.brand_prefix,
@@ -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."""
Generated
+67 -47
View File
@@ -1873,14 +1873,14 @@ platformdirs = ">=4.3.6"
[[package]]
name = "flacfetch"
version = "0.8.0"
version = "0.11.0"
description = "Search and download high-quality audio from multiple sources"
optional = false
python-versions = ">=3.8"
groups = ["main"]
files = [
{file = "flacfetch-0.8.0-py3-none-any.whl", hash = "sha256:a684f902a95f4d89f5ca0d7577e56fc17024f07d89fa198f5505300c25ba4c50"},
{file = "flacfetch-0.8.0.tar.gz", hash = "sha256:53eaae2e85099f05d6a667c13edbcac650faeacd366400db5b564c4a48b1fc9d"},
{file = "flacfetch-0.11.0-py3-none-any.whl", hash = "sha256:56657cba85cf6e390b4213d3f44d9fd05603138735d01dd10ebc1f695b5f77f3"},
{file = "flacfetch-0.11.0.tar.gz", hash = "sha256:56bbc3a66f1241c831490a88c51fcbfd5d5026108daac9d41f5a23c66c1f79b3"},
]
[package.dependencies]
@@ -1889,10 +1889,12 @@ transmission-rpc = ">=7.0.0"
yt-dlp = ">=2023.0.0"
[package.extras]
all = ["flacfetch[api]", "flacfetch[dev]", "flacfetch[remote]"]
api = ["fastapi (>=0.104.0)", "google-cloud-storage (>=2.13.0)", "httpx (>=0.25.0)", "pydantic (>=2.0.0)", "uvicorn[standard] (>=0.24.0)"]
all = ["fastapi (>=0.115.0)", "google-cloud-secret-manager (>=2.16.0)", "google-cloud-storage (>=2.13.0)", "httpx (>=0.28.0)", "mypy (>=1.0.0)", "pydantic (>=2.0.0)", "pytest (>=7.0.0)", "pytest-asyncio (>=0.23.0)", "pytest-cov (>=4.0.0)", "pytest-mock (>=3.10.0)", "ruff (>=0.1.0)", "spotipy (>=2.25.1)", "types-requests (>=2.28.0)", "uvicorn[standard] (>=0.24.0)", "yt-dlp-ejs (>=0.3.0)"]
api = ["fastapi (>=0.115.0)", "google-cloud-secret-manager (>=2.16.0)", "google-cloud-storage (>=2.13.0)", "httpx (>=0.28.0)", "pydantic (>=2.0.0)", "uvicorn[standard] (>=0.24.0)"]
dev = ["mypy (>=1.0.0)", "pytest (>=7.0.0)", "pytest-asyncio (>=0.23.0)", "pytest-cov (>=4.0.0)", "pytest-mock (>=3.10.0)", "ruff (>=0.1.0)", "types-requests (>=2.28.0)"]
remote = ["httpx (>=0.25.0)"]
ejs = ["yt-dlp-ejs (>=0.3.0)"]
remote = ["httpx (>=0.28.0)"]
spotify = ["spotipy (>=2.25.1)"]
[[package]]
name = "flatbuffers"
@@ -2816,22 +2818,26 @@ testing = ["pytest (>=6)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-ena
[[package]]
name = "jaraco-context"
version = "6.0.1"
version = "6.0.2"
description = "Useful decorators and context managers"
optional = false
python-versions = ">=3.8"
python-versions = ">=3.9"
groups = ["dev"]
files = [
{file = "jaraco.context-6.0.1-py3-none-any.whl", hash = "sha256:f797fc481b490edb305122c9181830a3a5b76d84ef6d1aef2fb9b47ab956f9e4"},
{file = "jaraco_context-6.0.1.tar.gz", hash = "sha256:9bae4ea555cf0b14938dc0aee7c9f32ed303aa20a3b73e7dc80111628792d1b3"},
{file = "jaraco_context-6.0.2-py3-none-any.whl", hash = "sha256:55fc21af4b4f9ca94aa643b6ee7fe13b1e4c01abf3aeb98ca4ad9c80b741c786"},
{file = "jaraco_context-6.0.2.tar.gz", hash = "sha256:953ae8dddb57b1d791bf72ea1009b32088840a7dd19b9ba16443f62be919ee57"},
]
[package.dependencies]
"backports.tarfile" = {version = "*", markers = "python_version < \"3.12\""}
[package.extras]
check = ["pytest-checkdocs (>=2.4)", "pytest-ruff (>=0.2.1) ; sys_platform != \"cygwin\""]
cover = ["pytest-cov"]
doc = ["furo", "jaraco.packaging (>=9.3)", "jaraco.tidelift (>=1.4)", "rst.linker (>=1.9)", "sphinx (>=3.5)", "sphinx-lint"]
test = ["portend", "pytest (>=6,!=8.1.*)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=2.2)", "pytest-mypy", "pytest-ruff (>=0.2.1) ; sys_platform != \"cygwin\""]
enabler = ["pytest-enabler (>=3.4)"]
test = ["jaraco.test (>=5.6.0)", "portend", "pytest (>=6,!=8.1.*)"]
type = ["mypy (<1.19) ; platform_python_implementation == \"PyPy\"", "pytest-mypy (>=1.0.1)"]
[[package]]
name = "jaraco-functools"
@@ -3360,14 +3366,14 @@ tiktoken = ">=0.7.0,<1.0.0"
[[package]]
name = "langfuse"
version = "3.11.1"
version = "3.11.2"
description = "A client library for accessing langfuse"
optional = false
python-versions = "<4.0,>=3.10"
groups = ["main"]
files = [
{file = "langfuse-3.11.1-py3-none-any.whl", hash = "sha256:f489c97fb2231b14e75383100158cdd6a158b87c1e9c9f96b2cdcbc015c48319"},
{file = "langfuse-3.11.1.tar.gz", hash = "sha256:52bdb5bae2bb7c2add22777a0f88a1a5c96f90ec994935b773992153e57e94f8"},
{file = "langfuse-3.11.2-py3-none-any.whl", hash = "sha256:84faea9f909694023cc7f0eb45696be190248c8790424f22af57ca4cd7a29f2d"},
{file = "langfuse-3.11.2.tar.gz", hash = "sha256:ab5f296a8056815b7288c7f25bc308a5e79f82a8634467b25daffdde99276e09"},
]
[package.dependencies]
@@ -3452,14 +3458,14 @@ orjson = ">=3.10.1"
[[package]]
name = "langsmith"
version = "0.5.0"
version = "0.5.1"
description = "Client library to connect to the LangSmith Observability and Evaluation Platform."
optional = false
python-versions = ">=3.10"
groups = ["main"]
files = [
{file = "langsmith-0.5.0-py3-none-any.whl", hash = "sha256:a83750cb3dccb33148d4ffe005e3e03080fad13e01671efbb74c9a68813bfef8"},
{file = "langsmith-0.5.0.tar.gz", hash = "sha256:5cadf1ddd30e838cf61679f4a776aaef638d4b02ffbceba9f73283caebd39e1b"},
{file = "langsmith-0.5.1-py3-none-any.whl", hash = "sha256:70aa2a4c75add3f723c3bbac80dbb8adc575077834d3a733ee1ec133206ff351"},
{file = "langsmith-0.5.1.tar.gz", hash = "sha256:6a10b38cb4ce58941b7f1dbdf41a461868605dd0162bf05d17690f2e4b6e50e7"},
]
[package.dependencies]
@@ -4379,6 +4385,18 @@ files = [
{file = "musicbrainzngs-0.7.1.tar.gz", hash = "sha256:ab1c0100fd0b305852e65f2ed4113c6de12e68afd55186987b8ed97e0f98e627"},
]
[[package]]
name = "mutagen"
version = "1.47.0"
description = "read and write audio tags for many formats"
optional = false
python-versions = ">=3.7"
groups = ["main"]
files = [
{file = "mutagen-1.47.0-py3-none-any.whl", hash = "sha256:edd96f50c5907a9539d8e5bba7245f62c9f520aef333d13392a79a4f70aca719"},
{file = "mutagen-1.47.0.tar.gz", hash = "sha256:719fadef0a978c31b4cf3c956261b3c58b6948b32023078a2117b1de09f0fc99"},
]
[[package]]
name = "mypy-extensions"
version = "1.1.0"
@@ -5934,36 +5952,38 @@ files = [
[[package]]
name = "psutil"
version = "7.1.3"
version = "7.2.0"
description = "Cross-platform lib for process and system monitoring."
optional = false
python-versions = ">=3.6"
groups = ["main"]
files = [
{file = "psutil-7.1.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0005da714eee687b4b8decd3d6cc7c6db36215c9e74e5ad2264b90c3df7d92dc"},
{file = "psutil-7.1.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:19644c85dcb987e35eeeaefdc3915d059dac7bd1167cdcdbf27e0ce2df0c08c0"},
{file = "psutil-7.1.3-cp313-cp313t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:95ef04cf2e5ba0ab9eaafc4a11eaae91b44f4ef5541acd2ee91d9108d00d59a7"},
{file = "psutil-7.1.3-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1068c303be3a72f8e18e412c5b2a8f6d31750fb152f9cb106b54090296c9d251"},
{file = "psutil-7.1.3-cp313-cp313t-win_amd64.whl", hash = "sha256:18349c5c24b06ac5612c0428ec2a0331c26443d259e2a0144a9b24b4395b58fa"},
{file = "psutil-7.1.3-cp313-cp313t-win_arm64.whl", hash = "sha256:c525ffa774fe4496282fb0b1187725793de3e7c6b29e41562733cae9ada151ee"},
{file = "psutil-7.1.3-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:b403da1df4d6d43973dc004d19cee3b848e998ae3154cc8097d139b77156c353"},
{file = "psutil-7.1.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:ad81425efc5e75da3f39b3e636293360ad8d0b49bed7df824c79764fb4ba9b8b"},
{file = "psutil-7.1.3-cp314-cp314t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8f33a3702e167783a9213db10ad29650ebf383946e91bc77f28a5eb083496bc9"},
{file = "psutil-7.1.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fac9cd332c67f4422504297889da5ab7e05fd11e3c4392140f7370f4208ded1f"},
{file = "psutil-7.1.3-cp314-cp314t-win_amd64.whl", hash = "sha256:3792983e23b69843aea49c8f5b8f115572c5ab64c153bada5270086a2123c7e7"},
{file = "psutil-7.1.3-cp314-cp314t-win_arm64.whl", hash = "sha256:31d77fcedb7529f27bb3a0472bea9334349f9a04160e8e6e5020f22c59893264"},
{file = "psutil-7.1.3-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:2bdbcd0e58ca14996a42adf3621a6244f1bb2e2e528886959c72cf1e326677ab"},
{file = "psutil-7.1.3-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:bc31fa00f1fbc3c3802141eede66f3a2d51d89716a194bf2cd6fc68310a19880"},
{file = "psutil-7.1.3-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3bb428f9f05c1225a558f53e30ccbad9930b11c3fc206836242de1091d3e7dd3"},
{file = "psutil-7.1.3-cp36-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:56d974e02ca2c8eb4812c3f76c30e28836fffc311d55d979f1465c1feeb2b68b"},
{file = "psutil-7.1.3-cp37-abi3-win_amd64.whl", hash = "sha256:f39c2c19fe824b47484b96f9692932248a54c43799a84282cfe58d05a6449efd"},
{file = "psutil-7.1.3-cp37-abi3-win_arm64.whl", hash = "sha256:bd0d69cee829226a761e92f28140bec9a5ee9d5b4fb4b0cc589068dbfff559b1"},
{file = "psutil-7.1.3.tar.gz", hash = "sha256:6c86281738d77335af7aec228328e944b30930899ea760ecf33a4dba66be5e74"},
{file = "psutil-7.2.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:c31e927555539132a00380c971816ea43d089bf4bd5f3e918ed8c16776d68474"},
{file = "psutil-7.2.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:db8e44e766cef86dea47d9a1fa535d38dc76449e5878a92f33683b7dba5bfcb2"},
{file = "psutil-7.2.0-cp313-cp313t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:85ef849ac92169dedc59a7ac2fb565f47b3468fbe1524bf748746bc21afb94c7"},
{file = "psutil-7.2.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:26782bdbae2f5c14ce9ebe8ad2411dc2ca870495e0cd90f8910ede7fa5e27117"},
{file = "psutil-7.2.0-cp313-cp313t-win_amd64.whl", hash = "sha256:b7665f612d3b38a583391b95969667a53aaf6c5706dc27a602c9a4874fbf09e4"},
{file = "psutil-7.2.0-cp313-cp313t-win_arm64.whl", hash = "sha256:4413373c174520ae28a24a8974ad8ce6b21f060d27dde94e25f8c73a7effe57a"},
{file = "psutil-7.2.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:2f2f53fd114e7946dfba3afb98c9b7c7f376009447360ca15bfb73f2066f84c7"},
{file = "psutil-7.2.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:e65c41d7e60068f60ce43b31a3a7fc90deb0dfd34ffc824a2574c2e5279b377e"},
{file = "psutil-7.2.0-cp314-cp314t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cc66d21366850a4261412ce994ae9976bba9852dafb4f2fa60db68ed17ff5281"},
{file = "psutil-7.2.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e025d67b42b8f22b096d5d20f5171de0e0fefb2f0ce983a13c5a1b5ed9872706"},
{file = "psutil-7.2.0-cp314-cp314t-win_amd64.whl", hash = "sha256:45f6b91f7ad63414d6454fd609e5e3556d0e1038d5d9c75a1368513bdf763f57"},
{file = "psutil-7.2.0-cp314-cp314t-win_arm64.whl", hash = "sha256:87b18a19574139d60a546e88b5f5b9cbad598e26cdc790d204ab95d7024f03ee"},
{file = "psutil-7.2.0-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:977a2fcd132d15cb05b32b2d85b98d087cad039b0ce435731670ba74da9e6133"},
{file = "psutil-7.2.0-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:24151011c21fadd94214d7139d7c6c54569290d7e553989bdf0eab73b13beb8c"},
{file = "psutil-7.2.0-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:91f211ba9279e7c61d9d8f84b713cfc38fa161cb0597d5cb3f1ca742f6848254"},
{file = "psutil-7.2.0-cp36-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f37415188b7ea98faf90fed51131181646c59098b077550246e2e092e127418b"},
{file = "psutil-7.2.0-cp36-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:0d12c7ce6ed1128cd81fd54606afa054ac7dbb9773469ebb58cf2f171c49f2ac"},
{file = "psutil-7.2.0-cp36-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:ca0faef7976530940dcd39bc5382d0d0d5eb023b186a4901ca341bd8d8684151"},
{file = "psutil-7.2.0-cp37-abi3-win_amd64.whl", hash = "sha256:abdb74137ca232d20250e9ad471f58d500e7743bc8253ba0bfbf26e570c0e437"},
{file = "psutil-7.2.0-cp37-abi3-win_arm64.whl", hash = "sha256:284e71038b3139e7ab3834b63b3eb5aa5565fcd61a681ec746ef9a0a8c457fd2"},
{file = "psutil-7.2.0.tar.gz", hash = "sha256:2e4f8e1552f77d14dc96fb0f6240c5b34a37081c0889f0853b3b29a496e5ef64"},
]
[package.extras]
dev = ["abi3audit", "black", "check-manifest", "colorama ; os_name == \"nt\"", "coverage", "packaging", "pylint", "pyperf", "pypinfo", "pyreadline ; os_name == \"nt\"", "pytest", "pytest-cov", "pytest-instafail", "pytest-subtests", "pytest-xdist", "pywin32 ; os_name == \"nt\" and platform_python_implementation != \"PyPy\"", "requests", "rstcheck", "ruff", "setuptools", "sphinx", "sphinx_rtd_theme", "toml-sort", "twine", "validate-pyproject[all]", "virtualenv", "vulture", "wheel", "wheel ; os_name == \"nt\" and platform_python_implementation != \"PyPy\"", "wmi ; os_name == \"nt\" and platform_python_implementation != \"PyPy\""]
test = ["pytest", "pytest-instafail", "pytest-subtests", "pytest-xdist", "pywin32 ; os_name == \"nt\" and platform_python_implementation != \"PyPy\"", "setuptools", "wheel ; os_name == \"nt\" and platform_python_implementation != \"PyPy\"", "wmi ; os_name == \"nt\" and platform_python_implementation != \"PyPy\""]
dev = ["abi3audit", "black", "check-manifest", "coverage", "packaging", "psleak", "pylint", "pyperf", "pypinfo", "pytest", "pytest-cov", "pytest-instafail", "pytest-xdist", "requests", "rstcheck", "ruff", "setuptools", "sphinx", "sphinx_rtd_theme", "toml-sort", "twine", "validate-pyproject[all]", "virtualenv", "vulture", "wheel"]
test = ["psleak", "pytest", "pytest-instafail", "pytest-xdist", "setuptools"]
[[package]]
name = "pyasn1"
@@ -6249,14 +6269,14 @@ hook-testing = ["execnet (>=1.5.0)", "psutil", "pytest (>=2.7.3)"]
[[package]]
name = "pyinstaller-hooks-contrib"
version = "2025.10"
version = "2025.11"
description = "Community maintained hooks for PyInstaller"
optional = false
python-versions = ">=3.8"
groups = ["main"]
files = [
{file = "pyinstaller_hooks_contrib-2025.10-py3-none-any.whl", hash = "sha256:aa7a378518772846221f63a84d6306d9827299323243db890851474dfd1231a9"},
{file = "pyinstaller_hooks_contrib-2025.10.tar.gz", hash = "sha256:a1a737e5c0dccf1cf6f19a25e2efd109b9fec9ddd625f97f553dac16ee884881"},
{file = "pyinstaller_hooks_contrib-2025.11-py3-none-any.whl", hash = "sha256:777e163e2942474aa41a8e6d31ac1635292d63422c3646c176d584d04d971c34"},
{file = "pyinstaller_hooks_contrib-2025.11.tar.gz", hash = "sha256:dfe18632e06655fa88d218e0d768fd753e1886465c12a6d4bce04f1aaeec917d"},
]
[package.dependencies]
@@ -8576,14 +8596,14 @@ files = [
[[package]]
name = "typer-slim"
version = "0.20.1"
version = "0.21.0"
description = "Typer, build great CLIs. Easy to code. Based on Python type hints."
optional = false
python-versions = ">=3.8"
python-versions = ">=3.9"
groups = ["main"]
files = [
{file = "typer_slim-0.20.1-py3-none-any.whl", hash = "sha256:8e89c5dbaffe87a4f86f4c7a9e2f7059b5b68c66f558f298969d42ce34f10122"},
{file = "typer_slim-0.20.1.tar.gz", hash = "sha256:bb9e4f7e6dc31551c8a201383df322b81b0ce37239a5ead302598a2ebb6f7c9c"},
{file = "typer_slim-0.21.0-py3-none-any.whl", hash = "sha256:92aee2188ac6fc2b2924bd75bb61a340b78bd8cd51fd9735533ce5a856812c8e"},
{file = "typer_slim-0.21.0.tar.gz", hash = "sha256:f2dbd150cfa0fead2242e21fa9f654dfc64773763ddf07c6be9a49ad34f79557"},
]
[package.dependencies]
@@ -9569,4 +9589,4 @@ cffi = ["cffi (>=1.17,<2.0) ; platform_python_implementation != \"PyPy\" and pyt
[metadata]
lock-version = "2.1"
python-versions = ">=3.10,<3.14"
content-hash = "1e643f63a31d7a34f6c583c4043bc53bd689f68ce93f5cda0c54e49a348222ff"
content-hash = "8639a26faea41348894a9f6491a95fa1a4a222e206f9d0afafd299ffc41cf5e1"
+3 -2
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.75.33"
version = "0.75.49"
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"
@@ -26,7 +26,7 @@ python = ">=3.10,<3.14"
torch = ">=2.7"
requests = ">=2"
beautifulsoup4 = ">=4"
flacfetch = ">=0.8"
flacfetch = ">=0.9.0"
lyricsgenius = ">=3"
fetch-lyrics-from-genius = ">=0.1"
pillow = ">=10.1"
@@ -41,6 +41,7 @@ audio-separator = { version = ">=0.34.0", extras = ["cpu"] }
lyrics-converter = ">=0.2.1"
# lyrics-transcriber is vendored in lyrics_transcriber_temp/ and included via packages
# Dependencies from vendored lyrics_transcriber:
mutagen = ">=1.47" # For LRCLIB provider to get track duration for better matching
python-slugify = ">=8"
syrics = ">=0"
karaoke-lyrics-processor = ">=0.6"
+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()
+403 -2
View File
@@ -197,9 +197,10 @@ class TestRemoteKaraokeClient:
token = client._get_auth_token_from_gcloud()
assert token is None
@patch.dict(os.environ, {}, clear=True)
@patch('subprocess.run')
def test_refresh_auth_success(self, mock_run, client):
"""Test refreshing auth token."""
def test_refresh_auth_success_gcloud(self, mock_run, client):
"""Test refreshing auth token via gcloud when no env token is set."""
mock_run.return_value = MagicMock(
stdout="new-token\n",
returncode=0
@@ -209,6 +210,16 @@ class TestRemoteKaraokeClient:
assert client.config.auth_token == "new-token"
assert client.session.headers['Authorization'] == 'Bearer new-token'
@patch.dict(os.environ, {'KARAOKE_GEN_AUTH_TOKEN': 'static-admin-token'})
def test_refresh_auth_keeps_env_token(self, client):
"""Test that refresh_auth keeps static env token instead of calling gcloud."""
original_token = client.config.auth_token
result = client.refresh_auth()
assert result is True
# Token should NOT be changed when env var is set
assert client.config.auth_token == original_token
@patch.dict(os.environ, {}, clear=True)
@patch('subprocess.run')
def test_refresh_auth_failure(self, mock_run, client):
"""Test handling auth refresh failure."""
@@ -2236,3 +2247,393 @@ class TestJobMonitorDownloadProgress:
# Should use 'unknown' as default
assert "unknown" in caplog.text.lower() or "Downloading" in caplog.text
class TestCategorizedAudioDisplay:
"""Tests for categorized audio search display (flacfetch PR #4)."""
@pytest.fixture
def monitor(self):
"""Create a JobMonitor instance for testing."""
config = Config(
service_url="http://localhost:8000",
review_ui_url="http://localhost:3000",
poll_interval=5,
output_dir="/tmp/output",
non_interactive=False,
)
client = MagicMock()
logger = logging.getLogger("test")
return JobMonitor(client=client, config=config, logger=logger)
def test_convert_to_release_objects_empty_list(self, monitor):
"""Test conversion with empty list."""
result = monitor._convert_to_release_objects([])
assert result == []
def test_convert_to_release_objects_valid_dicts(self, monitor):
"""Test conversion with valid Release-compatible dicts."""
release_dicts = [
{
"title": "Test Song",
"artist": "Test Artist",
"source_name": "RED",
"quality": {"format": "FLAC", "media": "CD"},
},
{
"title": "Another Song",
"artist": "Another Artist",
"source_name": "YouTube",
"quality": {"format": "AAC", "media": "WEB"},
},
]
result = monitor._convert_to_release_objects(release_dicts)
# Should successfully convert both
assert len(result) == 2
assert result[0].title == "Test Song"
assert result[1].title == "Another Song"
def test_convert_to_release_objects_handles_invalid(self, monitor):
"""Test conversion skips invalid dicts gracefully."""
release_dicts = [
{
"title": "Valid Song",
"artist": "Valid Artist",
"source_name": "RED",
"quality": {"format": "FLAC", "media": "CD"},
},
# This dict is missing required fields - may cause error
{},
]
result = monitor._convert_to_release_objects(release_dicts)
# Should have at least one result (the valid one)
# Invalid ones should be skipped without raising
assert len(result) >= 1
def test_find_original_index_by_identity(self, monitor):
"""Test finding index by object identity."""
from flacfetch import Release
releases = [
Release.from_dict({
"title": "Song 1", "artist": "Artist", "source_name": "RED",
"quality": {"format": "FLAC", "media": "CD"}
}),
Release.from_dict({
"title": "Song 2", "artist": "Artist", "source_name": "OPS",
"quality": {"format": "FLAC", "media": "CD"}
}),
]
original_results = [
{"title": "Song 1", "artist": "Artist", "provider": "RED"},
{"title": "Song 2", "artist": "Artist", "provider": "OPS"},
]
# Find by object identity
result = monitor._find_original_index(releases[1], original_results, releases)
assert result == 1
def test_find_original_index_by_url(self, monitor):
"""Test finding index by download_url match."""
from flacfetch import Release
release = Release.from_dict({
"title": "Song", "artist": "Artist", "source_name": "RED",
"quality": {"format": "FLAC", "media": "CD"},
"download_url": "https://example.com/download/123"
})
original_results = [
{"title": "Wrong", "artist": "Artist", "provider": "RED", "url": "https://other.com"},
{"title": "Song", "artist": "Artist", "provider": "RED", "url": "https://example.com/download/123"},
]
result = monitor._find_original_index(release, original_results, [])
assert result == 1
def test_find_original_index_by_hash(self, monitor):
"""Test finding index by info_hash match."""
from flacfetch import Release
release = Release.from_dict({
"title": "Song", "artist": "Artist", "source_name": "RED",
"quality": {"format": "FLAC", "media": "CD"},
"info_hash": "abc123hash"
})
original_results = [
{"title": "Wrong", "artist": "Artist", "provider": "RED", "source_id": "other"},
{"title": "Song", "artist": "Artist", "provider": "RED", "source_id": "abc123hash"},
]
result = monitor._find_original_index(release, original_results, [])
assert result == 1
def test_find_original_index_by_metadata(self, monitor):
"""Test finding index by title+artist+provider match."""
from flacfetch import Release
release = Release.from_dict({
"title": "Unique Title", "artist": "Unique Artist", "source_name": "OPS",
"quality": {"format": "FLAC", "media": "CD"}
})
original_results = [
{"title": "Other", "artist": "Other", "provider": "RED"},
{"title": "Unique Title", "artist": "Unique Artist", "provider": "OPS"},
]
result = monitor._find_original_index(release, original_results, [])
assert result == 1
def test_find_original_index_not_found(self, monitor):
"""Test returns -1 when no match found."""
from flacfetch import Release
release = Release.from_dict({
"title": "No Match", "artist": "No Artist", "source_name": "Unknown",
"quality": {"format": "MP3", "media": "WEB"}
})
original_results = [
{"title": "Other", "artist": "Other", "provider": "RED"},
]
result = monitor._find_original_index(release, original_results, [])
assert result == -1
def test_convert_api_result_to_release_dict(self, monitor):
"""Test API result conversion to Release-compatible dict."""
api_result = {
"title": "Test Song",
"artist": "Test Artist",
"provider": "RED",
"url": "https://download.url",
"source_id": "hash123",
"seeders": 50,
"quality": "FLAC 16bit CD",
"quality_data": {"format": "FLAC", "bit_depth": 16, "media": "CD"},
"is_lossless": True,
"year": 2020,
}
result = monitor._convert_api_result_to_release_dict(api_result)
assert result["title"] == "Test Song"
assert result["artist"] == "Test Artist"
assert result["source_name"] == "RED"
assert result["download_url"] == "https://download.url"
assert result["seeders"] == 50
assert result["is_lossless"] == True
class TestSearchAudioWithStyleFiles:
"""Tests for search_audio method with style file upload support."""
@pytest.fixture
def config(self):
"""Create test config."""
return Config(
service_url="http://localhost:8000",
review_ui_url="http://localhost:3000",
poll_interval=5,
output_dir="/tmp/output",
non_interactive=False,
auth_token="test-token"
)
@pytest.fixture
def logger(self):
"""Create test logger."""
return logging.getLogger("test-search-audio")
@pytest.fixture
def client(self, config, logger):
"""Create a RemoteKaraokeClient instance for testing."""
return RemoteKaraokeClient(config, logger)
@patch('requests.Session.request')
def test_search_audio_without_style_files(self, mock_request, client):
"""Test search_audio without style files."""
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json.return_value = {
"status": "awaiting_selection",
"job_id": "test-job-123",
"message": "Found 5 audio sources",
"results_count": 5,
"server_version": "0.75.47",
}
mock_request.return_value = mock_response
result = client.search_audio("Test Artist", "Test Title")
assert result["job_id"] == "test-job-123"
assert result["results_count"] == 5
# Verify request was made without style_files
call_args = mock_request.call_args
request_json = call_args.kwargs.get('json', {})
assert "style_files" not in request_json
@patch('requests.put')
@patch('requests.Session.request')
@patch('os.path.isfile')
def test_search_audio_with_style_params(self, mock_isfile, mock_request, mock_put, client):
"""Test search_audio with style_params.json file."""
# Mock file checks
mock_isfile.return_value = True
# Mock API response with style upload URLs
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json.return_value = {
"status": "awaiting_selection",
"job_id": "test-job-123",
"message": "Found 5 audio sources",
"results_count": 5,
"server_version": "0.75.47",
"style_upload_urls": [
{
"file_type": "style_params",
"gcs_path": "uploads/test-job-123/style/style_params.json",
"upload_url": "https://storage.googleapis.com/signed-url-1"
}
]
}
mock_request.return_value = mock_response
# Mock successful upload
mock_put_response = MagicMock()
mock_put_response.status_code = 200
mock_put.return_value = mock_put_response
# Create temp style params file
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
json.dump({"intro": {}, "karaoke": {}, "end": {}}, f)
style_file = f.name
try:
# Mock open for reading the style file for upload
with patch('builtins.open', mock_open(read_data=b'{"test": "data"}')):
result = client.search_audio(
"Test Artist",
"Test Title",
style_params_path=style_file
)
assert result["job_id"] == "test-job-123"
# Verify style_files was included in request
call_args = mock_request.call_args
request_json = call_args.kwargs.get('json', {})
assert "style_files" in request_json
assert len(request_json["style_files"]) >= 1
assert request_json["style_files"][0]["file_type"] == "style_params"
# Verify upload was attempted
mock_put.assert_called_once()
finally:
os.unlink(style_file)
@patch('requests.Session.request')
def test_search_audio_no_results(self, mock_request, client):
"""Test search_audio when no results are found."""
mock_response = MagicMock()
mock_response.status_code = 404
mock_response.json.return_value = {"error": "no_results", "message": "No audio found"}
mock_response.text = "Not found"
mock_request.return_value = mock_response
with pytest.raises(ValueError, match="No audio sources found"):
client.search_audio("Unknown Artist", "Unknown Title")
@patch('requests.Session.request')
def test_search_audio_server_error(self, mock_request, client):
"""Test search_audio when server returns error."""
mock_response = MagicMock()
mock_response.status_code = 500
mock_response.json.return_value = {"error": "Internal error"}
mock_response.text = "Internal Server Error"
mock_request.return_value = mock_response
with pytest.raises(RuntimeError, match="Error searching for audio"):
client.search_audio("Test Artist", "Test Title")
@patch('requests.put')
@patch('requests.Session.request')
@patch('os.path.isfile')
def test_search_audio_upload_failure_continues(self, mock_isfile, mock_request, mock_put, client):
"""Test that search_audio continues even if style upload fails."""
mock_isfile.return_value = True
# Mock API response with style upload URLs
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json.return_value = {
"status": "awaiting_selection",
"job_id": "test-job-123",
"results_count": 5,
"server_version": "0.75.47",
"style_upload_urls": [
{
"file_type": "style_params",
"gcs_path": "uploads/test-job-123/style/style_params.json",
"upload_url": "https://storage.googleapis.com/signed-url-1"
}
]
}
mock_request.return_value = mock_response
# Mock failed upload (403)
mock_put_response = MagicMock()
mock_put_response.status_code = 403
mock_put.return_value = mock_put_response
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
json.dump({}, f)
style_file = f.name
try:
with patch('builtins.open', mock_open(read_data=b'{}')):
# Should not raise, even if upload fails
result = client.search_audio(
"Test Artist",
"Test Title",
style_params_path=style_file
)
assert result["job_id"] == "test-job-123"
finally:
os.unlink(style_file)
@patch('requests.Session.request')
@patch('os.path.isfile')
def test_search_audio_style_file_not_found(self, mock_isfile, mock_request, client):
"""Test search_audio when style_params file doesn't exist."""
# First call (for style_params_path check) returns False
mock_isfile.return_value = False
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json.return_value = {
"status": "awaiting_selection",
"job_id": "test-job-123",
"results_count": 5,
"server_version": "0.75.47",
}
mock_request.return_value = mock_response
# Should succeed but without style files
result = client.search_audio(
"Test Artist",
"Test Title",
style_params_path="/nonexistent/style.json"
)
assert result["job_id"] == "test-job-123"
# Verify no style_files in request
call_args = mock_request.call_args
request_json = call_args.kwargs.get('json', {})
assert "style_files" not in request_json