mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-30 09:14:03 +09:00
Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
68eec8b8b9 | ||
|
|
5aa0920fae | ||
|
|
6d81ad804a | ||
|
|
81dca5c673 | ||
|
|
5c29fabd0f | ||
|
|
6951de03b3 | ||
|
|
f1d3423e9d | ||
|
|
82475a8b03 | ||
|
|
8c2be7bfe2 | ||
|
|
b7e157ec15 | ||
|
|
722ec69cda | ||
|
|
67b0601811 | ||
|
|
97a0c642f1 | ||
|
|
71dadc71a2 | ||
|
|
e81ecbbbba | ||
|
|
6897d20358 | ||
|
|
af09ee4b50 | ||
|
|
634bb3a11c | ||
|
|
79cc552226 | ||
|
|
f579f0ce71 | ||
|
|
682f5ef432 | ||
|
|
8015e2a228 | ||
|
|
55b9691fb9 | ||
|
|
6e089850a7 | ||
|
|
5f52cffc34 | ||
|
|
71ebd43771 |
No files matched your search
@@ -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.
|
||||
@@ -220,3 +220,4 @@ cython_debug/
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
flacfetch
|
||||
@@ -58,6 +58,40 @@ This installs both `karaoke-gen` (local) and `karaoke-gen-remote` (cloud) CLIs.
|
||||
- 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
|
||||
|
||||
@@ -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):
|
||||
@@ -395,6 +428,7 @@ async def search_audio(
|
||||
brand_prefix=body.brand_prefix,
|
||||
enable_youtube_upload=body.enable_youtube_upload,
|
||||
youtube_description=body.youtube_description,
|
||||
youtube_description_template=body.youtube_description, # video_worker reads this field
|
||||
discord_webhook_url=effective_discord_webhook_url,
|
||||
dropbox_path=effective_dropbox_path,
|
||||
gdrive_folder_id=effective_gdrive_folder_id,
|
||||
@@ -421,6 +455,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 +572,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 +587,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 +632,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 +645,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:
|
||||
|
||||
@@ -0,0 +1,477 @@
|
||||
"""
|
||||
End-to-End CLI + Backend Integration Tests
|
||||
|
||||
These tests verify the FULL flow from CLI to Backend with real emulators.
|
||||
They would have caught bugs like:
|
||||
- Content-type mismatch in signed URL uploads (403 errors)
|
||||
- Missing auth headers in download requests
|
||||
- YouTube description field name mismatch
|
||||
|
||||
Run with: ./scripts/run-emulator-tests.sh
|
||||
|
||||
Prerequisites:
|
||||
- GCS emulator running (fake-gcs-server)
|
||||
- Firestore emulator running
|
||||
"""
|
||||
import pytest
|
||||
import json
|
||||
import time
|
||||
import tempfile
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch, MagicMock, AsyncMock
|
||||
|
||||
from .conftest import emulators_running
|
||||
|
||||
|
||||
# Skip all tests if emulators aren't running
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not emulators_running(),
|
||||
reason="GCP emulators not running. Start with: scripts/start-emulators.sh"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_style_files(tmp_path):
|
||||
"""Create realistic test style files for upload testing."""
|
||||
# Create a style params JSON that references local files
|
||||
style_params = {
|
||||
"intro": {
|
||||
"background_color": "#000000",
|
||||
"background_image": str(tmp_path / "intro_bg.png"),
|
||||
"font": str(tmp_path / "test_font.ttf"),
|
||||
"title_color": "#ffffff",
|
||||
"artist_color": "#ffdf6b"
|
||||
},
|
||||
"karaoke": {
|
||||
"background_color": "#000000",
|
||||
"background_image": str(tmp_path / "karaoke_bg.png"),
|
||||
"font_path": str(tmp_path / "test_font.ttf"),
|
||||
"primary_color": "112, 112, 247, 255",
|
||||
"secondary_color": "255, 255, 255, 255"
|
||||
},
|
||||
"end": {
|
||||
"background_color": "#000000",
|
||||
"background_image": str(tmp_path / "end_bg.png"),
|
||||
"font": str(tmp_path / "test_font.ttf")
|
||||
},
|
||||
"cdg": {
|
||||
"background_color": "#000000",
|
||||
"instrumental_background": str(tmp_path / "cdg_inst_bg.png"),
|
||||
"title_screen_background": str(tmp_path / "cdg_title_bg.png"),
|
||||
"outro_background": str(tmp_path / "cdg_outro_bg.png"),
|
||||
"font_path": str(tmp_path / "test_font.ttf")
|
||||
}
|
||||
}
|
||||
|
||||
style_params_path = tmp_path / "karaoke-prep-styles.json"
|
||||
with open(style_params_path, 'w') as f:
|
||||
json.dump(style_params, f)
|
||||
|
||||
# Create minimal valid PNG (1x1 pixel)
|
||||
minimal_png = bytes([
|
||||
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, # PNG signature
|
||||
0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, # IHDR chunk
|
||||
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, # 1x1
|
||||
0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53,
|
||||
0xDE, 0x00, 0x00, 0x00, 0x0C, 0x49, 0x44, 0x41, # IDAT chunk
|
||||
0x54, 0x08, 0xD7, 0x63, 0xF8, 0xFF, 0xFF, 0x3F,
|
||||
0x00, 0x05, 0xFE, 0x02, 0xFE, 0xDC, 0xCC, 0x59,
|
||||
0xE7, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, # IEND chunk
|
||||
0x44, 0xAE, 0x42, 0x60, 0x82
|
||||
])
|
||||
|
||||
# Create all referenced image files
|
||||
for name in ["intro_bg.png", "karaoke_bg.png", "end_bg.png",
|
||||
"cdg_inst_bg.png", "cdg_title_bg.png", "cdg_outro_bg.png"]:
|
||||
(tmp_path / name).write_bytes(minimal_png)
|
||||
|
||||
# Create minimal TTF font file
|
||||
minimal_ttf = bytes([0x00, 0x01, 0x00, 0x00] + [0x00] * 100)
|
||||
(tmp_path / "test_font.ttf").write_bytes(minimal_ttf)
|
||||
|
||||
return {
|
||||
'style_params_path': str(style_params_path),
|
||||
'tmp_path': tmp_path
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def youtube_description():
|
||||
"""Sample YouTube description template."""
|
||||
return """This is a karaoke (instrumental) version of the song.
|
||||
|
||||
Created using AI-powered vocal removal.
|
||||
|
||||
LINKS:
|
||||
- Community: https://discord.gg/example
|
||||
- More karaoke: https://example.com
|
||||
"""
|
||||
|
||||
|
||||
class TestStyleFileUploadE2E:
|
||||
"""
|
||||
Test the complete style file upload flow.
|
||||
|
||||
This is the flow that broke with the content-type mismatch bug:
|
||||
1. CLI parses style_params.json and finds all referenced files
|
||||
2. CLI sends metadata to backend, gets signed upload URLs
|
||||
3. CLI uploads each file to its signed URL with correct content-type
|
||||
4. Backend records the GCS paths for later use
|
||||
"""
|
||||
|
||||
def test_style_params_json_upload_content_type(self, client, auth_headers, tmp_path):
|
||||
"""
|
||||
Test that style_params.json uploads with application/json content-type.
|
||||
|
||||
BUG CAUGHT: CLI was deriving content-type from Path('.json').suffix which
|
||||
returns '' because '.json' looks like a hidden file. This caused 403 errors
|
||||
because the upload content-type didn't match the signed URL's expected type.
|
||||
"""
|
||||
# Create minimal style params
|
||||
style_params = {"karaoke": {"background_color": "#000000"}}
|
||||
style_path = tmp_path / "styles.json"
|
||||
with open(style_path, 'w') as f:
|
||||
json.dump(style_params, f)
|
||||
|
||||
# Create job with style files
|
||||
response = client.post(
|
||||
"/api/audio-search/search",
|
||||
headers=auth_headers,
|
||||
json={
|
||||
'artist': 'Test Artist',
|
||||
'title': 'Test Song',
|
||||
'auto_download': False,
|
||||
'files': [
|
||||
{
|
||||
'filename': 'styles.json',
|
||||
'content_type': 'application/json',
|
||||
'file_type': 'style_params'
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
# Should not fail with 500 (backend error)
|
||||
assert response.status_code in [200, 404], f"Unexpected: {response.status_code} - {response.text}"
|
||||
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
# Verify upload URLs are returned
|
||||
if 'upload_urls' in data:
|
||||
assert 'style_params' in data['upload_urls']
|
||||
# The URL should be a signed GCS URL
|
||||
url = data['upload_urls']['style_params']
|
||||
assert 'storage' in url.lower() or 'localhost' in url.lower()
|
||||
|
||||
def test_image_upload_content_type(self, client, auth_headers, tmp_path):
|
||||
"""Test that PNG images upload with image/png content-type."""
|
||||
response = client.post(
|
||||
"/api/audio-search/search",
|
||||
headers=auth_headers,
|
||||
json={
|
||||
'artist': 'Test Artist',
|
||||
'title': 'Test Song',
|
||||
'auto_download': False,
|
||||
'files': [
|
||||
{
|
||||
'filename': 'background.png',
|
||||
'content_type': 'image/png',
|
||||
'file_type': 'style_intro_background'
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
assert response.status_code in [200, 404]
|
||||
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
if 'upload_urls' in data:
|
||||
assert 'style_intro_background' in data['upload_urls']
|
||||
|
||||
def test_font_upload_content_type(self, client, auth_headers):
|
||||
"""Test that TTF fonts upload with font/ttf content-type."""
|
||||
response = client.post(
|
||||
"/api/audio-search/search",
|
||||
headers=auth_headers,
|
||||
json={
|
||||
'artist': 'Test Artist',
|
||||
'title': 'Test Song',
|
||||
'auto_download': False,
|
||||
'files': [
|
||||
{
|
||||
'filename': 'font.ttf',
|
||||
'content_type': 'font/ttf',
|
||||
'file_type': 'style_font'
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
assert response.status_code in [200, 404]
|
||||
|
||||
|
||||
class TestYouTubeDescriptionFieldMapping:
|
||||
"""
|
||||
Test that YouTube description is properly passed from API to workers.
|
||||
|
||||
BUG CAUGHT: audio_search endpoint set 'youtube_description' but
|
||||
video_worker.py reads 'youtube_description_template'. YouTube uploads
|
||||
silently failed because the template field was always None.
|
||||
"""
|
||||
|
||||
def test_job_has_youtube_description_template(self, client, auth_headers, youtube_description):
|
||||
"""
|
||||
Test that when youtube_description is provided, youtube_description_template is also set.
|
||||
|
||||
This is critical because video_worker.py uses this pattern:
|
||||
if youtube_credentials and getattr(job, 'youtube_description_template', None):
|
||||
"""
|
||||
response = client.post(
|
||||
"/api/audio-search/search",
|
||||
headers=auth_headers,
|
||||
json={
|
||||
'artist': 'Test Artist',
|
||||
'title': 'Test Song',
|
||||
'auto_download': False,
|
||||
'enable_youtube_upload': True,
|
||||
'youtube_description': youtube_description
|
||||
}
|
||||
)
|
||||
|
||||
# Job should be created (or 404 if flacfetch not configured)
|
||||
assert response.status_code in [200, 404], f"Unexpected: {response.status_code}"
|
||||
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
job_id = data.get('job_id')
|
||||
|
||||
if job_id:
|
||||
# Fetch the job and verify both fields are set
|
||||
time.sleep(0.2) # Allow for emulator consistency
|
||||
job_response = client.get(f"/api/jobs/{job_id}", headers=auth_headers)
|
||||
|
||||
if job_response.status_code == 200:
|
||||
job = job_response.json()
|
||||
|
||||
# CRITICAL: Both fields must be set for YouTube upload to work
|
||||
assert job.get('youtube_description') == youtube_description, \
|
||||
"youtube_description not set correctly"
|
||||
assert job.get('youtube_description_template') == youtube_description, \
|
||||
"youtube_description_template not set - YouTube upload will fail!"
|
||||
|
||||
def test_youtube_upload_disabled_no_template_needed(self, client, auth_headers):
|
||||
"""Test that youtube_description_template is not required when upload is disabled."""
|
||||
response = client.post(
|
||||
"/api/audio-search/search",
|
||||
headers=auth_headers,
|
||||
json={
|
||||
'artist': 'Test Artist',
|
||||
'title': 'Test Song',
|
||||
'auto_download': False,
|
||||
'enable_youtube_upload': False
|
||||
}
|
||||
)
|
||||
|
||||
# Should succeed without YouTube config
|
||||
assert response.status_code in [200, 404]
|
||||
|
||||
|
||||
class TestDownloadAuthHeaders:
|
||||
"""
|
||||
Test that file downloads include authentication headers.
|
||||
|
||||
BUG CAUGHT: download_file_via_url() used requests.get() directly instead
|
||||
of self.session.get(), so auth headers were not included. All downloads
|
||||
failed with 401/403 even though the job completed successfully.
|
||||
"""
|
||||
|
||||
def test_download_endpoint_requires_auth(self, client):
|
||||
"""Test that download endpoints reject unauthenticated requests."""
|
||||
# Try to download without auth header
|
||||
response = client.get("/api/jobs/nonexistent/download-urls")
|
||||
|
||||
# Should fail with 401 (unauthorized), not 404
|
||||
assert response.status_code in [401, 403], \
|
||||
f"Download endpoint should require auth, got {response.status_code}"
|
||||
|
||||
def test_download_endpoint_with_auth(self, client, auth_headers):
|
||||
"""Test that download endpoints work with auth header."""
|
||||
# First create a job
|
||||
create_response = client.post(
|
||||
"/api/jobs",
|
||||
headers=auth_headers,
|
||||
json={"url": "https://youtube.com/watch?v=test123"}
|
||||
)
|
||||
|
||||
if create_response.status_code == 200:
|
||||
job_id = create_response.json()["job_id"]
|
||||
time.sleep(0.2)
|
||||
|
||||
# Try to get download URLs with auth
|
||||
download_response = client.get(
|
||||
f"/api/jobs/{job_id}/download-urls",
|
||||
headers=auth_headers
|
||||
)
|
||||
|
||||
# Should succeed (200) or return empty URLs for incomplete job
|
||||
assert download_response.status_code in [200, 404], \
|
||||
f"Download URLs request failed: {download_response.status_code}"
|
||||
|
||||
|
||||
class TestFullAudioSearchFlow:
|
||||
"""
|
||||
Test the complete audio search flow that the CLI uses.
|
||||
"""
|
||||
|
||||
def test_audio_search_creates_job_with_all_fields(
|
||||
self, client, auth_headers, test_style_files, youtube_description
|
||||
):
|
||||
"""Test that audio search creates a job with all expected fields."""
|
||||
response = client.post(
|
||||
"/api/audio-search/search",
|
||||
headers=auth_headers,
|
||||
json={
|
||||
'artist': 'ABBA',
|
||||
'title': 'Waterloo',
|
||||
'auto_download': False,
|
||||
'enable_cdg': True,
|
||||
'enable_txt': True,
|
||||
'enable_youtube_upload': True,
|
||||
'youtube_description': youtube_description,
|
||||
'brand_prefix': 'TEST',
|
||||
'files': [
|
||||
{
|
||||
'filename': 'styles.json',
|
||||
'content_type': 'application/json',
|
||||
'file_type': 'style_params'
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
# Should create job or return 404 if no results
|
||||
assert response.status_code in [200, 404], \
|
||||
f"Unexpected status: {response.status_code} - {response.text}"
|
||||
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
|
||||
# Verify job was created
|
||||
assert 'job_id' in data
|
||||
job_id = data['job_id']
|
||||
|
||||
# Verify upload URLs returned for style files
|
||||
if 'upload_urls' in data:
|
||||
assert isinstance(data['upload_urls'], dict)
|
||||
|
||||
# Fetch job and verify all fields are set
|
||||
time.sleep(0.2)
|
||||
job_response = client.get(f"/api/jobs/{job_id}", headers=auth_headers)
|
||||
|
||||
if job_response.status_code == 200:
|
||||
job = job_response.json()
|
||||
|
||||
# Verify job configuration
|
||||
assert job.get('enable_cdg') is True
|
||||
assert job.get('enable_txt') is True
|
||||
assert job.get('enable_youtube_upload') is True
|
||||
assert job.get('youtube_description') == youtube_description
|
||||
# CRITICAL: This field must be set for video_worker.py
|
||||
assert job.get('youtube_description_template') == youtube_description
|
||||
|
||||
def test_audio_search_returns_server_version(self, client, auth_headers):
|
||||
"""Test that audio search response includes server version."""
|
||||
response = client.post(
|
||||
"/api/audio-search/search",
|
||||
headers=auth_headers,
|
||||
json={
|
||||
'artist': 'Test',
|
||||
'title': 'Song',
|
||||
'auto_download': False
|
||||
}
|
||||
)
|
||||
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
# Server version helps CLI verify compatibility
|
||||
assert 'server_version' in data
|
||||
|
||||
|
||||
class TestCLIClientIntegration:
|
||||
"""
|
||||
Test the actual CLI client code against the backend.
|
||||
|
||||
These tests import and use the real RemoteKaraokeClient class.
|
||||
"""
|
||||
|
||||
@pytest.fixture
|
||||
def cli_client(self):
|
||||
"""Create a CLI client configured for local testing."""
|
||||
# Import here to avoid issues when emulators aren't running
|
||||
from karaoke_gen.utils.remote_cli import RemoteKaraokeClient, RemoteConfig
|
||||
|
||||
logger = logging.getLogger("test_cli")
|
||||
config = RemoteConfig(
|
||||
service_url='http://localhost:8000',
|
||||
auth_token='test-admin-token',
|
||||
environment='test'
|
||||
)
|
||||
return RemoteKaraokeClient(config, logger)
|
||||
|
||||
def test_cli_get_content_type_handles_all_extensions(self, cli_client):
|
||||
"""Test CLI content type detection for all file types we use."""
|
||||
# JSON
|
||||
assert cli_client._get_content_type('/path/to/style.json') == 'application/json'
|
||||
# Images
|
||||
assert cli_client._get_content_type('/path/to/bg.png') == 'image/png'
|
||||
assert cli_client._get_content_type('/path/to/bg.jpg') == 'image/jpeg'
|
||||
assert cli_client._get_content_type('/path/to/bg.jpeg') == 'image/jpeg'
|
||||
# Fonts
|
||||
assert cli_client._get_content_type('/path/to/font.ttf') == 'font/ttf'
|
||||
assert cli_client._get_content_type('/path/to/font.otf') == 'font/otf'
|
||||
# Audio
|
||||
assert cli_client._get_content_type('/path/to/audio.flac') == 'audio/flac'
|
||||
assert cli_client._get_content_type('/path/to/audio.mp3') == 'audio/mpeg'
|
||||
|
||||
def test_cli_download_uses_session_not_requests(self, cli_client, tmp_path):
|
||||
"""
|
||||
Test that CLI download method uses session (with auth headers).
|
||||
|
||||
This verifies the fix for the download auth bug.
|
||||
"""
|
||||
# Mock the session.get to verify it's called
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.iter_content.return_value = [b'test content']
|
||||
cli_client.session.get = MagicMock(return_value=mock_response)
|
||||
|
||||
local_path = str(tmp_path / "test.mp4")
|
||||
|
||||
# Call download with a relative URL
|
||||
result = cli_client.download_file_via_url("/api/jobs/123/download/test", local_path)
|
||||
|
||||
# Verify session.get was called (not bare requests.get)
|
||||
assert result is True
|
||||
cli_client.session.get.assert_called_once()
|
||||
|
||||
# Verify URL was constructed correctly
|
||||
call_args = cli_client.session.get.call_args
|
||||
assert 'localhost:8000' in call_args[0][0] or cli_client.config.service_url in call_args[0][0]
|
||||
|
||||
def test_cli_parse_style_params_extracts_all_assets(self, cli_client, test_style_files):
|
||||
"""Test that CLI correctly parses style params and finds all asset files."""
|
||||
assets = cli_client._parse_style_params(test_style_files['style_params_path'])
|
||||
|
||||
# Should find all the referenced files
|
||||
assert len(assets) > 0
|
||||
|
||||
# Verify it found background images
|
||||
bg_keys = [k for k in assets.keys() if 'background' in k.lower()]
|
||||
assert len(bg_keys) > 0, "Should find background image references"
|
||||
|
||||
# Verify it found font
|
||||
font_keys = [k for k in assets.keys() if 'font' in k.lower()]
|
||||
assert len(font_keys) > 0, "Should find font references"
|
||||
|
||||
@@ -69,6 +69,78 @@ class TestJobModelAudioSearchFields:
|
||||
assert job_create.auto_download is True
|
||||
|
||||
|
||||
class TestYouTubeFieldMapping:
|
||||
"""Test YouTube description field mapping between API and workers.
|
||||
|
||||
CRITICAL: This test class exists because we had a bug where:
|
||||
- The audio_search API endpoint set `youtube_description`
|
||||
- But video_worker.py reads `youtube_description_template`
|
||||
|
||||
These tests ensure both fields are properly set so YouTube uploads work.
|
||||
"""
|
||||
|
||||
def test_job_has_both_youtube_description_fields(self):
|
||||
"""Test Job model has both youtube_description and youtube_description_template."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
enable_youtube_upload=True,
|
||||
youtube_description="This is a karaoke video",
|
||||
youtube_description_template="This is a karaoke video",
|
||||
)
|
||||
|
||||
# Both fields should exist and be set
|
||||
assert job.youtube_description == "This is a karaoke video"
|
||||
assert job.youtube_description_template == "This is a karaoke video"
|
||||
assert job.enable_youtube_upload is True
|
||||
|
||||
def test_job_create_has_youtube_description_template(self):
|
||||
"""Test JobCreate model has youtube_description_template field."""
|
||||
job_create = JobCreate(
|
||||
artist="Test",
|
||||
title="Song",
|
||||
enable_youtube_upload=True,
|
||||
youtube_description="This is a karaoke video",
|
||||
youtube_description_template="This is a karaoke video",
|
||||
)
|
||||
|
||||
assert job_create.youtube_description_template == "This is a karaoke video"
|
||||
|
||||
def test_video_worker_reads_youtube_description_template(self):
|
||||
"""Document what field video_worker expects.
|
||||
|
||||
This is a documentation test - if video_worker changes what field
|
||||
it reads, this test should be updated to match.
|
||||
"""
|
||||
# video_worker.py uses this pattern:
|
||||
# if youtube_credentials and getattr(job, 'youtube_description_template', None):
|
||||
# youtube_desc_path = os.path.join(temp_dir, "youtube_description.txt")
|
||||
# with open(youtube_desc_path, 'w') as f:
|
||||
# f.write(job.youtube_description_template)
|
||||
#
|
||||
# So the job MUST have youtube_description_template set for YouTube upload to work
|
||||
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
enable_youtube_upload=True,
|
||||
youtube_description_template="Template text",
|
||||
)
|
||||
|
||||
# Simulate what video_worker does
|
||||
template = getattr(job, 'youtube_description_template', None)
|
||||
assert template is not None, "youtube_description_template must be set for YouTube upload"
|
||||
assert template == "Template text"
|
||||
|
||||
|
||||
class TestJobStatusAudioSearchStates:
|
||||
"""Test Job status includes audio search states."""
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
# CLI + Backend Integration Testing
|
||||
|
||||
## The Problem
|
||||
|
||||
We had multiple bugs that unit tests didn't catch:
|
||||
- Content-type mismatch in signed URL uploads (403 errors)
|
||||
- Missing auth headers in download requests (all downloads failed)
|
||||
- YouTube description field name mismatch (uploads silently failed)
|
||||
- Style file path handling issues
|
||||
|
||||
These bugs required:
|
||||
1. Full CI/CD deploy (~12 min)
|
||||
2. Full karaoke generation (~10 min)
|
||||
3. Manual inspection of logs
|
||||
|
||||
**Total: 20+ minutes per iteration** 😱
|
||||
|
||||
## The Solution
|
||||
|
||||
New **CLI + Backend Integration Tests** that:
|
||||
- Run the ACTUAL CLI code against a LOCAL backend
|
||||
- Use GCP emulators (Firestore + GCS)
|
||||
- Test the full signed URL upload flow
|
||||
- Run in **< 30 seconds**
|
||||
|
||||
## Test Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ Unit Tests (Mocked) │ ← Fast, isolated
|
||||
│ tests/unit/ │ ~0.5s, 100+ tests
|
||||
├─────────────────────────────────────┤
|
||||
│ Backend Emulator Tests │ ← Backend-only integration
|
||||
│ backend/tests/emulator/ │ ~10s, uses Firestore/GCS
|
||||
│ - test_emulator_integration.py │ Basic CRUD operations
|
||||
│ - test_e2e_cli_backend.py │ Full CLI → Backend flow
|
||||
├─────────────────────────────────────┤
|
||||
│ Cloud Integration Tests │ ← Against deployed backend
|
||||
│ backend/tests/test_api_integration│ ~10min, pre-prod only
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Run All Integration Tests
|
||||
|
||||
```bash
|
||||
./scripts/run-cli-integration-tests.sh
|
||||
```
|
||||
|
||||
This automatically:
|
||||
1. Starts GCP emulators
|
||||
2. Starts local backend
|
||||
3. Runs tests
|
||||
4. Cleans up
|
||||
|
||||
### Interactive Development Mode
|
||||
|
||||
```bash
|
||||
# Terminal 1: Start environment
|
||||
./scripts/start-local-test-env.sh
|
||||
|
||||
# Terminal 2: Run specific tests repeatedly
|
||||
pytest tests/integration/test_cli_backend_integration.py -v -k "test_style_params"
|
||||
```
|
||||
|
||||
## What These Tests Catch
|
||||
|
||||
### ✅ Content-Type Mismatches
|
||||
```python
|
||||
def test_style_params_json_upload(self, test_style_files, cli_config):
|
||||
"""Test uploading style_params.json via signed URL."""
|
||||
# This would have caught the Path('.json').suffix bug!
|
||||
result = client.search_audio(
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
style_params_path=test_style_files['style_params_path'],
|
||||
)
|
||||
# If we get 403, the test fails with a clear message
|
||||
```
|
||||
|
||||
### ✅ Request/Response Format Mismatches
|
||||
Tests verify CLI and backend agree on API contract.
|
||||
|
||||
### ✅ GCS Path Issues
|
||||
Uploads go to real (emulated) GCS, catches path/encoding bugs.
|
||||
|
||||
### ✅ Auth Token Handling
|
||||
Tests run with actual token flow.
|
||||
|
||||
### ✅ Download Auth Headers
|
||||
```python
|
||||
def test_download_uses_session_not_requests(self, cli_client, tmp_path):
|
||||
"""Verify downloads use session.get() not requests.get()."""
|
||||
# This catches the bug where downloads failed with 401/403
|
||||
# because auth headers weren't included
|
||||
```
|
||||
|
||||
### ✅ Cross-Component Field Mapping
|
||||
```python
|
||||
def test_job_has_youtube_description_template(self, client, auth_headers):
|
||||
"""Test youtube_description AND youtube_description_template are set."""
|
||||
# audio_search sets youtube_description
|
||||
# video_worker reads youtube_description_template
|
||||
# Both must be set for YouTube upload to work!
|
||||
```
|
||||
|
||||
## When to Run
|
||||
|
||||
| Situation | Run This |
|
||||
|-----------|----------|
|
||||
| Quick check before commit | `./scripts/run-emulator-tests.sh` |
|
||||
| Testing CLI changes | `./scripts/run-cli-integration-tests.sh` |
|
||||
| Testing backend API changes | `./scripts/run-cli-integration-tests.sh` |
|
||||
| Before creating PR | Both of the above |
|
||||
| Pre-production | Cloud integration tests |
|
||||
|
||||
## Test Files
|
||||
|
||||
### `backend/tests/emulator/test_e2e_cli_backend.py` (Primary)
|
||||
|
||||
Key test classes:
|
||||
- `TestStyleFileUploadE2E` - Full style file upload flow with content-type verification
|
||||
- `TestYouTubeDescriptionFieldMapping` - Verifies youtube_description_template is set
|
||||
- `TestDownloadAuthHeaders` - Verifies auth headers are sent with downloads
|
||||
- `TestFullAudioSearchFlow` - Complete audio search → job creation flow
|
||||
- `TestCLIClientIntegration` - Tests actual CLI client code
|
||||
|
||||
### `tests/integration/test_cli_backend_integration.py` (Legacy)
|
||||
|
||||
- `TestSignedUrlUploadRoundTrip` - Full upload flow
|
||||
- `TestContentTypeMatching` - Content-type bug documentation
|
||||
- `TestAudioSearchWithStyles` - API contract tests
|
||||
|
||||
### Test Fixtures
|
||||
|
||||
- `test_style_files` - Creates minimal valid PNG/TTF/JSON files
|
||||
- `cli_config` - Points CLI at local backend
|
||||
|
||||
## Extending Tests
|
||||
|
||||
### Adding a New Integration Test
|
||||
|
||||
```python
|
||||
class TestMyNewFeature:
|
||||
def test_my_feature(self, cli_config, tmp_path):
|
||||
from karaoke_gen.utils.remote_cli import RemoteKaraokeClient, RemoteConfig
|
||||
import logging
|
||||
|
||||
config = RemoteConfig(
|
||||
service_url=cli_config['service_url'],
|
||||
auth_token=cli_config['auth_token'],
|
||||
environment='test'
|
||||
)
|
||||
client = RemoteKaraokeClient(config, logging.getLogger("test"))
|
||||
|
||||
# Test your feature
|
||||
result = client.some_method(...)
|
||||
assert result['expected_field'] == expected_value
|
||||
```
|
||||
|
||||
## Prerequisites
|
||||
|
||||
1. **Docker** (for fake-gcs-server)
|
||||
2. **gcloud CLI** with Firestore emulator:
|
||||
```bash
|
||||
gcloud components install cloud-firestore-emulator
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "Emulators not running"
|
||||
```bash
|
||||
./scripts/start-emulators.sh
|
||||
```
|
||||
|
||||
### "Backend failed to start"
|
||||
Check if port 8000 is already in use:
|
||||
```bash
|
||||
lsof -i :8000
|
||||
```
|
||||
|
||||
### Tests pass locally but fail in CI
|
||||
The integration tests require Docker, which may not be available in all CI environments. Consider:
|
||||
- Running in a CI job with Docker support
|
||||
- Skipping in CI and running locally before merge
|
||||
|
||||
## Benefits
|
||||
|
||||
| Before | After |
|
||||
|--------|-------|
|
||||
| 20+ min per iteration | < 30 sec per iteration |
|
||||
| Manual log inspection | Automated assertions |
|
||||
| Bugs found in production | Bugs caught locally |
|
||||
| Expensive cloud resources | Free local emulators |
|
||||
|
||||
@@ -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
@@ -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
@@ -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
|
||||
|
||||
@@ -76,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
|
||||
|
||||
|
||||
@@ -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...")
|
||||
|
||||
@@ -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}")
|
||||
|
||||
+235
-12
@@ -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
|
||||
@@ -1081,7 +1095,8 @@ class RemoteKaraokeClient:
|
||||
if url.startswith('/'):
|
||||
url = f"{self.config.service_url}{url}"
|
||||
|
||||
response = requests.get(url, stream=True, timeout=600)
|
||||
# Use session headers (includes Authorization) for authenticated downloads
|
||||
response = self.session.get(url, stream=True, timeout=600)
|
||||
if response.status_code != 200:
|
||||
return False
|
||||
|
||||
@@ -1192,6 +1207,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 +1248,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):
|
||||
# Use full path for content type detection (not just extension)
|
||||
content_type = self._get_content_type(asset_path)
|
||||
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 +1298,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 +1708,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 +1745,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 +1760,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 +1842,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 +3055,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
@@ -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
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.75.35"
|
||||
version = "0.75.52"
|
||||
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"
|
||||
|
||||
Executable
+111
@@ -0,0 +1,111 @@
|
||||
#!/bin/bash
|
||||
# Run CLI + Backend integration tests
|
||||
#
|
||||
# This script:
|
||||
# 1. Starts emulators
|
||||
# 2. Starts local backend
|
||||
# 3. Runs integration tests
|
||||
# 4. Cleans up
|
||||
#
|
||||
# Usage:
|
||||
# ./scripts/run-cli-integration-tests.sh
|
||||
|
||||
set -e
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
|
||||
echo "🧪 Running CLI + Backend Integration Tests"
|
||||
echo "==========================================="
|
||||
echo ""
|
||||
|
||||
# Cleanup function
|
||||
cleanup() {
|
||||
echo ""
|
||||
echo "Cleaning up..."
|
||||
|
||||
# Kill backend if running
|
||||
if [ ! -z "$BACKEND_PID" ]; then
|
||||
kill $BACKEND_PID 2>/dev/null || true
|
||||
echo " Stopped backend (PID $BACKEND_PID)"
|
||||
fi
|
||||
|
||||
# Stop emulators
|
||||
"$SCRIPT_DIR/stop-emulators.sh" 2>/dev/null || true
|
||||
}
|
||||
|
||||
trap cleanup EXIT
|
||||
|
||||
# Step 1: Start emulators
|
||||
echo "Step 1/4: Starting GCP emulators..."
|
||||
"$SCRIPT_DIR/start-emulators.sh"
|
||||
echo ""
|
||||
|
||||
# Step 2: Set environment
|
||||
echo "Step 2/4: Setting environment..."
|
||||
export FIRESTORE_EMULATOR_HOST="127.0.0.1:8080"
|
||||
export STORAGE_EMULATOR_HOST="http://127.0.0.1:4443"
|
||||
export GOOGLE_CLOUD_PROJECT="test-project"
|
||||
export GCS_BUCKET_NAME="test-bucket"
|
||||
export FIRESTORE_COLLECTION="jobs"
|
||||
export ENVIRONMENT="test"
|
||||
export ADMIN_TOKENS="test-admin-token"
|
||||
|
||||
# Disable external services for tests
|
||||
export FLACFETCH_API_URL=""
|
||||
export AUDIO_SEPARATOR_API_URL=""
|
||||
export AUDIOSHAKE_API_TOKEN=""
|
||||
export GENIUS_API_TOKEN=""
|
||||
export SPOTIFY_COOKIE=""
|
||||
|
||||
echo " Environment configured for local testing"
|
||||
echo ""
|
||||
|
||||
# Step 3: Start backend
|
||||
echo "Step 3/4: Starting local backend..."
|
||||
cd "$PROJECT_ROOT"
|
||||
|
||||
if command -v poetry &> /dev/null; then
|
||||
poetry run uvicorn backend.main:app --host 127.0.0.1 --port 8000 &
|
||||
else
|
||||
python -m uvicorn backend.main:app --host 127.0.0.1 --port 8000 &
|
||||
fi
|
||||
BACKEND_PID=$!
|
||||
|
||||
# Wait for backend
|
||||
echo " Waiting for backend..."
|
||||
for i in {1..30}; do
|
||||
if curl -s http://localhost:8000/api/health > /dev/null 2>&1; then
|
||||
echo " Backend ready!"
|
||||
break
|
||||
fi
|
||||
if [ $i -eq 30 ]; then
|
||||
echo " ❌ Backend failed to start"
|
||||
exit 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
echo ""
|
||||
|
||||
# Step 4: Run tests
|
||||
echo "Step 4/4: Running integration tests..."
|
||||
echo ""
|
||||
|
||||
cd "$PROJECT_ROOT"
|
||||
|
||||
if command -v poetry &> /dev/null; then
|
||||
PYTEST_CMD="poetry run pytest"
|
||||
else
|
||||
PYTEST_CMD="pytest"
|
||||
fi
|
||||
|
||||
if $PYTEST_CMD tests/integration/test_cli_backend_integration.py -v --tb=short; then
|
||||
echo ""
|
||||
echo "✅ All CLI + Backend integration tests passed!"
|
||||
exit 0
|
||||
else
|
||||
echo ""
|
||||
echo "❌ Some integration tests failed"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
Executable
+101
@@ -0,0 +1,101 @@
|
||||
#!/bin/bash
|
||||
# Start local test environment with emulators and backend
|
||||
#
|
||||
# This sets up everything needed to run CLI+Backend integration tests locally.
|
||||
# Much faster than deploying to cloud for testing!
|
||||
#
|
||||
# Usage:
|
||||
# ./scripts/start-local-test-env.sh
|
||||
# # In another terminal:
|
||||
# pytest tests/integration/test_cli_backend_integration.py -v
|
||||
|
||||
set -e
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
|
||||
echo "🚀 Starting local test environment"
|
||||
echo "=================================="
|
||||
echo ""
|
||||
|
||||
# Step 1: Start emulators
|
||||
echo "Step 1/2: Starting GCP emulators..."
|
||||
"$SCRIPT_DIR/start-emulators.sh"
|
||||
echo ""
|
||||
|
||||
# Set environment variables for local backend
|
||||
export FIRESTORE_EMULATOR_HOST="127.0.0.1:8080"
|
||||
export STORAGE_EMULATOR_HOST="http://127.0.0.1:4443"
|
||||
export GOOGLE_CLOUD_PROJECT="test-project"
|
||||
export GCS_BUCKET_NAME="test-bucket"
|
||||
export FIRESTORE_COLLECTION="jobs"
|
||||
export ENVIRONMENT="test"
|
||||
export ADMIN_TOKENS="test-admin-token"
|
||||
|
||||
# Also export for any external services to be mocked/disabled
|
||||
export FLACFETCH_API_URL=""
|
||||
export AUDIO_SEPARATOR_API_URL=""
|
||||
export AUDIOSHAKE_API_TOKEN=""
|
||||
export GENIUS_API_TOKEN=""
|
||||
export SPOTIFY_COOKIE=""
|
||||
|
||||
echo "Step 2/2: Starting local backend..."
|
||||
echo ""
|
||||
echo "Environment:"
|
||||
echo " FIRESTORE_EMULATOR_HOST=$FIRESTORE_EMULATOR_HOST"
|
||||
echo " STORAGE_EMULATOR_HOST=$STORAGE_EMULATOR_HOST"
|
||||
echo " GOOGLE_CLOUD_PROJECT=$GOOGLE_CLOUD_PROJECT"
|
||||
echo " ADMIN_TOKENS=test-admin-token"
|
||||
echo ""
|
||||
|
||||
cd "$PROJECT_ROOT"
|
||||
|
||||
# Start backend in background
|
||||
if command -v poetry &> /dev/null; then
|
||||
echo "Starting backend with poetry..."
|
||||
poetry run uvicorn backend.main:app --host 0.0.0.0 --port 8000 --reload &
|
||||
else
|
||||
echo "Starting backend with Python..."
|
||||
python -m uvicorn backend.main:app --host 0.0.0.0 --port 8000 --reload &
|
||||
fi
|
||||
|
||||
BACKEND_PID=$!
|
||||
echo "Backend PID: $BACKEND_PID"
|
||||
|
||||
# Wait for backend to be ready
|
||||
echo ""
|
||||
echo "Waiting for backend to be ready..."
|
||||
for i in {1..30}; do
|
||||
if curl -s http://localhost:8000/api/health > /dev/null 2>&1; then
|
||||
echo "✅ Backend is ready!"
|
||||
break
|
||||
fi
|
||||
if [ $i -eq 30 ]; then
|
||||
echo "❌ Backend failed to start"
|
||||
kill $BACKEND_PID 2>/dev/null || true
|
||||
"$SCRIPT_DIR/stop-emulators.sh"
|
||||
exit 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "=============================================="
|
||||
echo "✅ Local test environment is running!"
|
||||
echo ""
|
||||
echo "Run integration tests with:"
|
||||
echo " pytest tests/integration/test_cli_backend_integration.py -v"
|
||||
echo ""
|
||||
echo "Or run all CLI+Backend tests:"
|
||||
echo " ./scripts/run-cli-integration-tests.sh"
|
||||
echo ""
|
||||
echo "To stop:"
|
||||
echo " kill $BACKEND_PID"
|
||||
echo " ./scripts/stop-emulators.sh"
|
||||
echo ""
|
||||
echo "Backend PID: $BACKEND_PID"
|
||||
echo "=============================================="
|
||||
|
||||
# Keep script running (for foreground mode)
|
||||
wait $BACKEND_PID
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
"""
|
||||
CLI + Backend Integration Tests
|
||||
|
||||
These tests run the ACTUAL CLI code against a LOCAL backend with emulators.
|
||||
This catches bugs like content-type mismatches that unit tests with mocks miss.
|
||||
|
||||
Run with:
|
||||
./scripts/run-cli-integration-tests.sh
|
||||
|
||||
Prerequisites:
|
||||
- GCS emulator running (fake-gcs-server)
|
||||
- Firestore emulator running
|
||||
- Backend running locally against emulators
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import pytest
|
||||
import tempfile
|
||||
import requests
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
# Add project root to path
|
||||
PROJECT_ROOT = Path(__file__).parent.parent.parent
|
||||
sys.path.insert(0, str(PROJECT_ROOT))
|
||||
|
||||
|
||||
def emulators_and_backend_running() -> bool:
|
||||
"""Check if emulators and local backend are running."""
|
||||
try:
|
||||
# Check GCS emulator
|
||||
gcs_response = requests.get("http://localhost:4443/storage/v1/b", timeout=2)
|
||||
if gcs_response.status_code != 200:
|
||||
return False
|
||||
|
||||
# Check Firestore emulator
|
||||
firestore_response = requests.get("http://localhost:8080", timeout=2)
|
||||
|
||||
# Check local backend
|
||||
backend_response = requests.get("http://localhost:8000/api/health", timeout=2)
|
||||
if backend_response.status_code != 200:
|
||||
return False
|
||||
|
||||
return True
|
||||
except requests.exceptions.RequestException:
|
||||
return False
|
||||
|
||||
|
||||
# Skip all tests if infrastructure isn't running
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not emulators_and_backend_running(),
|
||||
reason="Emulators and local backend not running. Run: ./scripts/start-local-test-env.sh"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_style_files(tmp_path):
|
||||
"""Create test style files for upload testing."""
|
||||
# Create a minimal style params JSON
|
||||
style_params = {
|
||||
"intro": {
|
||||
"background_color": "#000000",
|
||||
"background_image": str(tmp_path / "intro_bg.png"),
|
||||
"font": str(tmp_path / "test_font.ttf"),
|
||||
"title_color": "#ffffff",
|
||||
"artist_color": "#ffdf6b"
|
||||
},
|
||||
"karaoke": {
|
||||
"background_color": "#000000",
|
||||
"background_image": str(tmp_path / "karaoke_bg.png"),
|
||||
"font_path": str(tmp_path / "test_font.ttf"),
|
||||
"primary_color": "112, 112, 247, 255",
|
||||
"secondary_color": "255, 255, 255, 255"
|
||||
},
|
||||
"cdg": {
|
||||
"background_color": "#000000",
|
||||
"instrumental_background": str(tmp_path / "cdg_inst_bg.png"),
|
||||
"title_screen_background": str(tmp_path / "cdg_title_bg.png"),
|
||||
"font_path": str(tmp_path / "test_font.ttf")
|
||||
}
|
||||
}
|
||||
|
||||
style_params_path = tmp_path / "styles.json"
|
||||
with open(style_params_path, 'w') as f:
|
||||
json.dump(style_params, f)
|
||||
|
||||
# Create minimal test image (1x1 pixel PNG)
|
||||
# PNG header + minimal IHDR + IDAT + IEND
|
||||
minimal_png = bytes([
|
||||
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, # PNG signature
|
||||
0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, # IHDR chunk
|
||||
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, # 1x1
|
||||
0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53,
|
||||
0xDE, 0x00, 0x00, 0x00, 0x0C, 0x49, 0x44, 0x41, # IDAT chunk
|
||||
0x54, 0x08, 0xD7, 0x63, 0xF8, 0xFF, 0xFF, 0x3F,
|
||||
0x00, 0x05, 0xFE, 0x02, 0xFE, 0xDC, 0xCC, 0x59,
|
||||
0xE7, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, # IEND chunk
|
||||
0x44, 0xAE, 0x42, 0x60, 0x82
|
||||
])
|
||||
|
||||
# Create test images
|
||||
for name in ["intro_bg.png", "karaoke_bg.png", "cdg_inst_bg.png", "cdg_title_bg.png"]:
|
||||
(tmp_path / name).write_bytes(minimal_png)
|
||||
|
||||
# Create minimal TTF font (just header)
|
||||
minimal_ttf = bytes([0x00, 0x01, 0x00, 0x00] + [0x00] * 100)
|
||||
(tmp_path / "test_font.ttf").write_bytes(minimal_ttf)
|
||||
|
||||
return {
|
||||
'style_params_path': str(style_params_path),
|
||||
'tmp_path': tmp_path
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cli_config():
|
||||
"""Configuration for CLI to connect to local backend."""
|
||||
return {
|
||||
'service_url': 'http://localhost:8000',
|
||||
'auth_token': 'test-admin-token',
|
||||
}
|
||||
|
||||
|
||||
class TestSignedUrlUploadRoundTrip:
|
||||
"""
|
||||
Test the full signed URL upload flow:
|
||||
1. CLI requests signed URLs from backend
|
||||
2. CLI uploads files directly to GCS using signed URLs
|
||||
3. Backend can read the uploaded files
|
||||
|
||||
This is the flow that broke with the content-type mismatch bug.
|
||||
"""
|
||||
|
||||
def test_style_params_json_upload(self, test_style_files, cli_config):
|
||||
"""Test uploading style_params.json via signed URL."""
|
||||
from karaoke_gen.utils.remote_cli import RemoteKaraokeClient, RemoteConfig
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger("test")
|
||||
config = RemoteConfig(
|
||||
service_url=cli_config['service_url'],
|
||||
auth_token=cli_config['auth_token'],
|
||||
environment='test'
|
||||
)
|
||||
client = RemoteKaraokeClient(config, logger)
|
||||
|
||||
# This should:
|
||||
# 1. Send request with style_files metadata
|
||||
# 2. Get back signed URLs
|
||||
# 3. Upload files to those URLs
|
||||
# 4. Return job info
|
||||
try:
|
||||
result = client.search_audio(
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
style_params_path=test_style_files['style_params_path'],
|
||||
auto_download=False
|
||||
)
|
||||
|
||||
# If we get here without 403, the upload worked!
|
||||
assert 'job_id' in result
|
||||
|
||||
except Exception as e:
|
||||
# Check if it's a content-type mismatch (403)
|
||||
if '403' in str(e):
|
||||
pytest.fail(f"Signed URL upload failed with 403 - likely content-type mismatch: {e}")
|
||||
raise
|
||||
|
||||
def test_image_file_upload(self, test_style_files, cli_config):
|
||||
"""Test uploading PNG image via signed URL."""
|
||||
from karaoke_gen.utils.remote_cli import RemoteKaraokeClient, RemoteConfig
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger("test")
|
||||
config = RemoteConfig(
|
||||
service_url=cli_config['service_url'],
|
||||
auth_token=cli_config['auth_token'],
|
||||
environment='test'
|
||||
)
|
||||
client = RemoteKaraokeClient(config, logger)
|
||||
|
||||
try:
|
||||
result = client.search_audio(
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
style_params_path=test_style_files['style_params_path'],
|
||||
auto_download=False
|
||||
)
|
||||
|
||||
# Verify job was created
|
||||
assert 'job_id' in result
|
||||
|
||||
# Verify style assets were recorded
|
||||
job_id = result['job_id']
|
||||
job_response = requests.get(
|
||||
f"{cli_config['service_url']}/api/jobs/{job_id}",
|
||||
headers={'Authorization': f"Bearer {cli_config['auth_token']}"}
|
||||
)
|
||||
assert job_response.status_code == 200
|
||||
job = job_response.json()
|
||||
|
||||
# Check style assets exist
|
||||
assert 'style_assets' in job or job.get('style_params_gcs_path')
|
||||
|
||||
except Exception as e:
|
||||
if '403' in str(e):
|
||||
pytest.fail(f"Image upload failed with 403 - content-type mismatch: {e}")
|
||||
raise
|
||||
|
||||
def test_font_file_upload(self, test_style_files, cli_config):
|
||||
"""Test uploading TTF font via signed URL."""
|
||||
from karaoke_gen.utils.remote_cli import RemoteKaraokeClient, RemoteConfig
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger("test")
|
||||
config = RemoteConfig(
|
||||
service_url=cli_config['service_url'],
|
||||
auth_token=cli_config['auth_token'],
|
||||
environment='test'
|
||||
)
|
||||
client = RemoteKaraokeClient(config, logger)
|
||||
|
||||
try:
|
||||
result = client.search_audio(
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
style_params_path=test_style_files['style_params_path'],
|
||||
auto_download=False
|
||||
)
|
||||
assert 'job_id' in result
|
||||
|
||||
except Exception as e:
|
||||
if '403' in str(e):
|
||||
pytest.fail(f"Font upload failed with 403 - content-type mismatch: {e}")
|
||||
raise
|
||||
|
||||
|
||||
class TestContentTypeMatching:
|
||||
"""
|
||||
Direct tests for content-type handling.
|
||||
These catch the specific bug we found.
|
||||
"""
|
||||
|
||||
def test_get_content_type_with_full_path(self):
|
||||
"""Test _get_content_type works with full paths."""
|
||||
from karaoke_gen.utils.remote_cli import RemoteKaraokeClient, RemoteConfig
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger("test")
|
||||
config = RemoteConfig(
|
||||
service_url='http://localhost:8000',
|
||||
auth_token='test',
|
||||
environment='test'
|
||||
)
|
||||
client = RemoteKaraokeClient(config, logger)
|
||||
|
||||
# Test various file paths
|
||||
assert client._get_content_type('/path/to/file.json') == 'application/json'
|
||||
assert client._get_content_type('/path/to/file.png') == 'image/png'
|
||||
assert client._get_content_type('/path/to/file.ttf') == 'font/ttf'
|
||||
assert client._get_content_type('/path/to/file.flac') == 'audio/flac'
|
||||
|
||||
def test_get_content_type_with_extension_only_bug(self):
|
||||
"""
|
||||
Test that passing just an extension doesn't work.
|
||||
This documents the bug we found.
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
# This is the bug: Path('.json').suffix returns empty string!
|
||||
assert Path('.json').suffix == ''
|
||||
assert Path('.png').suffix == ''
|
||||
|
||||
# But full paths work correctly
|
||||
assert Path('/path/to/file.json').suffix == '.json'
|
||||
assert Path('/path/to/file.png').suffix == '.png'
|
||||
|
||||
|
||||
class TestAudioSearchWithStyles:
|
||||
"""Test audio search endpoint with style file handling."""
|
||||
|
||||
def test_audio_search_returns_style_upload_urls(self, cli_config, tmp_path):
|
||||
"""Test that audio search returns signed URLs for style files."""
|
||||
# Create minimal style params
|
||||
style_params = {"karaoke": {"background_color": "#000000"}}
|
||||
style_path = tmp_path / "styles.json"
|
||||
with open(style_path, 'w') as f:
|
||||
json.dump(style_params, f)
|
||||
|
||||
# Make direct API call to check response format
|
||||
response = requests.post(
|
||||
f"{cli_config['service_url']}/api/audio-search/search",
|
||||
headers={'Authorization': f"Bearer {cli_config['auth_token']}"},
|
||||
json={
|
||||
'artist': 'Test Artist',
|
||||
'title': 'Test Song',
|
||||
'auto_download': False,
|
||||
'style_files': [
|
||||
{
|
||||
'filename': 'styles.json',
|
||||
'content_type': 'application/json',
|
||||
'file_type': 'style_params'
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
# Should get 200 or 404 (no results), not 500
|
||||
assert response.status_code in [200, 404], f"Unexpected status: {response.status_code} - {response.text}"
|
||||
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
# If style files were provided, should get upload URLs back
|
||||
if 'style_upload_urls' in data:
|
||||
assert len(data['style_upload_urls']) > 0
|
||||
for url_info in data['style_upload_urls']:
|
||||
assert 'upload_url' in url_info
|
||||
assert 'file_type' in url_info
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
@@ -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."""
|
||||
@@ -533,6 +544,73 @@ class TestRemoteKaraokeClient:
|
||||
|
||||
assert result is False
|
||||
|
||||
def test_download_file_via_url_uses_session_with_auth(self, client, tmp_path):
|
||||
"""Test that download_file_via_url uses session (which has auth headers).
|
||||
|
||||
This test verifies the fix for the bug where downloads failed because
|
||||
the auth header wasn't included in requests.
|
||||
"""
|
||||
# Setup: mock the session.get method
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.iter_content.return_value = [b'test content']
|
||||
client.session.get = MagicMock(return_value=mock_response)
|
||||
|
||||
local_path = str(tmp_path / "test.mp4")
|
||||
|
||||
# Call the method with a relative URL
|
||||
result = client.download_file_via_url("/api/jobs/123/download/finals/mp4", local_path)
|
||||
|
||||
assert result is True
|
||||
# CRITICAL: Verify session.get was called (not requests.get directly)
|
||||
client.session.get.assert_called_once()
|
||||
# Verify the URL was properly constructed with service URL from config
|
||||
call_args = client.session.get.call_args
|
||||
expected_url = f"{client.config.service_url}/api/jobs/123/download/finals/mp4"
|
||||
assert expected_url == call_args[0][0]
|
||||
# Verify the file was written
|
||||
assert (tmp_path / "test.mp4").exists()
|
||||
|
||||
def test_download_file_via_url_absolute_url(self, client, tmp_path):
|
||||
"""Test download_file_via_url with absolute URL (e.g., signed GCS URL)."""
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.iter_content.return_value = [b'gcs content']
|
||||
client.session.get = MagicMock(return_value=mock_response)
|
||||
|
||||
local_path = str(tmp_path / "test.mp4")
|
||||
absolute_url = "https://storage.googleapis.com/bucket/path/file.mp4?signed=xyz"
|
||||
|
||||
result = client.download_file_via_url(absolute_url, local_path)
|
||||
|
||||
assert result is True
|
||||
# Verify the absolute URL was used as-is
|
||||
call_args = client.session.get.call_args
|
||||
assert absolute_url == call_args[0][0]
|
||||
|
||||
def test_download_file_via_url_failure_returns_false(self, client, tmp_path):
|
||||
"""Test that download failures return False without raising."""
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 403 # Forbidden - simulates auth failure
|
||||
client.session.get = MagicMock(return_value=mock_response)
|
||||
|
||||
local_path = str(tmp_path / "test.mp4")
|
||||
|
||||
result = client.download_file_via_url("/api/jobs/123/download", local_path)
|
||||
|
||||
assert result is False
|
||||
assert not (tmp_path / "test.mp4").exists()
|
||||
|
||||
def test_download_file_via_url_network_error(self, client, tmp_path):
|
||||
"""Test that network errors return False without raising."""
|
||||
client.session.get = MagicMock(side_effect=Exception("Network error"))
|
||||
|
||||
local_path = str(tmp_path / "test.mp4")
|
||||
|
||||
result = client.download_file_via_url("/api/jobs/123/download", local_path)
|
||||
|
||||
assert result is False
|
||||
|
||||
@patch.object(RemoteKaraokeClient, '_request')
|
||||
def test_submit_job_file_not_found(self, mock_request, client):
|
||||
"""Test submitting job with nonexistent file."""
|
||||
@@ -2236,3 +2314,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
|
||||
Reference in new issue
Block a user