mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-30 17:21:26 +09:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4b346dd369 | ||
|
|
7480950a1b | ||
|
|
64ada25e9c | ||
|
|
de6322dd87 | ||
|
|
49b472429d |
No files matched your search
@@ -27,6 +27,10 @@ COPY lyrics_transcriber_temp /app/lyrics_transcriber_temp
|
||||
RUN pip install --no-cache-dir --upgrade pip && \
|
||||
pip install --no-cache-dir -e .
|
||||
|
||||
# Download spaCy language model for lyrics transcription
|
||||
# This must be done at build time, not runtime (Cloud Run network restrictions)
|
||||
RUN python -m spacy download en_core_web_sm
|
||||
|
||||
# Label with build info
|
||||
ARG BUILD_DATE
|
||||
ARG BUILD_ID
|
||||
|
||||
@@ -1,13 +1,24 @@
|
||||
"""
|
||||
File upload route for local file submission with style configuration support.
|
||||
|
||||
Supports two upload flows:
|
||||
1. Direct upload (original): All files sent as multipart form data to /api/jobs/upload
|
||||
- Simple but limited by Cloud Run's 32MB request body size
|
||||
|
||||
2. Signed URL upload (recommended for large files):
|
||||
- POST /api/jobs/create-with-upload-urls - Creates job, returns signed GCS upload URLs
|
||||
- Client uploads files directly to GCS using signed URLs (no size limit)
|
||||
- POST /api/jobs/{job_id}/uploads-complete - Validates uploads, triggers workers
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Request
|
||||
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Request, Body
|
||||
from pathlib import Path
|
||||
from typing import Optional, List, Dict, Any
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from backend.models.job import JobCreate, JobStatus
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
@@ -19,6 +30,76 @@ from backend.version import VERSION
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(tags=["jobs"])
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Pydantic models for signed URL upload flow
|
||||
# ============================================================================
|
||||
|
||||
class FileUploadRequest(BaseModel):
|
||||
"""Information about a 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: 'audio', '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', 'lyrics_file'")
|
||||
|
||||
|
||||
class CreateJobWithUploadUrlsRequest(BaseModel):
|
||||
"""Request to create a job and get signed upload URLs."""
|
||||
# Required fields
|
||||
artist: str = Field(..., description="Artist name")
|
||||
title: str = Field(..., description="Song title")
|
||||
files: List[FileUploadRequest] = Field(..., description="List of files to upload")
|
||||
|
||||
# Processing options
|
||||
enable_cdg: bool = Field(True, description="Generate CDG+MP3 package")
|
||||
enable_txt: bool = Field(True, description="Generate TXT+MP3 package")
|
||||
|
||||
# Finalisation options
|
||||
brand_prefix: Optional[str] = Field(None, description="Brand code prefix (e.g., NOMAD)")
|
||||
enable_youtube_upload: bool = Field(False, description="Upload to YouTube")
|
||||
youtube_description: Optional[str] = Field(None, description="YouTube video description text")
|
||||
discord_webhook_url: Optional[str] = Field(None, description="Discord webhook URL for notifications")
|
||||
webhook_url: Optional[str] = Field(None, description="Generic webhook URL")
|
||||
user_email: Optional[str] = Field(None, description="User email for notifications")
|
||||
|
||||
# Distribution options (native API - preferred for remote CLI)
|
||||
dropbox_path: Optional[str] = Field(None, description="Dropbox folder path for organized output")
|
||||
gdrive_folder_id: Optional[str] = Field(None, description="Google Drive folder ID for public share uploads")
|
||||
|
||||
# Legacy distribution options (rclone - deprecated)
|
||||
organised_dir_rclone_root: Optional[str] = Field(None, description="[Deprecated] rclone remote path")
|
||||
|
||||
# Lyrics configuration
|
||||
lyrics_artist: Optional[str] = Field(None, description="Override artist name for lyrics search")
|
||||
lyrics_title: Optional[str] = Field(None, description="Override title for lyrics search")
|
||||
subtitle_offset_ms: int = Field(0, description="Subtitle timing offset in milliseconds")
|
||||
|
||||
# Audio separation model configuration
|
||||
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")
|
||||
|
||||
|
||||
class SignedUploadUrl(BaseModel):
|
||||
"""Signed URL for uploading a file."""
|
||||
file_type: str = Field(..., description="Type of file this URL is for")
|
||||
gcs_path: str = Field(..., description="The GCS path where file will be stored")
|
||||
upload_url: str = Field(..., description="Signed URL to PUT the file to")
|
||||
content_type: str = Field(..., description="Content-Type header to use when uploading")
|
||||
|
||||
|
||||
class CreateJobWithUploadUrlsResponse(BaseModel):
|
||||
"""Response from creating a job with upload URLs."""
|
||||
status: str
|
||||
job_id: str
|
||||
message: str
|
||||
upload_urls: List[SignedUploadUrl]
|
||||
server_version: str
|
||||
|
||||
|
||||
class UploadsCompleteRequest(BaseModel):
|
||||
"""Request to mark uploads as complete and start processing."""
|
||||
uploaded_files: List[str] = Field(..., description="List of file_types that were successfully uploaded")
|
||||
|
||||
# Initialize services
|
||||
job_manager = JobManager()
|
||||
storage_service = StorageService()
|
||||
@@ -131,6 +212,10 @@ async def upload_and_create_job(
|
||||
lyrics_title: Optional[str] = Form(None, description="Override title for lyrics search"),
|
||||
lyrics_file: Optional[UploadFile] = File(None, description="User-provided lyrics file (TXT, DOCX, RTF)"),
|
||||
subtitle_offset_ms: int = Form(0, description="Subtitle timing offset in milliseconds (positive = delay)"),
|
||||
# Audio separation model configuration
|
||||
clean_instrumental_model: Optional[str] = Form(None, description="Model for clean instrumental separation (e.g., model_bs_roformer_ep_317_sdr_12.9755.ckpt)"),
|
||||
backing_vocals_models: Optional[str] = Form(None, description="Comma-separated list of models for backing vocals separation"),
|
||||
other_stems_models: Optional[str] = Form(None, description="Comma-separated list of models for other stems (bass, drums, guitar, etc.)"),
|
||||
):
|
||||
"""
|
||||
Upload an audio file and create a karaoke generation job with full style configuration.
|
||||
@@ -244,6 +329,15 @@ async def upload_and_create_job(
|
||||
# Extract request metadata for tracking and filtering
|
||||
request_metadata = extract_request_metadata(request, created_from="upload")
|
||||
|
||||
# Parse comma-separated model lists into arrays
|
||||
parsed_backing_vocals_models = None
|
||||
if backing_vocals_models:
|
||||
parsed_backing_vocals_models = [m.strip() for m in backing_vocals_models.split(',') if m.strip()]
|
||||
|
||||
parsed_other_stems_models = None
|
||||
if other_stems_models:
|
||||
parsed_other_stems_models = [m.strip() for m in other_stems_models.split(',') if m.strip()]
|
||||
|
||||
# Create job first to get job_id
|
||||
job_create = JobCreate(
|
||||
artist=artist,
|
||||
@@ -266,6 +360,10 @@ async def upload_and_create_job(
|
||||
lyrics_artist=lyrics_artist,
|
||||
lyrics_title=lyrics_title,
|
||||
subtitle_offset_ms=subtitle_offset_ms,
|
||||
# Audio separation model configuration
|
||||
clean_instrumental_model=clean_instrumental_model,
|
||||
backing_vocals_models=parsed_backing_vocals_models,
|
||||
other_stems_models=parsed_other_stems_models,
|
||||
# Request metadata for tracking and filtering
|
||||
request_metadata=request_metadata,
|
||||
)
|
||||
@@ -378,6 +476,14 @@ async def upload_and_create_job(
|
||||
if subtitle_offset_ms != 0:
|
||||
update_data['subtitle_offset_ms'] = subtitle_offset_ms
|
||||
|
||||
# Audio separation model configuration
|
||||
if clean_instrumental_model:
|
||||
update_data['clean_instrumental_model'] = clean_instrumental_model
|
||||
if parsed_backing_vocals_models:
|
||||
update_data['backing_vocals_models'] = parsed_backing_vocals_models
|
||||
if parsed_other_stems_models:
|
||||
update_data['other_stems_models'] = parsed_other_stems_models
|
||||
|
||||
job_manager.update_job(job_id, update_data)
|
||||
|
||||
# Verify the update
|
||||
@@ -457,3 +563,348 @@ async def upload_and_create_job(
|
||||
except Exception as e:
|
||||
logger.error(f"Error uploading files: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Signed URL Upload Flow - For large files that exceed Cloud Run's 32MB limit
|
||||
# ============================================================================
|
||||
|
||||
# Valid file types and their expected extensions
|
||||
VALID_FILE_TYPES = {
|
||||
'audio': ALLOWED_AUDIO_EXTENSIONS,
|
||||
'style_params': {'.json'},
|
||||
'style_intro_background': ALLOWED_IMAGE_EXTENSIONS,
|
||||
'style_karaoke_background': ALLOWED_IMAGE_EXTENSIONS,
|
||||
'style_end_background': ALLOWED_IMAGE_EXTENSIONS,
|
||||
'style_font': ALLOWED_FONT_EXTENSIONS,
|
||||
'style_cdg_instrumental_background': ALLOWED_IMAGE_EXTENSIONS,
|
||||
'style_cdg_title_background': ALLOWED_IMAGE_EXTENSIONS,
|
||||
'style_cdg_outro_background': ALLOWED_IMAGE_EXTENSIONS,
|
||||
'lyrics_file': {'.txt', '.docx', '.rtf'},
|
||||
}
|
||||
|
||||
|
||||
def _get_gcs_path_for_file(job_id: str, file_type: str, filename: str) -> str:
|
||||
"""Generate the GCS path for a file based on its type."""
|
||||
ext = Path(filename).suffix.lower()
|
||||
|
||||
if file_type == 'audio':
|
||||
return f"uploads/{job_id}/audio/{filename}"
|
||||
elif file_type == 'style_params':
|
||||
return f"uploads/{job_id}/style/style_params.json"
|
||||
elif file_type.startswith('style_'):
|
||||
# Map style_intro_background -> intro_background, etc.
|
||||
asset_key = file_type.replace('style_', '')
|
||||
return f"uploads/{job_id}/style/{asset_key}{ext}"
|
||||
elif file_type == 'lyrics_file':
|
||||
return f"uploads/{job_id}/lyrics/user_lyrics{ext}"
|
||||
else:
|
||||
return f"uploads/{job_id}/other/{filename}"
|
||||
|
||||
|
||||
@router.post("/jobs/create-with-upload-urls", response_model=CreateJobWithUploadUrlsResponse)
|
||||
async def create_job_with_upload_urls(
|
||||
request: Request,
|
||||
body: CreateJobWithUploadUrlsRequest,
|
||||
):
|
||||
"""
|
||||
Create a karaoke generation job and return signed URLs for direct file upload to GCS.
|
||||
|
||||
This is the first step of the two-step upload flow for large files:
|
||||
1. Call this endpoint with job metadata and list of files to upload
|
||||
2. Upload each file directly to GCS using the returned signed URLs
|
||||
3. Call POST /api/jobs/{job_id}/uploads-complete to start processing
|
||||
|
||||
Benefits of this flow:
|
||||
- No file size limits (GCS supports up to 5TB)
|
||||
- Faster uploads (direct to storage, no proxy)
|
||||
- Works with any HTTP client (no HTTP/2 required)
|
||||
- Resumable uploads possible with GCS
|
||||
"""
|
||||
try:
|
||||
# Validate files list
|
||||
if not body.files:
|
||||
raise HTTPException(status_code=400, detail="At least one file is required")
|
||||
|
||||
# Check that audio file is included
|
||||
audio_files = [f for f in body.files if f.file_type == 'audio']
|
||||
if not audio_files:
|
||||
raise HTTPException(status_code=400, detail="An audio file is required")
|
||||
if len(audio_files) > 1:
|
||||
raise HTTPException(status_code=400, detail="Only one audio file is allowed")
|
||||
|
||||
# Validate file types and extensions
|
||||
for file_info in body.files:
|
||||
if file_info.file_type not in VALID_FILE_TYPES:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Invalid file_type: '{file_info.file_type}'. Valid types: {list(VALID_FILE_TYPES.keys())}"
|
||||
)
|
||||
|
||||
ext = Path(file_info.filename).suffix.lower()
|
||||
allowed_extensions = VALID_FILE_TYPES[file_info.file_type]
|
||||
if ext not in allowed_extensions:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Invalid file extension '{ext}' for file_type '{file_info.file_type}'. Allowed: {allowed_extensions}"
|
||||
)
|
||||
|
||||
# Apply default distribution settings from environment if not provided
|
||||
settings = get_settings()
|
||||
effective_dropbox_path = body.dropbox_path or settings.default_dropbox_path
|
||||
effective_gdrive_folder_id = body.gdrive_folder_id or settings.default_gdrive_folder_id
|
||||
effective_discord_webhook_url = body.discord_webhook_url or settings.default_discord_webhook_url
|
||||
|
||||
# Validate credentials for requested distribution services
|
||||
invalid_services = []
|
||||
credential_manager = get_credential_manager()
|
||||
|
||||
if body.enable_youtube_upload:
|
||||
result = credential_manager.check_youtube_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"youtube ({result.message})")
|
||||
|
||||
if effective_dropbox_path:
|
||||
result = credential_manager.check_dropbox_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"dropbox ({result.message})")
|
||||
|
||||
if effective_gdrive_folder_id:
|
||||
result = credential_manager.check_gdrive_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"gdrive ({result.message})")
|
||||
|
||||
if invalid_services:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"error": "credentials_invalid",
|
||||
"message": f"The following distribution services need re-authorization: {', '.join(invalid_services)}",
|
||||
"invalid_services": invalid_services,
|
||||
"auth_url": "/api/auth/status"
|
||||
}
|
||||
)
|
||||
|
||||
# Extract request metadata for tracking
|
||||
request_metadata = extract_request_metadata(request, created_from="signed_url_upload")
|
||||
|
||||
# Get original audio filename
|
||||
audio_file = audio_files[0]
|
||||
|
||||
# Create job
|
||||
job_create = JobCreate(
|
||||
artist=body.artist,
|
||||
title=body.title,
|
||||
filename=audio_file.filename,
|
||||
enable_cdg=body.enable_cdg,
|
||||
enable_txt=body.enable_txt,
|
||||
brand_prefix=body.brand_prefix,
|
||||
enable_youtube_upload=body.enable_youtube_upload,
|
||||
youtube_description=body.youtube_description,
|
||||
discord_webhook_url=effective_discord_webhook_url,
|
||||
webhook_url=body.webhook_url,
|
||||
user_email=body.user_email,
|
||||
dropbox_path=effective_dropbox_path,
|
||||
gdrive_folder_id=effective_gdrive_folder_id,
|
||||
organised_dir_rclone_root=body.organised_dir_rclone_root,
|
||||
lyrics_artist=body.lyrics_artist,
|
||||
lyrics_title=body.lyrics_title,
|
||||
subtitle_offset_ms=body.subtitle_offset_ms,
|
||||
clean_instrumental_model=body.clean_instrumental_model,
|
||||
backing_vocals_models=body.backing_vocals_models,
|
||||
other_stems_models=body.other_stems_models,
|
||||
request_metadata=request_metadata,
|
||||
)
|
||||
job = job_manager.create_job(job_create)
|
||||
job_id = job.job_id
|
||||
|
||||
logger.info(f"Created job {job_id} for {body.artist} - {body.title} (signed URL upload flow)")
|
||||
|
||||
# Generate signed upload URLs for each file
|
||||
upload_urls = []
|
||||
for file_info in body.files:
|
||||
gcs_path = _get_gcs_path_for_file(job_id, file_info.file_type, file_info.filename)
|
||||
|
||||
# Generate signed upload URL (valid for 60 minutes)
|
||||
signed_url = storage_service.generate_signed_upload_url(
|
||||
gcs_path,
|
||||
content_type=file_info.content_type,
|
||||
expiration_minutes=60
|
||||
)
|
||||
|
||||
upload_urls.append(SignedUploadUrl(
|
||||
file_type=file_info.file_type,
|
||||
gcs_path=gcs_path,
|
||||
upload_url=signed_url,
|
||||
content_type=file_info.content_type
|
||||
))
|
||||
|
||||
logger.info(f"Generated signed upload URL for {file_info.file_type}: {gcs_path}")
|
||||
|
||||
return CreateJobWithUploadUrlsResponse(
|
||||
status="success",
|
||||
job_id=job_id,
|
||||
message="Job created. Upload files to the provided URLs, then call /api/jobs/{job_id}/uploads-complete",
|
||||
upload_urls=upload_urls,
|
||||
server_version=VERSION
|
||||
)
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating job with upload URLs: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/uploads-complete")
|
||||
async def mark_uploads_complete(
|
||||
job_id: str,
|
||||
background_tasks: BackgroundTasks,
|
||||
body: UploadsCompleteRequest,
|
||||
):
|
||||
"""
|
||||
Mark file uploads as complete and start job processing.
|
||||
|
||||
This is the second step of the signed URL upload flow:
|
||||
1. Create job with POST /api/jobs/create-with-upload-urls
|
||||
2. Upload files directly to GCS using signed URLs
|
||||
3. Call this endpoint to validate uploads and start processing
|
||||
|
||||
The endpoint will:
|
||||
- Verify the job exists and is in PENDING state
|
||||
- Validate that required files (audio) were uploaded
|
||||
- Update job with GCS paths
|
||||
- Trigger audio and lyrics workers
|
||||
"""
|
||||
try:
|
||||
# Get job and verify it exists
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
# Verify job is in pending state
|
||||
if job.status != JobStatus.PENDING:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job {job_id} is not in pending state (current: {job.status}). Cannot complete uploads."
|
||||
)
|
||||
|
||||
# Validate required files
|
||||
if 'audio' not in body.uploaded_files:
|
||||
raise HTTPException(status_code=400, detail="Audio file upload is required")
|
||||
|
||||
# Build GCS paths for uploaded files and validate they exist
|
||||
update_data = {}
|
||||
style_assets = {}
|
||||
|
||||
for file_type in body.uploaded_files:
|
||||
if file_type not in VALID_FILE_TYPES:
|
||||
logger.warning(f"Unknown file_type in uploaded_files: {file_type}")
|
||||
continue
|
||||
|
||||
# Determine the GCS path - we need to find the actual file
|
||||
prefix = f"uploads/{job_id}/"
|
||||
if file_type == 'audio':
|
||||
prefix = f"uploads/{job_id}/audio/"
|
||||
elif file_type == 'style_params':
|
||||
prefix = f"uploads/{job_id}/style/style_params"
|
||||
elif file_type.startswith('style_'):
|
||||
asset_key = file_type.replace('style_', '')
|
||||
prefix = f"uploads/{job_id}/style/{asset_key}"
|
||||
elif file_type == 'lyrics_file':
|
||||
prefix = f"uploads/{job_id}/lyrics/user_lyrics"
|
||||
|
||||
# List files with this prefix to find the actual uploaded file
|
||||
files = storage_service.list_files(prefix)
|
||||
if not files:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"File for '{file_type}' was not uploaded to GCS. Expected prefix: {prefix}"
|
||||
)
|
||||
|
||||
# Use the first (and should be only) file found
|
||||
gcs_path = files[0]
|
||||
|
||||
# Update appropriate field based on file type
|
||||
if file_type == 'audio':
|
||||
update_data['input_media_gcs_path'] = gcs_path
|
||||
update_data['filename'] = Path(gcs_path).name
|
||||
elif file_type == 'style_params':
|
||||
update_data['style_params_gcs_path'] = gcs_path
|
||||
style_assets['style_params'] = gcs_path
|
||||
elif file_type.startswith('style_'):
|
||||
asset_key = file_type.replace('style_', '')
|
||||
style_assets[asset_key] = gcs_path
|
||||
elif file_type == 'lyrics_file':
|
||||
update_data['lyrics_file_gcs_path'] = gcs_path
|
||||
|
||||
# Add style assets to update if any
|
||||
if style_assets:
|
||||
update_data['style_assets'] = style_assets
|
||||
|
||||
# Update job with GCS paths
|
||||
job_manager.update_job(job_id, update_data)
|
||||
|
||||
logger.info(f"Validated uploads for job {job_id}: {body.uploaded_files}")
|
||||
|
||||
# Transition job to DOWNLOADING state
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING,
|
||||
progress=5,
|
||||
message="Files uploaded, preparing to process"
|
||||
)
|
||||
|
||||
# Trigger workers in parallel
|
||||
background_tasks.add_task(_trigger_workers_parallel, job_id)
|
||||
|
||||
# Get distribution services info for response
|
||||
credential_manager = get_credential_manager()
|
||||
distribution_services: Dict[str, Any] = {}
|
||||
|
||||
# Get fresh job data
|
||||
updated_job = job_manager.get_job(job_id)
|
||||
|
||||
if updated_job.dropbox_path:
|
||||
dropbox_result = credential_manager.check_dropbox_credentials()
|
||||
distribution_services["dropbox"] = {
|
||||
"enabled": True,
|
||||
"path": updated_job.dropbox_path,
|
||||
"credentials_valid": dropbox_result.status == CredentialStatus.VALID,
|
||||
}
|
||||
|
||||
if updated_job.gdrive_folder_id:
|
||||
gdrive_result = credential_manager.check_gdrive_credentials()
|
||||
distribution_services["gdrive"] = {
|
||||
"enabled": True,
|
||||
"folder_id": updated_job.gdrive_folder_id,
|
||||
"credentials_valid": gdrive_result.status == CredentialStatus.VALID,
|
||||
}
|
||||
|
||||
if updated_job.enable_youtube_upload:
|
||||
youtube_result = credential_manager.check_youtube_credentials()
|
||||
distribution_services["youtube"] = {
|
||||
"enabled": True,
|
||||
"credentials_valid": youtube_result.status == CredentialStatus.VALID,
|
||||
}
|
||||
|
||||
if updated_job.discord_webhook_url:
|
||||
distribution_services["discord"] = {
|
||||
"enabled": True,
|
||||
}
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"job_id": job_id,
|
||||
"message": "Uploads validated. Processing started.",
|
||||
"files_validated": body.uploaded_files,
|
||||
"style_assets": list(style_assets.keys()) if style_assets else [],
|
||||
"server_version": VERSION,
|
||||
"distribution_services": distribution_services,
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error completing uploads for job {job_id}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
@@ -217,6 +217,11 @@ class Job(BaseModel):
|
||||
lyrics_file_gcs_path: Optional[str] = None # GCS path to user-provided lyrics file
|
||||
subtitle_offset_ms: int = 0 # Offset for subtitle timing (positive = delay)
|
||||
|
||||
# Audio separation model configuration
|
||||
clean_instrumental_model: Optional[str] = None # Model for clean instrumental separation
|
||||
backing_vocals_models: Optional[List[str]] = None # Models for backing vocals separation
|
||||
other_stems_models: Optional[List[str]] = None # Models for other stems (bass, drums, etc.)
|
||||
|
||||
# Processing state
|
||||
track_output_dir: Optional[str] = None # Local output directory (temp)
|
||||
audio_hash: Optional[str] = None # Hash for deduplication
|
||||
@@ -385,6 +390,11 @@ class JobCreate(BaseModel):
|
||||
lyrics_file_gcs_path: Optional[str] = None # GCS path to user-provided lyrics file
|
||||
subtitle_offset_ms: int = 0 # Offset for subtitle timing (positive = delay)
|
||||
|
||||
# Audio separation model configuration
|
||||
clean_instrumental_model: Optional[str] = None # Model for clean instrumental separation
|
||||
backing_vocals_models: Optional[List[str]] = None # Models for backing vocals separation
|
||||
other_stems_models: Optional[List[str]] = None # Models for other stems (bass, drums, etc.)
|
||||
|
||||
# Request metadata (set by API endpoint from request headers)
|
||||
request_metadata: Dict[str, Any] = Field(default_factory=dict)
|
||||
"""
|
||||
|
||||
@@ -65,6 +65,26 @@ class StorageService:
|
||||
a private key available. Requires the service account to have
|
||||
roles/iam.serviceAccountTokenCreator on itself.
|
||||
"""
|
||||
return self._generate_signed_url_internal(blob_path, "GET", expiration_minutes)
|
||||
|
||||
def generate_signed_upload_url(self, blob_path: str, content_type: str = "application/octet-stream", expiration_minutes: int = 60) -> str:
|
||||
"""Generate a signed URL for uploading a file directly to GCS.
|
||||
|
||||
This allows clients to upload files directly to GCS without going through
|
||||
the backend, bypassing any request body size limits.
|
||||
|
||||
Args:
|
||||
blob_path: The destination path in GCS
|
||||
content_type: The expected content type of the upload
|
||||
expiration_minutes: How long the URL is valid for
|
||||
|
||||
Returns:
|
||||
A signed URL that accepts PUT requests with the file content
|
||||
"""
|
||||
return self._generate_signed_url_internal(blob_path, "PUT", expiration_minutes, content_type)
|
||||
|
||||
def _generate_signed_url_internal(self, blob_path: str, method: str, expiration_minutes: int = 60, content_type: Optional[str] = None) -> str:
|
||||
"""Internal method to generate signed URLs for GET or PUT operations."""
|
||||
import google.auth
|
||||
from google.auth.transport import requests
|
||||
|
||||
@@ -74,6 +94,17 @@ class StorageService:
|
||||
# Get default credentials and refresh to ensure we have a valid token
|
||||
credentials, project = google.auth.default()
|
||||
|
||||
# Common kwargs for signed URL generation
|
||||
kwargs = {
|
||||
"version": "v4",
|
||||
"expiration": timedelta(minutes=expiration_minutes),
|
||||
"method": method,
|
||||
}
|
||||
|
||||
# For PUT requests, we need to specify the content type in headers
|
||||
if method == "PUT" and content_type:
|
||||
kwargs["headers"] = {"Content-Type": content_type}
|
||||
|
||||
# Check if we're using compute credentials (Cloud Run/GCE)
|
||||
# These need to use IAM signBlob via service_account_email + access_token
|
||||
if hasattr(credentials, 'service_account_email'):
|
||||
@@ -81,25 +112,15 @@ class StorageService:
|
||||
auth_request = requests.Request()
|
||||
credentials.refresh(auth_request)
|
||||
|
||||
url = blob.generate_signed_url(
|
||||
version="v4",
|
||||
expiration=timedelta(minutes=expiration_minutes),
|
||||
method="GET",
|
||||
service_account_email=credentials.service_account_email,
|
||||
access_token=credentials.token
|
||||
)
|
||||
else:
|
||||
# Local development with service account key or user credentials
|
||||
url = blob.generate_signed_url(
|
||||
version="v4",
|
||||
expiration=timedelta(minutes=expiration_minutes),
|
||||
method="GET"
|
||||
)
|
||||
kwargs["service_account_email"] = credentials.service_account_email
|
||||
kwargs["access_token"] = credentials.token
|
||||
|
||||
logger.info(f"Generated signed URL for {blob_path}")
|
||||
url = blob.generate_signed_url(**kwargs)
|
||||
|
||||
logger.info(f"Generated signed {method} URL for {blob_path}")
|
||||
return url
|
||||
except Exception as e:
|
||||
logger.error(f"Error generating signed URL for {blob_path}: {e}")
|
||||
logger.error(f"Error generating signed {method} URL for {blob_path}: {e}")
|
||||
raise
|
||||
|
||||
def delete_file(self, blob_path: str) -> None:
|
||||
|
||||
@@ -427,6 +427,362 @@ class TestJobCreateLyricsFields:
|
||||
assert job_create.subtitle_offset_ms == 0
|
||||
|
||||
|
||||
class TestAudioModelConfigurationFields:
|
||||
"""Test that Job and JobCreate models support audio model configuration fields."""
|
||||
|
||||
def test_job_has_clean_instrumental_model_field(self):
|
||||
"""Test that Job model has clean_instrumental_model field."""
|
||||
from backend.models.job import Job
|
||||
from datetime import datetime
|
||||
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
clean_instrumental_model="custom_model.ckpt"
|
||||
)
|
||||
|
||||
assert hasattr(job, 'clean_instrumental_model')
|
||||
assert job.clean_instrumental_model == "custom_model.ckpt"
|
||||
|
||||
def test_job_has_backing_vocals_models_field(self):
|
||||
"""Test that Job model has backing_vocals_models field."""
|
||||
from backend.models.job import Job
|
||||
from datetime import datetime
|
||||
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
backing_vocals_models=["model1.ckpt", "model2.ckpt"]
|
||||
)
|
||||
|
||||
assert hasattr(job, 'backing_vocals_models')
|
||||
assert job.backing_vocals_models == ["model1.ckpt", "model2.ckpt"]
|
||||
|
||||
def test_job_has_other_stems_models_field(self):
|
||||
"""Test that Job model has other_stems_models field."""
|
||||
from backend.models.job import Job
|
||||
from datetime import datetime
|
||||
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
other_stems_models=["htdemucs_6s.yaml"]
|
||||
)
|
||||
|
||||
assert hasattr(job, 'other_stems_models')
|
||||
assert job.other_stems_models == ["htdemucs_6s.yaml"]
|
||||
|
||||
def test_audio_model_fields_are_optional(self):
|
||||
"""Test that audio model fields default to None."""
|
||||
from backend.models.job import Job
|
||||
from datetime import datetime
|
||||
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow()
|
||||
)
|
||||
|
||||
assert job.clean_instrumental_model is None
|
||||
assert job.backing_vocals_models is None
|
||||
assert job.other_stems_models is None
|
||||
|
||||
def test_job_create_has_audio_model_fields(self):
|
||||
"""Test that JobCreate model has all audio model configuration fields."""
|
||||
from backend.models.job import JobCreate
|
||||
|
||||
job_create = JobCreate(
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
clean_instrumental_model="custom_clean.ckpt",
|
||||
backing_vocals_models=["custom_bv.ckpt"],
|
||||
other_stems_models=["custom_stems.yaml"]
|
||||
)
|
||||
|
||||
assert job_create.clean_instrumental_model == "custom_clean.ckpt"
|
||||
assert job_create.backing_vocals_models == ["custom_bv.ckpt"]
|
||||
assert job_create.other_stems_models == ["custom_stems.yaml"]
|
||||
|
||||
def test_job_create_audio_model_fields_optional(self):
|
||||
"""Test that audio model fields are optional in JobCreate."""
|
||||
from backend.models.job import JobCreate
|
||||
|
||||
job_create = JobCreate(
|
||||
artist="Artist",
|
||||
title="Title"
|
||||
)
|
||||
|
||||
assert job_create.clean_instrumental_model is None
|
||||
assert job_create.backing_vocals_models is None
|
||||
assert job_create.other_stems_models is None
|
||||
|
||||
def test_pydantic_includes_audio_model_fields_in_serialization(self):
|
||||
"""Test that Pydantic includes audio model fields in serialization."""
|
||||
from backend.models.job import Job
|
||||
from datetime import datetime
|
||||
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
clean_instrumental_model="custom.ckpt",
|
||||
backing_vocals_models=["bv1.ckpt", "bv2.ckpt"],
|
||||
other_stems_models=["stems.yaml"]
|
||||
)
|
||||
|
||||
job_dict = job.model_dump()
|
||||
|
||||
assert "clean_instrumental_model" in job_dict
|
||||
assert job_dict["clean_instrumental_model"] == "custom.ckpt"
|
||||
assert "backing_vocals_models" in job_dict
|
||||
assert job_dict["backing_vocals_models"] == ["bv1.ckpt", "bv2.ckpt"]
|
||||
assert "other_stems_models" in job_dict
|
||||
assert job_dict["other_stems_models"] == ["stems.yaml"]
|
||||
|
||||
|
||||
class TestCommaDelimitedModelParsing:
|
||||
"""Test parsing of comma-delimited model strings."""
|
||||
|
||||
def test_parse_single_model(self):
|
||||
"""Test parsing a single model string."""
|
||||
model_str = "model1.ckpt"
|
||||
result = [m.strip() for m in model_str.split(',') if m.strip()]
|
||||
assert result == ["model1.ckpt"]
|
||||
|
||||
def test_parse_multiple_models(self):
|
||||
"""Test parsing multiple models."""
|
||||
model_str = "model1.ckpt,model2.ckpt,model3.ckpt"
|
||||
result = [m.strip() for m in model_str.split(',') if m.strip()]
|
||||
assert result == ["model1.ckpt", "model2.ckpt", "model3.ckpt"]
|
||||
|
||||
def test_parse_models_with_whitespace(self):
|
||||
"""Test parsing models with whitespace around commas."""
|
||||
model_str = "model1.ckpt , model2.ckpt, model3.ckpt "
|
||||
result = [m.strip() for m in model_str.split(',') if m.strip()]
|
||||
assert result == ["model1.ckpt", "model2.ckpt", "model3.ckpt"]
|
||||
|
||||
def test_parse_empty_string(self):
|
||||
"""Test parsing empty string."""
|
||||
model_str = ""
|
||||
result = [m.strip() for m in model_str.split(',') if m.strip()]
|
||||
assert result == []
|
||||
|
||||
def test_parse_none_returns_none(self):
|
||||
"""Test that None model string is handled correctly."""
|
||||
model_str = None
|
||||
result = None
|
||||
if model_str:
|
||||
result = [m.strip() for m in model_str.split(',') if m.strip()]
|
||||
assert result is None
|
||||
|
||||
|
||||
class TestSignedUrlUploadModels:
|
||||
"""Test Pydantic models for signed URL upload flow."""
|
||||
|
||||
def test_file_upload_request_model(self):
|
||||
"""Test FileUploadRequest model."""
|
||||
from backend.api.routes.file_upload import FileUploadRequest
|
||||
|
||||
file_req = FileUploadRequest(
|
||||
filename="test.flac",
|
||||
content_type="audio/flac",
|
||||
file_type="audio"
|
||||
)
|
||||
|
||||
assert file_req.filename == "test.flac"
|
||||
assert file_req.content_type == "audio/flac"
|
||||
assert file_req.file_type == "audio"
|
||||
|
||||
def test_create_job_with_upload_urls_request_model(self):
|
||||
"""Test CreateJobWithUploadUrlsRequest model."""
|
||||
from backend.api.routes.file_upload import CreateJobWithUploadUrlsRequest, FileUploadRequest
|
||||
|
||||
request = CreateJobWithUploadUrlsRequest(
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
files=[
|
||||
FileUploadRequest(filename="test.flac", content_type="audio/flac", file_type="audio")
|
||||
],
|
||||
enable_cdg=True,
|
||||
enable_txt=True,
|
||||
brand_prefix="NOMAD"
|
||||
)
|
||||
|
||||
assert request.artist == "Test Artist"
|
||||
assert request.title == "Test Song"
|
||||
assert len(request.files) == 1
|
||||
assert request.files[0].file_type == "audio"
|
||||
assert request.brand_prefix == "NOMAD"
|
||||
|
||||
def test_signed_upload_url_model(self):
|
||||
"""Test SignedUploadUrl model."""
|
||||
from backend.api.routes.file_upload import SignedUploadUrl
|
||||
|
||||
url_info = SignedUploadUrl(
|
||||
file_type="audio",
|
||||
gcs_path="uploads/test123/audio/test.flac",
|
||||
upload_url="https://storage.googleapis.com/signed-url",
|
||||
content_type="audio/flac"
|
||||
)
|
||||
|
||||
assert url_info.file_type == "audio"
|
||||
assert url_info.gcs_path == "uploads/test123/audio/test.flac"
|
||||
assert url_info.upload_url.startswith("https://")
|
||||
assert url_info.content_type == "audio/flac"
|
||||
|
||||
def test_uploads_complete_request_model(self):
|
||||
"""Test UploadsCompleteRequest model."""
|
||||
from backend.api.routes.file_upload import UploadsCompleteRequest
|
||||
|
||||
request = UploadsCompleteRequest(
|
||||
uploaded_files=["audio", "style_params", "style_intro_background"]
|
||||
)
|
||||
|
||||
assert len(request.uploaded_files) == 3
|
||||
assert "audio" in request.uploaded_files
|
||||
|
||||
|
||||
class TestValidFileTypes:
|
||||
"""Test file type validation for signed URL upload."""
|
||||
|
||||
def test_valid_file_types_includes_audio(self):
|
||||
"""Test that audio is a valid file type."""
|
||||
from backend.api.routes.file_upload import VALID_FILE_TYPES
|
||||
|
||||
assert 'audio' in VALID_FILE_TYPES
|
||||
assert '.flac' in VALID_FILE_TYPES['audio']
|
||||
assert '.mp3' in VALID_FILE_TYPES['audio']
|
||||
|
||||
def test_valid_file_types_includes_style_assets(self):
|
||||
"""Test that all style assets are valid file types."""
|
||||
from backend.api.routes.file_upload import VALID_FILE_TYPES
|
||||
|
||||
assert 'style_params' in VALID_FILE_TYPES
|
||||
assert 'style_intro_background' in VALID_FILE_TYPES
|
||||
assert 'style_karaoke_background' in VALID_FILE_TYPES
|
||||
assert 'style_end_background' in VALID_FILE_TYPES
|
||||
assert 'style_font' in VALID_FILE_TYPES
|
||||
assert 'style_cdg_instrumental_background' in VALID_FILE_TYPES
|
||||
assert 'style_cdg_title_background' in VALID_FILE_TYPES
|
||||
assert 'style_cdg_outro_background' in VALID_FILE_TYPES
|
||||
|
||||
def test_valid_file_types_includes_lyrics(self):
|
||||
"""Test that lyrics file is a valid file type."""
|
||||
from backend.api.routes.file_upload import VALID_FILE_TYPES
|
||||
|
||||
assert 'lyrics_file' in VALID_FILE_TYPES
|
||||
assert '.txt' in VALID_FILE_TYPES['lyrics_file']
|
||||
assert '.docx' in VALID_FILE_TYPES['lyrics_file']
|
||||
|
||||
|
||||
class TestSignedUrlGCSPathGeneration:
|
||||
"""Test GCS path generation for signed URL upload."""
|
||||
|
||||
def test_audio_gcs_path(self):
|
||||
"""Test GCS path generation for audio file."""
|
||||
from backend.api.routes.file_upload import _get_gcs_path_for_file
|
||||
|
||||
path = _get_gcs_path_for_file("test123", "audio", "song.flac")
|
||||
assert path == "uploads/test123/audio/song.flac"
|
||||
|
||||
def test_style_params_gcs_path(self):
|
||||
"""Test GCS path generation for style params."""
|
||||
from backend.api.routes.file_upload import _get_gcs_path_for_file
|
||||
|
||||
path = _get_gcs_path_for_file("test123", "style_params", "style.json")
|
||||
assert path == "uploads/test123/style/style_params.json"
|
||||
|
||||
def test_style_background_gcs_path(self):
|
||||
"""Test GCS path generation for style background images."""
|
||||
from backend.api.routes.file_upload import _get_gcs_path_for_file
|
||||
|
||||
path = _get_gcs_path_for_file("test123", "style_intro_background", "bg.png")
|
||||
assert path == "uploads/test123/style/intro_background.png"
|
||||
|
||||
def test_style_font_gcs_path(self):
|
||||
"""Test GCS path generation for font file."""
|
||||
from backend.api.routes.file_upload import _get_gcs_path_for_file
|
||||
|
||||
path = _get_gcs_path_for_file("test123", "style_font", "font.ttf")
|
||||
assert path == "uploads/test123/style/font.ttf"
|
||||
|
||||
def test_lyrics_file_gcs_path(self):
|
||||
"""Test GCS path generation for lyrics file."""
|
||||
from backend.api.routes.file_upload import _get_gcs_path_for_file
|
||||
|
||||
path = _get_gcs_path_for_file("test123", "lyrics_file", "lyrics.txt")
|
||||
assert path == "uploads/test123/lyrics/user_lyrics.txt"
|
||||
|
||||
|
||||
class TestStorageServiceSignedUrls:
|
||||
"""Test StorageService signed URL generation."""
|
||||
|
||||
def test_generate_signed_upload_url_method_exists(self):
|
||||
"""Test that generate_signed_upload_url method exists in StorageService."""
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
assert hasattr(StorageService, 'generate_signed_upload_url')
|
||||
|
||||
def test_generate_signed_url_internal_method_exists(self):
|
||||
"""Test that _generate_signed_url_internal method exists in StorageService."""
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
assert hasattr(StorageService, '_generate_signed_url_internal')
|
||||
|
||||
|
||||
class TestCreateJobWithUploadUrlsValidation:
|
||||
"""Test validation for create_job_with_upload_urls endpoint."""
|
||||
|
||||
def test_request_without_audio_is_invalid(self):
|
||||
"""Test that request without audio file is rejected."""
|
||||
from backend.api.routes.file_upload import CreateJobWithUploadUrlsRequest, FileUploadRequest
|
||||
import pytest
|
||||
|
||||
# This should be caught during endpoint validation
|
||||
# Here we test the model can be created but endpoint should reject
|
||||
request = CreateJobWithUploadUrlsRequest(
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
files=[
|
||||
FileUploadRequest(filename="style.json", content_type="application/json", file_type="style_params")
|
||||
]
|
||||
)
|
||||
|
||||
# Endpoint validation should catch this
|
||||
audio_files = [f for f in request.files if f.file_type == 'audio']
|
||||
assert len(audio_files) == 0 # No audio - should be rejected by endpoint
|
||||
|
||||
def test_request_with_multiple_audio_is_invalid(self):
|
||||
"""Test that request with multiple audio files is rejected."""
|
||||
from backend.api.routes.file_upload import CreateJobWithUploadUrlsRequest, FileUploadRequest
|
||||
|
||||
request = CreateJobWithUploadUrlsRequest(
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
files=[
|
||||
FileUploadRequest(filename="song1.flac", content_type="audio/flac", file_type="audio"),
|
||||
FileUploadRequest(filename="song2.flac", content_type="audio/flac", file_type="audio")
|
||||
]
|
||||
)
|
||||
|
||||
audio_files = [f for f in request.files if f.file_type == 'audio']
|
||||
assert len(audio_files) == 2 # Multiple audio - should be rejected by endpoint
|
||||
|
||||
def test_request_with_invalid_file_type(self):
|
||||
"""Test that request with invalid file type is rejected."""
|
||||
from backend.api.routes.file_upload import VALID_FILE_TYPES
|
||||
|
||||
assert 'invalid_type' not in VALID_FILE_TYPES
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pytest.main([__file__, "-v"])
|
||||
|
||||
@@ -573,3 +573,164 @@ class TestDownloadHelpers:
|
||||
# Should have downloaded from GCS
|
||||
mock_storage.download_file.assert_called()
|
||||
|
||||
|
||||
class TestAudioWorkerModelConfiguration:
|
||||
"""Tests for audio worker model configuration parameters."""
|
||||
|
||||
def test_create_audio_processor_with_defaults(self):
|
||||
"""Test creating AudioProcessor with default models."""
|
||||
with patch('backend.workers.audio_worker.AudioProcessor') as mock_processor:
|
||||
from backend.workers.audio_worker import create_audio_processor
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
result = create_audio_processor(temp_dir)
|
||||
|
||||
mock_processor.assert_called_once()
|
||||
call_kwargs = mock_processor.call_args[1]
|
||||
|
||||
# Should use default models
|
||||
assert call_kwargs['clean_instrumental_model'] == "model_bs_roformer_ep_317_sdr_12.9755.ckpt"
|
||||
assert call_kwargs['backing_vocals_models'] == ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"]
|
||||
assert call_kwargs['other_stems_models'] == ["htdemucs_6s.yaml"]
|
||||
|
||||
def test_create_audio_processor_with_custom_clean_model(self):
|
||||
"""Test creating AudioProcessor with custom clean instrumental model."""
|
||||
with patch('backend.workers.audio_worker.AudioProcessor') as mock_processor:
|
||||
from backend.workers.audio_worker import create_audio_processor
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
result = create_audio_processor(
|
||||
temp_dir,
|
||||
clean_instrumental_model="custom_clean_model.ckpt"
|
||||
)
|
||||
|
||||
mock_processor.assert_called_once()
|
||||
call_kwargs = mock_processor.call_args[1]
|
||||
|
||||
# Should use custom clean model
|
||||
assert call_kwargs['clean_instrumental_model'] == "custom_clean_model.ckpt"
|
||||
# Other models should still be defaults
|
||||
assert call_kwargs['backing_vocals_models'] == ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"]
|
||||
|
||||
def test_create_audio_processor_with_custom_backing_models(self):
|
||||
"""Test creating AudioProcessor with custom backing vocals models."""
|
||||
with patch('backend.workers.audio_worker.AudioProcessor') as mock_processor:
|
||||
from backend.workers.audio_worker import create_audio_processor
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
result = create_audio_processor(
|
||||
temp_dir,
|
||||
backing_vocals_models=["custom_bv1.ckpt", "custom_bv2.ckpt"]
|
||||
)
|
||||
|
||||
mock_processor.assert_called_once()
|
||||
call_kwargs = mock_processor.call_args[1]
|
||||
|
||||
# Should use custom backing vocals models
|
||||
assert call_kwargs['backing_vocals_models'] == ["custom_bv1.ckpt", "custom_bv2.ckpt"]
|
||||
|
||||
def test_create_audio_processor_with_custom_other_stems_models(self):
|
||||
"""Test creating AudioProcessor with custom other stems models."""
|
||||
with patch('backend.workers.audio_worker.AudioProcessor') as mock_processor:
|
||||
from backend.workers.audio_worker import create_audio_processor
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
result = create_audio_processor(
|
||||
temp_dir,
|
||||
other_stems_models=["custom_demucs.yaml"]
|
||||
)
|
||||
|
||||
mock_processor.assert_called_once()
|
||||
call_kwargs = mock_processor.call_args[1]
|
||||
|
||||
# Should use custom other stems models
|
||||
assert call_kwargs['other_stems_models'] == ["custom_demucs.yaml"]
|
||||
|
||||
def test_create_audio_processor_with_all_custom_models(self):
|
||||
"""Test creating AudioProcessor with all custom models."""
|
||||
with patch('backend.workers.audio_worker.AudioProcessor') as mock_processor:
|
||||
from backend.workers.audio_worker import create_audio_processor
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
result = create_audio_processor(
|
||||
temp_dir,
|
||||
clean_instrumental_model="custom_clean.ckpt",
|
||||
backing_vocals_models=["custom_bv.ckpt"],
|
||||
other_stems_models=["custom_stems.yaml"]
|
||||
)
|
||||
|
||||
mock_processor.assert_called_once()
|
||||
call_kwargs = mock_processor.call_args[1]
|
||||
|
||||
# All models should be custom
|
||||
assert call_kwargs['clean_instrumental_model'] == "custom_clean.ckpt"
|
||||
assert call_kwargs['backing_vocals_models'] == ["custom_bv.ckpt"]
|
||||
assert call_kwargs['other_stems_models'] == ["custom_stems.yaml"]
|
||||
|
||||
def test_job_model_fields_are_passed_to_processor(self):
|
||||
"""Test that job model fields can be passed to create_audio_processor."""
|
||||
mock_job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Test",
|
||||
clean_instrumental_model="job_clean.ckpt",
|
||||
backing_vocals_models=["job_bv.ckpt"],
|
||||
other_stems_models=["job_stems.yaml"]
|
||||
)
|
||||
|
||||
with patch('backend.workers.audio_worker.AudioProcessor') as mock_processor:
|
||||
from backend.workers.audio_worker import create_audio_processor
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# Simulate passing job model fields to create_audio_processor
|
||||
result = create_audio_processor(
|
||||
temp_dir,
|
||||
clean_instrumental_model=mock_job.clean_instrumental_model,
|
||||
backing_vocals_models=mock_job.backing_vocals_models,
|
||||
other_stems_models=mock_job.other_stems_models
|
||||
)
|
||||
|
||||
mock_processor.assert_called_once()
|
||||
call_kwargs = mock_processor.call_args[1]
|
||||
|
||||
# Models from job should be used
|
||||
assert call_kwargs['clean_instrumental_model'] == "job_clean.ckpt"
|
||||
assert call_kwargs['backing_vocals_models'] == ["job_bv.ckpt"]
|
||||
assert call_kwargs['other_stems_models'] == ["job_stems.yaml"]
|
||||
|
||||
def test_none_model_values_use_defaults(self):
|
||||
"""Test that None model values fall back to defaults."""
|
||||
mock_job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Test",
|
||||
clean_instrumental_model=None, # Not specified
|
||||
backing_vocals_models=None, # Not specified
|
||||
other_stems_models=None # Not specified
|
||||
)
|
||||
|
||||
with patch('backend.workers.audio_worker.AudioProcessor') as mock_processor:
|
||||
from backend.workers.audio_worker import create_audio_processor
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
result = create_audio_processor(
|
||||
temp_dir,
|
||||
clean_instrumental_model=mock_job.clean_instrumental_model,
|
||||
backing_vocals_models=mock_job.backing_vocals_models,
|
||||
other_stems_models=mock_job.other_stems_models
|
||||
)
|
||||
|
||||
mock_processor.assert_called_once()
|
||||
call_kwargs = mock_processor.call_args[1]
|
||||
|
||||
# Should fall back to defaults
|
||||
assert call_kwargs['clean_instrumental_model'] == "model_bs_roformer_ep_317_sdr_12.9755.ckpt"
|
||||
assert call_kwargs['backing_vocals_models'] == ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"]
|
||||
assert call_kwargs['other_stems_models'] == ["htdemucs_6s.yaml"]
|
||||
|
||||
@@ -112,7 +112,12 @@ async def download_from_url(url: str, temp_dir: str, artist: str, title: str) ->
|
||||
return None
|
||||
|
||||
|
||||
def create_audio_processor(temp_dir: str) -> AudioProcessor:
|
||||
def create_audio_processor(
|
||||
temp_dir: str,
|
||||
clean_instrumental_model: Optional[str] = None,
|
||||
backing_vocals_models: Optional[list] = None,
|
||||
other_stems_models: Optional[list] = None
|
||||
) -> AudioProcessor:
|
||||
"""
|
||||
Create an AudioProcessor instance configured for remote API processing.
|
||||
|
||||
@@ -120,10 +125,13 @@ def create_audio_processor(temp_dir: str) -> AudioProcessor:
|
||||
- Uses remote Modal API (via AUDIO_SEPARATOR_API_URL env var)
|
||||
- No local models needed (model_file_dir=None)
|
||||
- FLAC output format for quality
|
||||
- Standard model configurations from karaoke-gen CLI
|
||||
- Model configurations from job or CLI defaults
|
||||
|
||||
Args:
|
||||
temp_dir: Temporary directory for processing
|
||||
clean_instrumental_model: Model for clean instrumental separation (optional, uses default if not provided)
|
||||
backing_vocals_models: List of models for backing vocals separation (optional, uses default if not provided)
|
||||
other_stems_models: List of models for other stems separation (optional, uses default if not provided)
|
||||
|
||||
Returns:
|
||||
Configured AudioProcessor instance
|
||||
@@ -132,10 +140,10 @@ def create_audio_processor(temp_dir: str) -> AudioProcessor:
|
||||
audio_logger = logging.getLogger("karaoke_gen.audio_processor")
|
||||
audio_logger.setLevel(logging.INFO)
|
||||
|
||||
# Model configurations (same as CLI defaults)
|
||||
clean_instrumental_model = "model_bs_roformer_ep_317_sdr_12.9755.ckpt"
|
||||
backing_vocals_models = ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"]
|
||||
other_stems_models = ["htdemucs_6s.yaml"] # For 6-stem separation (bass, drums, etc.)
|
||||
# Model configurations - use provided values or CLI defaults
|
||||
effective_clean_model = clean_instrumental_model or "model_bs_roformer_ep_317_sdr_12.9755.ckpt"
|
||||
effective_backing_models = backing_vocals_models or ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"]
|
||||
effective_other_models = other_stems_models or ["htdemucs_6s.yaml"] # For 6-stem separation (bass, drums, etc.)
|
||||
|
||||
# FFmpeg command for combining audio files (must be a string, not a list)
|
||||
ffmpeg_base_command = "ffmpeg -hide_banner -loglevel error -nostats -y"
|
||||
@@ -146,9 +154,9 @@ def create_audio_processor(temp_dir: str) -> AudioProcessor:
|
||||
log_formatter=None, # Not needed for our use case
|
||||
model_file_dir=None, # No local models, using remote API
|
||||
lossless_output_format="FLAC",
|
||||
clean_instrumental_model=clean_instrumental_model,
|
||||
backing_vocals_models=backing_vocals_models,
|
||||
other_stems_models=other_stems_models,
|
||||
clean_instrumental_model=effective_clean_model,
|
||||
backing_vocals_models=effective_backing_models,
|
||||
other_stems_models=effective_other_models,
|
||||
ffmpeg_base_command=ffmpeg_base_command
|
||||
)
|
||||
|
||||
@@ -226,8 +234,21 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
})
|
||||
|
||||
# Create AudioProcessor instance (reuses karaoke_gen code)
|
||||
# Use model configuration from job if provided, otherwise use defaults
|
||||
job_log.info("Creating AudioProcessor instance...")
|
||||
audio_processor = create_audio_processor(temp_dir)
|
||||
if job.clean_instrumental_model:
|
||||
job_log.info(f" Using clean instrumental model: {job.clean_instrumental_model}")
|
||||
if job.backing_vocals_models:
|
||||
job_log.info(f" Using backing vocals models: {job.backing_vocals_models}")
|
||||
if job.other_stems_models:
|
||||
job_log.info(f" Using other stems models: {job.other_stems_models}")
|
||||
|
||||
audio_processor = create_audio_processor(
|
||||
temp_dir,
|
||||
clean_instrumental_model=job.clean_instrumental_model,
|
||||
backing_vocals_models=job.backing_vocals_models,
|
||||
other_stems_models=job.other_stems_models
|
||||
)
|
||||
|
||||
# Format artist-title for file naming (matches CLI behavior)
|
||||
artist_title = f"{job.artist} - {job.title}"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Backend Feature Parity Plan
|
||||
|
||||
**Last Updated:** 2024-12-10
|
||||
**Status:** ✅ Core Feature Parity Achieved (v0.71.0) | Batch 1 Complete ✅
|
||||
**Last Updated:** 2024-12-11
|
||||
**Status:** ✅ Core Feature Parity Achieved (v0.71.0) | Batch 1 ✅ | Batch 2 ✅
|
||||
|
||||
This document tracks the progress toward complete feature parity between the local `karaoke-gen` CLI and the cloud backend, enabling the `karaoke-gen-remote` CLI to have equivalent functionality.
|
||||
|
||||
@@ -14,7 +14,7 @@ This document tracks the progress toward complete feature parity between the loc
|
||||
| Lyrics Configuration | 5 | 5 | **100%** | ✅ **Batch 1 Complete** (L1-L4) |
|
||||
| Style Configuration | 1 | 4 | **25%** | S2-S4 are MEDIUM priority |
|
||||
| Workflow Control | 0 | 3 | **0%** | W1/W2 HIGH, W7 MEDIUM (skip flags deferred) |
|
||||
| Audio Processing | 0 | 4 | **0%** | AP1-3, AP5 are HIGH priority |
|
||||
| Audio Processing | 3 | 4 | **75%** | ✅ **Batch 2 Complete** (AP1-AP3), AP5 remaining |
|
||||
| Input Modes | 1 | 3 | **33%** | P2, P3 are HIGH priority |
|
||||
| Audio Fetching | 0 | 1 | **0%** | A1 is HIGH priority |
|
||||
| Flags to Remove | - | - | - | I3-I6, AP6 (simplify codebase) |
|
||||
@@ -162,17 +162,19 @@ This section provides a comprehensive comparison of all CLI parameters between `
|
||||
|
||||
| # | Parameter | Local | Remote | Description |
|
||||
|---|-----------|-------|--------|-------------|
|
||||
| AP1 | `--clean_instrumental_model` | ✅ | ❌ | **Stage 1 separation model.** AI model for initial vocal/instrumental separation. Default: `model_bs_roformer_ep_317_sdr_12.9755.ckpt`. Different models have different quality/speed tradeoffs. |
|
||||
| AP2 | `--backing_vocals_models` | ✅ | ❌ | **Stage 2 separation model(s).** AI model(s) for separating lead vocals from backing vocals. Default: `mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt`. |
|
||||
| AP3 | `--other_stems_models` | ✅ | ❌ | **Multi-stem separation model.** AI model for separating drums, bass, guitar, piano, other. Default: `htdemucs_6s.yaml`. |
|
||||
| AP1 | `--clean_instrumental_model` | ✅ | ✅ | **Stage 1 separation model.** AI model for initial vocal/instrumental separation. Default: `model_bs_roformer_ep_317_sdr_12.9755.ckpt`. Different models have different quality/speed tradeoffs. |
|
||||
| AP2 | `--backing_vocals_models` | ✅ | ✅ | **Stage 2 separation model(s).** AI model(s) for separating lead vocals from backing vocals. Default: `mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt`. |
|
||||
| AP3 | `--other_stems_models` | ✅ | ✅ | **Multi-stem separation model.** AI model for separating drums, bass, guitar, piano, other. Default: `htdemucs_6s.yaml`. |
|
||||
| AP4 | `--model_file_dir` | ✅ | N/A | **Model cache directory.** Where to store/load AI model files. Default: `/tmp/audio-separator-models/`. |
|
||||
| AP5 | `--existing_instrumental` | ✅ | ❌ | **Use pre-made instrumental.** Path to an existing instrumental file to use instead of running AI separation. Useful when you have a better instrumental from another source (official instrumental release, manual editing, etc.). Skips audio separation entirely. |
|
||||
| AP6 | `--instrumental_format` | 🗑️ | N/A | **REMOVE FROM LOCAL CLI.** FLAC is always fine, no need for format option. |
|
||||
|
||||
**Remote Implementation Plan:**
|
||||
- **AP1-AP3 Model selection**: HIGH PRIORITY. All model options must work remotely! The Modal-hosted audio-separator API can download any model on demand and caches them. Just pass model name to API. Use case: A/B testing models, using newer models as they release.
|
||||
**Remote Implementation Status:** ✅ **BATCH 2 COMPLETE** (PR #9, v0.71.24)
|
||||
- **AP1 `--clean_instrumental_model`**: ✅ IMPLEMENTED. Sent as form field to backend. Audio worker passes to Modal API.
|
||||
- **AP2 `--backing_vocals_models`**: ✅ IMPLEMENTED. Sent as comma-separated list, parsed and passed to Modal API.
|
||||
- **AP3 `--other_stems_models`**: ✅ IMPLEMENTED. Sent as comma-separated list, parsed and passed to Modal API.
|
||||
- **AP4 `--model_file_dir`**: N/A for remote - Modal API handles model caching internally.
|
||||
- **AP5 `--existing_instrumental`**: HIGH PRIORITY. User uploads instrumental file with job. Backend STILL runs separation (for consistent stem outputs in download folder), but uses provided instrumental for karaoke remux and final video. **VALIDATION REQUIRED**: At job start, validate provided instrumental duration matches input audio duration (within 0.5 seconds tolerance) to ensure sync before proceeding.
|
||||
- **AP5 `--existing_instrumental`**: HIGH PRIORITY (Batch 3). User uploads instrumental file with job. Backend STILL runs separation (for consistent stem outputs in download folder), but uses provided instrumental for karaoke remux and final video. **VALIDATION REQUIRED**: At job start, validate provided instrumental duration matches input audio duration (within 0.5 seconds tolerance) to ensure sync before proceeding.
|
||||
- **AP6**: REMOVE from local CLI - FLAC is always fine.
|
||||
|
||||
---
|
||||
@@ -320,19 +322,24 @@ Bump the patch version in `pyproject.toml` before committing.
|
||||
|
||||
---
|
||||
|
||||
### Batch 2: Audio Separation Model Selection (HIGH)
|
||||
### Batch 2: Audio Separation Model Selection (HIGH) ✅ COMPLETE
|
||||
**Parameters:** AP1 `--clean_instrumental_model`, AP2 `--backing_vocals_models`, AP3 `--other_stems_models`
|
||||
|
||||
**Scope:**
|
||||
- Remote CLI: Add 3 form fields to `submit_job()`
|
||||
- Backend: Add 3 Form parameters to upload endpoint
|
||||
- Backend: Store in job, pass to audio worker
|
||||
- Backend: Audio worker passes model names to Modal API (already supports any model)
|
||||
**Status:** ✅ **IMPLEMENTED** - PR #9 merged (v0.71.24)
|
||||
|
||||
**Files to modify:**
|
||||
- `karaoke_gen/utils/remote_cli.py` - add to submit_job()
|
||||
- `backend/api/routes/file_upload.py` - add Form fields
|
||||
- `backend/workers/audio_worker.py` - pass model names to Modal API
|
||||
**Implementation Summary:**
|
||||
- Remote CLI: Added 3 form fields to `submit_job()`, sends models as comma-separated strings
|
||||
- Backend: Added 3 Form parameters to `/api/jobs/upload` endpoint, parses comma-separated lists
|
||||
- Backend: Job model stores model configuration as optional fields
|
||||
- Backend: Audio worker passes model names to AudioProcessor which uses Modal API
|
||||
|
||||
**Files modified:**
|
||||
- `karaoke_gen/utils/remote_cli.py` - submit_job() with model params
|
||||
- `backend/api/routes/file_upload.py` - Form fields + comma parsing
|
||||
- `backend/models/job.py` - clean_instrumental_model, backing_vocals_models, other_stems_models fields
|
||||
- `backend/workers/audio_worker.py` - create_audio_processor() accepts model params from job
|
||||
|
||||
**Tests added:** 15+ unit tests covering Job model fields, form parsing, AudioProcessor configuration
|
||||
|
||||
**Complexity:** Low (Modal API already supports dynamic model selection)
|
||||
|
||||
@@ -496,7 +503,7 @@ Bump the patch version in `pyproject.toml` before committing.
|
||||
| Batch | Parameters | Priority | Complexity | Status |
|
||||
|-------|------------|----------|------------|--------|
|
||||
| 1 | L1-L4 (lyrics config) | HIGH | Low-Medium | ✅ **COMPLETE** (PR #8) |
|
||||
| 2 | AP1-AP3 (model selection) | HIGH | Low | ⏳ Pending |
|
||||
| 2 | AP1-AP3 (model selection) | HIGH | Low | ✅ **COMPLETE** (PR #9) |
|
||||
| 3 | AP5 (existing instrumental) | HIGH | Medium | ⏳ Pending |
|
||||
| 4 | P2 (YouTube URLs) | HIGH | Medium-High | ⏳ Pending |
|
||||
| 5 | P3, A1 (flacfetch search) | HIGH | High | ⏳ Pending |
|
||||
@@ -506,7 +513,7 @@ Bump the patch version in `pyproject.toml` before committing.
|
||||
| 9 | W7 (edit-lyrics) | MEDIUM | Medium-High | ⏳ Pending |
|
||||
| 10 | F14, D2, D3, removals | LOW | Mixed | ⏳ Pending |
|
||||
|
||||
**Recommended Order:** ~~1~~ → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 9 → 10
|
||||
**Recommended Order:** ~~1~~ → ~~2~~ → 3 → 4 → 5 → 6 → 7 → 8 → 9 → 10
|
||||
|
||||
Batches 1-3 are quick wins that add significant value. Batches 4-6 are larger but high priority. Batches 7-10 can be done as time permits.
|
||||
|
||||
@@ -615,13 +622,13 @@ The karaoke-gen system supports multiple interfaces to the same core functionali
|
||||
|
||||
| Feature | Version | PR | Notes |
|
||||
|---------|---------|-----|-------|
|
||||
|| Audio model selection | v0.71.24 | #9 | `--clean_instrumental_model`, `--backing_vocals_models`, `--other_stems_models` |
|
||||
| Lyrics override params | v0.71.22 | #8 | `--lyrics_artist`, `--lyrics_title`, `--lyrics_file`, `--subtitle_offset_ms` |
|
||||
|
||||
### ⏳ Not Yet Implemented
|
||||
|
||||
| Feature | Priority | Notes |
|
||||
|---------|----------|-------|
|
||||
| Audio model selection | HIGH | `--clean_instrumental_model`, `--backing_vocals_models`, `--other_stems_models` |
|
||||
| Existing instrumental | HIGH | `--existing_instrumental` for re-processing |
|
||||
| Style override | MEDIUM | `--style_override` for quick tweaks |
|
||||
| Skip separation/transcription | MEDIUM | Workflow control for re-processing |
|
||||
@@ -874,6 +881,16 @@ DEFAULT_DISCORD_WEBHOOK_URL=https://discord.com/...
|
||||
|
||||
## Recent Changes Log
|
||||
|
||||
### 2024-12-11: v0.71.24 - Batch 2 Complete (Audio Model Selection)
|
||||
|
||||
**PR #9: Audio Model Selection for Remote CLI**
|
||||
|
||||
- ✅ `--clean_instrumental_model` - Custom Stage 1 separation model
|
||||
- ✅ `--backing_vocals_models` - Custom backing vocals separation models
|
||||
- ✅ `--other_stems_models` - Custom multi-stem separation models (bass, drums, etc.)
|
||||
- Added 15+ unit tests for new functionality
|
||||
- Files: `remote_cli.py`, `file_upload.py`, `job.py`, `audio_worker.py`
|
||||
|
||||
### 2024-12-10: v0.71.22 - Batch 1 Complete (Lyrics Configuration)
|
||||
|
||||
**PR #8: Lyrics Configuration for Remote CLI**
|
||||
@@ -936,12 +953,11 @@ DEFAULT_DISCORD_WEBHOOK_URL=https://discord.com/...
|
||||
- `--lyrics_artist`, `--lyrics_title`, `--lyrics_file`, `--subtitle_offset_ms`
|
||||
- PR #8, v0.71.22
|
||||
|
||||
2. **Audio Model Selection** (Batch 2 - NEXT)
|
||||
- Add `--clean_instrumental_model`, `--backing_vocals_models`, `--other_stems_models` support
|
||||
- Files: `remote_cli.py`, `file_upload.py`, `audio_worker.py`
|
||||
- Enables: A/B testing models, using newer models as they release
|
||||
2. ✅ **Audio Model Selection** (Batch 2 - COMPLETE)
|
||||
- `--clean_instrumental_model`, `--backing_vocals_models`, `--other_stems_models`
|
||||
- PR #9, v0.71.24
|
||||
|
||||
3. **Existing Instrumental** (Batch 3)
|
||||
3. **Existing Instrumental** (Batch 3 - NEXT)
|
||||
- Add `--existing_instrumental` upload support
|
||||
- Files: `remote_cli.py`, `file_upload.py`, `audio_worker.py`, `render_worker.py`
|
||||
- Enables: Re-processing with better instrumentals
|
||||
|
||||
+226
-92
@@ -143,6 +143,70 @@ class RemoteKaraokeClient:
|
||||
response = self.session.request(method, url, **kwargs)
|
||||
return response
|
||||
|
||||
def _upload_file_to_signed_url(self, signed_url: str, file_path: str, content_type: str) -> bool:
|
||||
"""
|
||||
Upload a file directly to GCS using a signed URL.
|
||||
|
||||
Args:
|
||||
signed_url: The signed URL from the backend
|
||||
file_path: Local path to the file to upload
|
||||
content_type: MIME type for the Content-Type header
|
||||
|
||||
Returns:
|
||||
True if upload succeeded, False otherwise
|
||||
"""
|
||||
try:
|
||||
with open(file_path, 'rb') as f:
|
||||
# Use a fresh requests session (not self.session) because
|
||||
# signed URLs should not have our auth headers
|
||||
response = requests.put(
|
||||
signed_url,
|
||||
data=f,
|
||||
headers={'Content-Type': content_type},
|
||||
timeout=600 # 10 minutes for large files
|
||||
)
|
||||
|
||||
if response.status_code in (200, 201):
|
||||
return True
|
||||
else:
|
||||
self.logger.error(f"Failed to upload to signed URL: HTTP {response.status_code} - {response.text}")
|
||||
return False
|
||||
except Exception as e:
|
||||
self.logger.error(f"Error uploading to signed URL: {e}")
|
||||
return False
|
||||
|
||||
def _get_content_type(self, file_path: str) -> str:
|
||||
"""Get the MIME content type for a file based on its extension."""
|
||||
ext = Path(file_path).suffix.lower()
|
||||
|
||||
content_types = {
|
||||
# Audio
|
||||
'.mp3': 'audio/mpeg',
|
||||
'.wav': 'audio/wav',
|
||||
'.flac': 'audio/flac',
|
||||
'.m4a': 'audio/mp4',
|
||||
'.ogg': 'audio/ogg',
|
||||
'.aac': 'audio/aac',
|
||||
# Images
|
||||
'.png': 'image/png',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.gif': 'image/gif',
|
||||
'.webp': 'image/webp',
|
||||
# Fonts
|
||||
'.ttf': 'font/ttf',
|
||||
'.otf': 'font/otf',
|
||||
'.woff': 'font/woff',
|
||||
'.woff2': 'font/woff2',
|
||||
# Other
|
||||
'.json': 'application/json',
|
||||
'.txt': 'text/plain',
|
||||
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'.rtf': 'application/rtf',
|
||||
}
|
||||
|
||||
return content_types.get(ext, 'application/octet-stream')
|
||||
|
||||
def _parse_style_params(self, style_params_path: str) -> Dict[str, str]:
|
||||
"""
|
||||
Parse style_params.json and extract file paths that need to be uploaded.
|
||||
@@ -204,10 +268,19 @@ class RemoteKaraokeClient:
|
||||
lyrics_title: Optional[str] = None,
|
||||
lyrics_file: Optional[str] = None,
|
||||
subtitle_offset_ms: int = 0,
|
||||
# Audio separation model configuration
|
||||
clean_instrumental_model: Optional[str] = None,
|
||||
backing_vocals_models: Optional[list] = None,
|
||||
other_stems_models: Optional[list] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Submit a new karaoke generation job with optional style configuration.
|
||||
|
||||
Uses signed URL upload flow to bypass Cloud Run's 32MB request body limit:
|
||||
1. Create job and get signed upload URLs from backend
|
||||
2. Upload files directly to GCS using signed URLs
|
||||
3. Notify backend that uploads are complete to start processing
|
||||
|
||||
Args:
|
||||
filepath: Path to audio file
|
||||
artist: Artist name
|
||||
@@ -226,6 +299,9 @@ class RemoteKaraokeClient:
|
||||
lyrics_title: Override title for lyrics search
|
||||
lyrics_file: Path to user-provided lyrics file
|
||||
subtitle_offset_ms: Subtitle timing offset in milliseconds
|
||||
clean_instrumental_model: Model for clean instrumental separation
|
||||
backing_vocals_models: List of models for backing vocals separation
|
||||
other_stems_models: List of models for other stems (bass, drums, etc.)
|
||||
"""
|
||||
file_path = Path(filepath)
|
||||
|
||||
@@ -239,110 +315,157 @@ class RemoteKaraokeClient:
|
||||
f"Allowed: {', '.join(self.ALLOWED_AUDIO_EXTENSIONS)}"
|
||||
)
|
||||
|
||||
self.logger.info(f"Uploading audio file: {filepath}")
|
||||
# Step 1: Build list of files to upload
|
||||
files_info = []
|
||||
local_files = {} # file_type -> local_path
|
||||
|
||||
# Prepare files dict for multipart upload
|
||||
files_to_upload = {}
|
||||
files_to_close = []
|
||||
# Main audio file
|
||||
audio_content_type = self._get_content_type(filepath)
|
||||
files_info.append({
|
||||
'filename': file_path.name,
|
||||
'content_type': audio_content_type,
|
||||
'file_type': 'audio'
|
||||
})
|
||||
local_files['audio'] = filepath
|
||||
self.logger.info(f"Will upload audio: {filepath}")
|
||||
|
||||
try:
|
||||
# Main audio file
|
||||
audio_file = open(filepath, 'rb')
|
||||
files_to_close.append(audio_file)
|
||||
files_to_upload['file'] = (file_path.name, audio_file)
|
||||
# Parse style params and find referenced files
|
||||
style_assets = {}
|
||||
if style_params_path and os.path.isfile(style_params_path):
|
||||
self.logger.info(f"Parsing style configuration: {style_params_path}")
|
||||
style_assets = self._parse_style_params(style_params_path)
|
||||
|
||||
# Parse style params and find referenced files
|
||||
style_assets = {}
|
||||
if style_params_path and os.path.isfile(style_params_path):
|
||||
self.logger.info(f"Parsing style configuration: {style_params_path}")
|
||||
style_assets = self._parse_style_params(style_params_path)
|
||||
|
||||
# Upload style_params.json
|
||||
style_file = open(style_params_path, 'rb')
|
||||
files_to_close.append(style_file)
|
||||
files_to_upload['style_params'] = (Path(style_params_path).name, style_file, 'application/json')
|
||||
self.logger.info(f" Will upload style_params.json")
|
||||
|
||||
# Upload each style asset file
|
||||
for asset_key, asset_path in style_assets.items():
|
||||
if os.path.isfile(asset_path):
|
||||
asset_file = open(asset_path, 'rb')
|
||||
files_to_close.append(asset_file)
|
||||
# Determine content type
|
||||
ext = Path(asset_path).suffix.lower()
|
||||
if ext in self.ALLOWED_IMAGE_EXTENSIONS:
|
||||
content_type = f'image/{ext[1:]}'
|
||||
elif ext in self.ALLOWED_FONT_EXTENSIONS:
|
||||
content_type = 'font/ttf'
|
||||
else:
|
||||
content_type = 'application/octet-stream'
|
||||
files_to_upload[asset_key] = (Path(asset_path).name, asset_file, content_type)
|
||||
self.logger.info(f" Will upload {asset_key}: {asset_path}")
|
||||
|
||||
# Upload lyrics file if provided
|
||||
if lyrics_file and os.path.isfile(lyrics_file):
|
||||
self.logger.info(f"Uploading lyrics file: {lyrics_file}")
|
||||
lyrics_file_handle = open(lyrics_file, 'rb')
|
||||
files_to_close.append(lyrics_file_handle)
|
||||
files_to_upload['lyrics_file'] = (Path(lyrics_file).name, lyrics_file_handle, 'text/plain')
|
||||
|
||||
# Prepare form data
|
||||
data = {
|
||||
'artist': artist,
|
||||
'title': title,
|
||||
'enable_cdg': str(enable_cdg).lower(),
|
||||
'enable_txt': str(enable_txt).lower(),
|
||||
}
|
||||
|
||||
if brand_prefix:
|
||||
data['brand_prefix'] = brand_prefix
|
||||
if discord_webhook_url:
|
||||
data['discord_webhook_url'] = discord_webhook_url
|
||||
if youtube_description:
|
||||
data['youtube_description'] = youtube_description
|
||||
if enable_youtube_upload:
|
||||
data['enable_youtube_upload'] = str(enable_youtube_upload).lower()
|
||||
|
||||
# Native API distribution (preferred for remote CLI)
|
||||
if dropbox_path:
|
||||
data['dropbox_path'] = dropbox_path
|
||||
if gdrive_folder_id:
|
||||
data['gdrive_folder_id'] = gdrive_folder_id
|
||||
|
||||
# Legacy rclone distribution (deprecated)
|
||||
if organised_dir_rclone_root:
|
||||
data['organised_dir_rclone_root'] = organised_dir_rclone_root
|
||||
|
||||
# Lyrics configuration
|
||||
if lyrics_artist:
|
||||
data['lyrics_artist'] = lyrics_artist
|
||||
if lyrics_title:
|
||||
data['lyrics_title'] = lyrics_title
|
||||
if subtitle_offset_ms != 0:
|
||||
data['subtitle_offset_ms'] = str(subtitle_offset_ms)
|
||||
|
||||
self.logger.info(f"Submitting job to {self.config.service_url}/api/jobs/upload")
|
||||
|
||||
response = self._request('POST', '/api/jobs/upload', files=files_to_upload, data=data)
|
||||
|
||||
finally:
|
||||
# Close all opened files
|
||||
for f in files_to_close:
|
||||
try:
|
||||
f.close()
|
||||
except:
|
||||
pass
|
||||
# Add style_params.json
|
||||
files_info.append({
|
||||
'filename': Path(style_params_path).name,
|
||||
'content_type': 'application/json',
|
||||
'file_type': 'style_params'
|
||||
})
|
||||
local_files['style_params'] = style_params_path
|
||||
self.logger.info(f" Will upload style_params.json")
|
||||
|
||||
# Add each style asset file
|
||||
for asset_key, asset_path in style_assets.items():
|
||||
if os.path.isfile(asset_path):
|
||||
content_type = self._get_content_type(asset_path)
|
||||
files_info.append({
|
||||
'filename': Path(asset_path).name,
|
||||
'content_type': content_type,
|
||||
'file_type': asset_key # e.g., 'style_intro_background'
|
||||
})
|
||||
local_files[asset_key] = asset_path
|
||||
self.logger.info(f" Will upload {asset_key}: {asset_path}")
|
||||
|
||||
# Add lyrics file if provided
|
||||
if lyrics_file and os.path.isfile(lyrics_file):
|
||||
content_type = self._get_content_type(lyrics_file)
|
||||
files_info.append({
|
||||
'filename': Path(lyrics_file).name,
|
||||
'content_type': content_type,
|
||||
'file_type': 'lyrics_file'
|
||||
})
|
||||
local_files['lyrics_file'] = lyrics_file
|
||||
self.logger.info(f"Will upload lyrics file: {lyrics_file}")
|
||||
|
||||
# Step 2: Create job and get signed upload URLs
|
||||
self.logger.info(f"Creating job at {self.config.service_url}/api/jobs/create-with-upload-urls")
|
||||
|
||||
create_request = {
|
||||
'artist': artist,
|
||||
'title': title,
|
||||
'files': files_info,
|
||||
'enable_cdg': enable_cdg,
|
||||
'enable_txt': enable_txt,
|
||||
}
|
||||
|
||||
if brand_prefix:
|
||||
create_request['brand_prefix'] = brand_prefix
|
||||
if discord_webhook_url:
|
||||
create_request['discord_webhook_url'] = discord_webhook_url
|
||||
if youtube_description:
|
||||
create_request['youtube_description'] = youtube_description
|
||||
if enable_youtube_upload:
|
||||
create_request['enable_youtube_upload'] = enable_youtube_upload
|
||||
if dropbox_path:
|
||||
create_request['dropbox_path'] = dropbox_path
|
||||
if gdrive_folder_id:
|
||||
create_request['gdrive_folder_id'] = gdrive_folder_id
|
||||
if organised_dir_rclone_root:
|
||||
create_request['organised_dir_rclone_root'] = organised_dir_rclone_root
|
||||
if lyrics_artist:
|
||||
create_request['lyrics_artist'] = lyrics_artist
|
||||
if lyrics_title:
|
||||
create_request['lyrics_title'] = lyrics_title
|
||||
if subtitle_offset_ms != 0:
|
||||
create_request['subtitle_offset_ms'] = subtitle_offset_ms
|
||||
if clean_instrumental_model:
|
||||
create_request['clean_instrumental_model'] = clean_instrumental_model
|
||||
if backing_vocals_models:
|
||||
create_request['backing_vocals_models'] = backing_vocals_models
|
||||
if other_stems_models:
|
||||
create_request['other_stems_models'] = other_stems_models
|
||||
|
||||
response = self._request('POST', '/api/jobs/create-with-upload-urls', json=create_request)
|
||||
|
||||
if response.status_code != 200:
|
||||
try:
|
||||
error_detail = response.json()
|
||||
except Exception:
|
||||
error_detail = response.text
|
||||
raise RuntimeError(f"Error submitting job: {error_detail}")
|
||||
raise RuntimeError(f"Error creating job: {error_detail}")
|
||||
|
||||
create_result = response.json()
|
||||
if create_result.get('status') != 'success':
|
||||
raise RuntimeError(f"Error creating job: {create_result}")
|
||||
|
||||
job_id = create_result['job_id']
|
||||
upload_urls = create_result['upload_urls']
|
||||
|
||||
self.logger.info(f"Job {job_id} created. Uploading {len(upload_urls)} files directly to storage...")
|
||||
|
||||
# Step 3: Upload each file directly to GCS using signed URLs
|
||||
uploaded_files = []
|
||||
for url_info in upload_urls:
|
||||
file_type = url_info['file_type']
|
||||
signed_url = url_info['upload_url']
|
||||
content_type = url_info['content_type']
|
||||
local_path = local_files.get(file_type)
|
||||
|
||||
if not local_path:
|
||||
self.logger.warning(f"No local file found for file_type: {file_type}")
|
||||
continue
|
||||
|
||||
# Calculate file size for logging
|
||||
file_size = os.path.getsize(local_path)
|
||||
file_size_mb = file_size / (1024 * 1024)
|
||||
self.logger.info(f" Uploading {file_type} ({file_size_mb:.1f} MB)...")
|
||||
|
||||
success = self._upload_file_to_signed_url(signed_url, local_path, content_type)
|
||||
if not success:
|
||||
raise RuntimeError(f"Failed to upload {file_type} to storage")
|
||||
|
||||
uploaded_files.append(file_type)
|
||||
self.logger.info(f" ✓ Uploaded {file_type}")
|
||||
|
||||
# Step 4: Notify backend that uploads are complete
|
||||
self.logger.info(f"Notifying backend that uploads are complete...")
|
||||
|
||||
complete_request = {
|
||||
'uploaded_files': uploaded_files
|
||||
}
|
||||
|
||||
response = self._request('POST', f'/api/jobs/{job_id}/uploads-complete', json=complete_request)
|
||||
|
||||
if response.status_code != 200:
|
||||
try:
|
||||
error_detail = response.json()
|
||||
except Exception:
|
||||
error_detail = response.text
|
||||
raise RuntimeError(f"Error completing uploads: {error_detail}")
|
||||
|
||||
result = response.json()
|
||||
if result.get('status') != 'success':
|
||||
raise RuntimeError(f"Error submitting job: {result}")
|
||||
raise RuntimeError(f"Error completing uploads: {result}")
|
||||
|
||||
# Log distribution services info if available
|
||||
if 'distribution_services' in result:
|
||||
@@ -1747,6 +1870,13 @@ def main():
|
||||
logger.info(f"Lyrics File: {args.lyrics_file}")
|
||||
if getattr(args, 'subtitle_offset_ms', 0):
|
||||
logger.info(f"Subtitle Offset: {args.subtitle_offset_ms}ms")
|
||||
# Audio model configuration
|
||||
if getattr(args, 'clean_instrumental_model', None):
|
||||
logger.info(f"Clean Instrumental Model: {args.clean_instrumental_model}")
|
||||
if getattr(args, 'backing_vocals_models', None):
|
||||
logger.info(f"Backing Vocals Models: {args.backing_vocals_models}")
|
||||
if getattr(args, 'other_stems_models', None):
|
||||
logger.info(f"Other Stems Models: {args.other_stems_models}")
|
||||
logger.info(f"Service URL: {config.service_url}")
|
||||
logger.info(f"Review UI: {config.review_ui_url}")
|
||||
if config.non_interactive:
|
||||
@@ -1785,6 +1915,10 @@ def main():
|
||||
lyrics_title=getattr(args, 'lyrics_title', None),
|
||||
lyrics_file=getattr(args, 'lyrics_file', None),
|
||||
subtitle_offset_ms=getattr(args, 'subtitle_offset_ms', 0) or 0,
|
||||
# Audio separation model configuration
|
||||
clean_instrumental_model=getattr(args, 'clean_instrumental_model', None),
|
||||
backing_vocals_models=getattr(args, 'backing_vocals_models', None),
|
||||
other_stems_models=getattr(args, 'other_stems_models', None),
|
||||
)
|
||||
job_id = result.get('job_id')
|
||||
style_assets = result.get('style_assets_uploaded', [])
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.71.23"
|
||||
version = "0.71.25"
|
||||
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"
|
||||
|
||||
+237
-24
@@ -549,44 +549,94 @@ class TestRemoteKaraokeClient:
|
||||
client.submit_job(str(test_file), "Artist", "Title")
|
||||
|
||||
@patch.object(RemoteKaraokeClient, '_request')
|
||||
def test_submit_job_success(self, mock_request, client, tmp_path):
|
||||
"""Test successful job submission."""
|
||||
@patch.object(RemoteKaraokeClient, '_upload_file_to_signed_url')
|
||||
def test_submit_job_success(self, mock_upload, mock_request, client, tmp_path):
|
||||
"""Test successful job submission via signed URL flow."""
|
||||
# Create test audio file
|
||||
audio_file = tmp_path / "test.mp3"
|
||||
audio_file.write_bytes(b"audio data")
|
||||
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = {
|
||||
|
||||
# Mock create job response (first API call)
|
||||
create_response = MagicMock()
|
||||
create_response.status_code = 200
|
||||
create_response.json.return_value = {
|
||||
"status": "success",
|
||||
"job_id": "new-job-123"
|
||||
"job_id": "new-job-123",
|
||||
"upload_urls": [
|
||||
{
|
||||
"file_type": "audio",
|
||||
"gcs_path": "uploads/new-job-123/audio/test.mp3",
|
||||
"upload_url": "https://storage.googleapis.com/signed-url",
|
||||
"content_type": "audio/mpeg"
|
||||
}
|
||||
]
|
||||
}
|
||||
mock_request.return_value = mock_response
|
||||
|
||||
# Mock uploads complete response (second API call)
|
||||
complete_response = MagicMock()
|
||||
complete_response.status_code = 200
|
||||
complete_response.json.return_value = {
|
||||
"status": "success",
|
||||
"job_id": "new-job-123",
|
||||
"message": "Processing started"
|
||||
}
|
||||
|
||||
mock_request.side_effect = [create_response, complete_response]
|
||||
mock_upload.return_value = True
|
||||
|
||||
result = client.submit_job(str(audio_file), "Test Artist", "Test Title")
|
||||
|
||||
|
||||
assert result["status"] == "success"
|
||||
assert result["job_id"] == "new-job-123"
|
||||
|
||||
# Verify the signed URL upload was called
|
||||
mock_upload.assert_called_once()
|
||||
|
||||
@patch.object(RemoteKaraokeClient, '_upload_file_to_signed_url')
|
||||
@patch.object(RemoteKaraokeClient, '_request')
|
||||
def test_submit_job_with_style_params(self, mock_request, client, tmp_path):
|
||||
"""Test job submission with style params."""
|
||||
def test_submit_job_with_style_params(self, mock_request, mock_upload, client, tmp_path):
|
||||
"""Test job submission with style params via signed URL flow."""
|
||||
# Create test files
|
||||
audio_file = tmp_path / "test.mp3"
|
||||
audio_file.write_bytes(b"audio data")
|
||||
|
||||
|
||||
style_file = tmp_path / "style_params.json"
|
||||
style_file.write_text(json.dumps({"intro": {}}))
|
||||
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = {
|
||||
|
||||
# Mock create job response (first API call)
|
||||
create_response = MagicMock()
|
||||
create_response.status_code = 200
|
||||
create_response.json.return_value = {
|
||||
"status": "success",
|
||||
"job_id": "new-job-456",
|
||||
"style_assets_uploaded": []
|
||||
"upload_urls": [
|
||||
{
|
||||
"file_type": "audio",
|
||||
"gcs_path": "uploads/new-job-456/audio/test.mp3",
|
||||
"upload_url": "https://storage.googleapis.com/signed-url-1",
|
||||
"content_type": "audio/mpeg"
|
||||
},
|
||||
{
|
||||
"file_type": "style_params",
|
||||
"gcs_path": "uploads/new-job-456/style/style_params.json",
|
||||
"upload_url": "https://storage.googleapis.com/signed-url-2",
|
||||
"content_type": "application/json"
|
||||
}
|
||||
]
|
||||
}
|
||||
mock_request.return_value = mock_response
|
||||
|
||||
# Mock uploads complete response (second API call)
|
||||
complete_response = MagicMock()
|
||||
complete_response.status_code = 200
|
||||
complete_response.json.return_value = {
|
||||
"status": "success",
|
||||
"job_id": "new-job-456",
|
||||
"message": "Processing started",
|
||||
"style_assets": ["style_params"]
|
||||
}
|
||||
|
||||
mock_request.side_effect = [create_response, complete_response]
|
||||
mock_upload.return_value = True
|
||||
|
||||
result = client.submit_job(
|
||||
str(audio_file),
|
||||
"Test Artist",
|
||||
@@ -597,21 +647,23 @@ class TestRemoteKaraokeClient:
|
||||
brand_prefix="TEST",
|
||||
discord_webhook_url="https://discord.webhook/url"
|
||||
)
|
||||
|
||||
|
||||
assert result["status"] == "success"
|
||||
# Verify uploads were called for both files
|
||||
assert mock_upload.call_count == 2
|
||||
|
||||
@patch.object(RemoteKaraokeClient, '_request')
|
||||
def test_submit_job_api_error(self, mock_request, client, tmp_path):
|
||||
"""Test handling API error during job submission."""
|
||||
"""Test handling API error during job creation."""
|
||||
audio_file = tmp_path / "test.mp3"
|
||||
audio_file.write_bytes(b"audio data")
|
||||
|
||||
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 500
|
||||
mock_response.json.return_value = {"error": "Server error"}
|
||||
mock_request.return_value = mock_response
|
||||
|
||||
with pytest.raises(RuntimeError, match="Error submitting job"):
|
||||
|
||||
with pytest.raises(RuntimeError, match="Error creating job"):
|
||||
client.submit_job(str(audio_file), "Artist", "Title")
|
||||
|
||||
|
||||
@@ -1717,3 +1769,164 @@ class TestJobMonitorHandleReview:
|
||||
|
||||
mock_open_ui.assert_called_once_with("job-123")
|
||||
assert mock_get_job.call_count == 2
|
||||
|
||||
|
||||
class TestSignedUrlUploadFlow:
|
||||
"""Tests for the signed URL upload flow."""
|
||||
|
||||
@pytest.fixture
|
||||
def config(self):
|
||||
return Config(
|
||||
service_url="https://api.example.com",
|
||||
review_ui_url="https://review.example.com",
|
||||
poll_interval=5,
|
||||
output_dir="/tmp/output"
|
||||
)
|
||||
|
||||
@pytest.fixture
|
||||
def logger(self):
|
||||
return logging.getLogger("test")
|
||||
|
||||
@pytest.fixture
|
||||
def client(self, config, logger):
|
||||
return RemoteKaraokeClient(config, logger)
|
||||
|
||||
def test_get_content_type_audio(self, client):
|
||||
"""Test content type detection for audio files."""
|
||||
assert client._get_content_type("song.flac") == "audio/flac"
|
||||
assert client._get_content_type("song.mp3") == "audio/mpeg"
|
||||
assert client._get_content_type("song.wav") == "audio/wav"
|
||||
assert client._get_content_type("song.m4a") == "audio/mp4"
|
||||
assert client._get_content_type("song.ogg") == "audio/ogg"
|
||||
assert client._get_content_type("song.aac") == "audio/aac"
|
||||
|
||||
def test_get_content_type_images(self, client):
|
||||
"""Test content type detection for image files."""
|
||||
assert client._get_content_type("bg.png") == "image/png"
|
||||
assert client._get_content_type("bg.jpg") == "image/jpeg"
|
||||
assert client._get_content_type("bg.jpeg") == "image/jpeg"
|
||||
assert client._get_content_type("bg.gif") == "image/gif"
|
||||
assert client._get_content_type("bg.webp") == "image/webp"
|
||||
|
||||
def test_get_content_type_fonts(self, client):
|
||||
"""Test content type detection for font files."""
|
||||
assert client._get_content_type("font.ttf") == "font/ttf"
|
||||
assert client._get_content_type("font.otf") == "font/otf"
|
||||
assert client._get_content_type("font.woff") == "font/woff"
|
||||
assert client._get_content_type("font.woff2") == "font/woff2"
|
||||
|
||||
def test_get_content_type_other(self, client):
|
||||
"""Test content type detection for other files."""
|
||||
assert client._get_content_type("style.json") == "application/json"
|
||||
assert client._get_content_type("lyrics.txt") == "text/plain"
|
||||
assert client._get_content_type("unknown.xyz") == "application/octet-stream"
|
||||
|
||||
@patch('requests.put')
|
||||
def test_upload_file_to_signed_url_success(self, mock_put, client):
|
||||
"""Test successful upload to signed URL."""
|
||||
mock_put.return_value = MagicMock(status_code=200)
|
||||
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=".flac") as f:
|
||||
f.write(b"fake audio data")
|
||||
temp_path = f.name
|
||||
|
||||
try:
|
||||
result = client._upload_file_to_signed_url(
|
||||
"https://storage.googleapis.com/signed-url",
|
||||
temp_path,
|
||||
"audio/flac"
|
||||
)
|
||||
assert result is True
|
||||
mock_put.assert_called_once()
|
||||
finally:
|
||||
os.unlink(temp_path)
|
||||
|
||||
@patch('requests.put')
|
||||
def test_upload_file_to_signed_url_failure(self, mock_put, client):
|
||||
"""Test failed upload to signed URL."""
|
||||
mock_put.return_value = MagicMock(status_code=403, text="Forbidden")
|
||||
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=".flac") as f:
|
||||
f.write(b"fake audio data")
|
||||
temp_path = f.name
|
||||
|
||||
try:
|
||||
result = client._upload_file_to_signed_url(
|
||||
"https://storage.googleapis.com/signed-url",
|
||||
temp_path,
|
||||
"audio/flac"
|
||||
)
|
||||
assert result is False
|
||||
finally:
|
||||
os.unlink(temp_path)
|
||||
|
||||
@patch.object(RemoteKaraokeClient, '_upload_file_to_signed_url')
|
||||
@patch.object(RemoteKaraokeClient, '_request')
|
||||
def test_submit_job_uses_signed_url_flow(self, mock_request, mock_upload, client):
|
||||
"""Test that submit_job uses the signed URL upload flow."""
|
||||
# Mock create job response
|
||||
create_response = MagicMock()
|
||||
create_response.status_code = 200
|
||||
create_response.json.return_value = {
|
||||
"status": "success",
|
||||
"job_id": "test-job-123",
|
||||
"upload_urls": [
|
||||
{
|
||||
"file_type": "audio",
|
||||
"gcs_path": "uploads/test-job-123/audio/test.flac",
|
||||
"upload_url": "https://storage.googleapis.com/signed-url-1",
|
||||
"content_type": "audio/flac"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
# Mock uploads complete response
|
||||
complete_response = MagicMock()
|
||||
complete_response.status_code = 200
|
||||
complete_response.json.return_value = {
|
||||
"status": "success",
|
||||
"job_id": "test-job-123",
|
||||
"message": "Processing started"
|
||||
}
|
||||
|
||||
mock_request.side_effect = [create_response, complete_response]
|
||||
mock_upload.return_value = True
|
||||
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=".flac") as f:
|
||||
f.write(b"fake audio data")
|
||||
temp_path = f.name
|
||||
|
||||
try:
|
||||
result = client.submit_job(
|
||||
filepath=temp_path,
|
||||
artist="Test Artist",
|
||||
title="Test Song"
|
||||
)
|
||||
|
||||
# Verify the flow: create -> upload -> complete
|
||||
assert mock_request.call_count == 2
|
||||
|
||||
# First call should be to create-with-upload-urls
|
||||
first_call = mock_request.call_args_list[0]
|
||||
assert first_call[0][0] == 'POST'
|
||||
assert 'create-with-upload-urls' in first_call[0][1]
|
||||
|
||||
# Second call should be to uploads-complete
|
||||
second_call = mock_request.call_args_list[1]
|
||||
assert second_call[0][0] == 'POST'
|
||||
assert 'uploads-complete' in second_call[0][1]
|
||||
|
||||
# Upload should have been called for the audio file
|
||||
mock_upload.assert_called_once()
|
||||
|
||||
assert result["status"] == "success"
|
||||
assert result["job_id"] == "test-job-123"
|
||||
finally:
|
||||
os.unlink(temp_path)
|
||||
|
||||
def test_client_has_signed_url_methods(self, client):
|
||||
"""Test that RemoteKaraokeClient has the required signed URL methods."""
|
||||
assert hasattr(client, '_upload_file_to_signed_url')
|
||||
assert hasattr(client, '_get_content_type')
|
||||
assert callable(client._upload_file_to_signed_url)
|
||||
assert callable(client._get_content_type)
|
||||
Reference in new issue
Block a user