mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-02 09:58:08 +09:00
Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e333fb2ae0 | ||
|
|
3dd2ee4a86 | ||
|
|
70b1410c0e | ||
|
|
067052448f | ||
|
|
a5bca8781a | ||
|
|
7d1b9ce960 | ||
|
|
311e0a4ad2 | ||
|
|
70977f4807 | ||
|
|
11c8d8d58e | ||
|
|
c15673b27e | ||
|
|
913efcf72a | ||
|
|
ad0a6c3475 | ||
|
|
cd15024c42 | ||
|
|
9906d4bb63 | ||
|
|
9e28f7bd99 | ||
|
|
1741470ddb |
No files matched your search
@@ -25,6 +25,8 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- name: Set up Python 3.13
|
||||
uses: actions/setup-python@v5
|
||||
@@ -65,6 +67,8 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- name: Set up Python 3.13
|
||||
uses: actions/setup-python@v5
|
||||
@@ -97,6 +101,8 @@ jobs:
|
||||
needs: [package-unit-tests, package-integration-tests]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- name: Set up Python 3.13
|
||||
uses: actions/setup-python@v5
|
||||
@@ -275,6 +281,8 @@ jobs:
|
||||
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- name: Set up Python 3.13
|
||||
uses: actions/setup-python@v5
|
||||
@@ -368,19 +376,44 @@ jobs:
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
- name: Enable Yarn (for lyrics frontend)
|
||||
run: corepack enable
|
||||
|
||||
# ===== Build Main Frontend (Next.js) =====
|
||||
- name: Install main frontend dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Build Next.js static export
|
||||
- name: Build main frontend (Next.js static export)
|
||||
working-directory: frontend
|
||||
env:
|
||||
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
|
||||
run: npm run build
|
||||
|
||||
# ===== Build Lyrics Review Frontend (Vite) =====
|
||||
- name: Install lyrics frontend dependencies
|
||||
working-directory: lyrics_transcriber_temp/lyrics_transcriber/frontend
|
||||
run: yarn install --frozen-lockfile
|
||||
|
||||
- name: Build lyrics frontend (Vite)
|
||||
working-directory: lyrics_transcriber_temp/lyrics_transcriber/frontend
|
||||
env:
|
||||
# Set base path for subpath deployment
|
||||
VITE_BASE_PATH: /lyrics/
|
||||
run: yarn build --base=/lyrics/
|
||||
|
||||
- name: Copy lyrics frontend to main output
|
||||
run: |
|
||||
mkdir -p frontend/out/lyrics
|
||||
cp -r lyrics_transcriber_temp/lyrics_transcriber/frontend/dist/* frontend/out/lyrics/
|
||||
|
||||
# ===== Copy Instrumental Review UI (Static HTML) =====
|
||||
- name: Copy instrumental review UI to main output
|
||||
run: |
|
||||
mkdir -p frontend/out/instrumental
|
||||
cp karaoke_gen/instrumental_review/static/index.html frontend/out/instrumental/
|
||||
|
||||
- name: Setup Pages
|
||||
uses: actions/configure-pages@v4
|
||||
|
||||
|
||||
+194
-2
@@ -2,8 +2,10 @@
|
||||
FastAPI dependencies for authentication and authorization.
|
||||
"""
|
||||
import logging
|
||||
from typing import Optional, Tuple
|
||||
from fastapi import Depends, HTTPException, Header, Query, Request
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, UTC
|
||||
from typing import Optional, Tuple, Callable
|
||||
from fastapi import Depends, HTTPException, Header, Query, Request, Path
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
|
||||
from backend.services.auth_service import get_auth_service, UserType, AuthService
|
||||
@@ -12,6 +14,16 @@ from backend.services.auth_service import get_auth_service, UserType, AuthServic
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def generate_review_token() -> str:
|
||||
"""Generate a cryptographically secure review token."""
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def get_review_token_expiry(hours: int = 24) -> datetime:
|
||||
"""Get expiry time for a review token."""
|
||||
return datetime.now(UTC) + timedelta(hours=hours)
|
||||
|
||||
|
||||
# HTTP Bearer security scheme (Authorization: Bearer <token>)
|
||||
security = HTTPBearer(auto_error=False)
|
||||
|
||||
@@ -151,3 +163,183 @@ def optional_auth(
|
||||
return None
|
||||
|
||||
return token_str, user_type, remaining_uses
|
||||
|
||||
|
||||
def require_review_auth_factory(job_id_param: str = "job_id"):
|
||||
"""
|
||||
Factory to create a review authentication dependency.
|
||||
|
||||
Accepts either:
|
||||
1. Full user authentication (admin/user token)
|
||||
2. Job-specific review token (only valid for the specific job)
|
||||
|
||||
Args:
|
||||
job_id_param: Name of the path parameter containing the job ID
|
||||
|
||||
Returns:
|
||||
Dependency function that validates review access
|
||||
"""
|
||||
async def require_review_auth(
|
||||
request: Request,
|
||||
job_id: str = Path(...),
|
||||
review_token: Optional[str] = Query(None, description="Job-specific review token"),
|
||||
auth_service: AuthService = Depends(get_auth_service),
|
||||
credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
|
||||
token: Optional[str] = Query(None, alias="token", description="Full access token")
|
||||
) -> Tuple[str, str]:
|
||||
"""
|
||||
Validate review access for a job.
|
||||
|
||||
Returns:
|
||||
(job_id, auth_type) where auth_type is "full" or "review_token"
|
||||
|
||||
Raises:
|
||||
HTTPException: 401 if authentication fails
|
||||
"""
|
||||
# Import here to avoid circular dependency
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
# Try full authentication first
|
||||
full_token = None
|
||||
if credentials:
|
||||
full_token = credentials.credentials
|
||||
elif token:
|
||||
full_token = token
|
||||
|
||||
if full_token:
|
||||
is_valid, user_type, remaining_uses, message = auth_service.validate_token(full_token)
|
||||
if is_valid:
|
||||
logger.info(f"Review access granted via full auth ({user_type}) for job {job_id}")
|
||||
return job_id, "full"
|
||||
|
||||
# Try review token
|
||||
if review_token:
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
# Validate review token matches
|
||||
if job.review_token and secrets.compare_digest(job.review_token, review_token):
|
||||
# Check expiry if set
|
||||
if job.review_token_expires_at:
|
||||
now = datetime.now(UTC)
|
||||
# Handle timezone-naive datetimes from Firestore
|
||||
expiry = job.review_token_expires_at
|
||||
if expiry.tzinfo is None:
|
||||
expiry = expiry.replace(tzinfo=UTC)
|
||||
|
||||
if now > expiry:
|
||||
logger.warning(f"Review token expired for job {job_id}")
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Review token has expired. Please request a new review link."
|
||||
)
|
||||
|
||||
logger.info(f"Review access granted via review_token for job {job_id}")
|
||||
return job_id, "review_token"
|
||||
else:
|
||||
logger.warning(f"Invalid review token for job {job_id}")
|
||||
|
||||
# No valid authentication
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Authentication required. Provide either a full access token or a valid review_token for this job."
|
||||
)
|
||||
|
||||
return require_review_auth
|
||||
|
||||
|
||||
# Default instance for most review endpoints
|
||||
require_review_auth = require_review_auth_factory()
|
||||
|
||||
|
||||
def require_instrumental_auth_factory(job_id_param: str = "job_id"):
|
||||
"""
|
||||
Factory to create an instrumental review authentication dependency.
|
||||
|
||||
Accepts either:
|
||||
1. Full user authentication (admin/user token)
|
||||
2. Job-specific instrumental token (only valid for the specific job)
|
||||
|
||||
Args:
|
||||
job_id_param: Name of the path parameter containing the job ID
|
||||
|
||||
Returns:
|
||||
Dependency function that validates instrumental review access
|
||||
"""
|
||||
async def require_instrumental_auth(
|
||||
request: Request,
|
||||
job_id: str = Path(...),
|
||||
instrumental_token: Optional[str] = Query(None, description="Job-specific instrumental review token"),
|
||||
auth_service: AuthService = Depends(get_auth_service),
|
||||
credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
|
||||
token: Optional[str] = Query(None, alias="token", description="Full access token")
|
||||
) -> Tuple[str, str]:
|
||||
"""
|
||||
Validate instrumental review access for a job.
|
||||
|
||||
Returns:
|
||||
(job_id, auth_type) where auth_type is "full" or "instrumental_token"
|
||||
|
||||
Raises:
|
||||
HTTPException: 401 if authentication fails
|
||||
"""
|
||||
# Import here to avoid circular dependency
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
# Try full authentication first
|
||||
full_token = None
|
||||
if credentials:
|
||||
full_token = credentials.credentials
|
||||
elif token:
|
||||
full_token = token
|
||||
|
||||
if full_token:
|
||||
is_valid, user_type, remaining_uses, message = auth_service.validate_token(full_token)
|
||||
if is_valid:
|
||||
logger.info(f"Instrumental access granted via full auth ({user_type}) for job {job_id}")
|
||||
return job_id, "full"
|
||||
|
||||
# Try instrumental token
|
||||
if instrumental_token:
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
# Validate instrumental token matches
|
||||
if job.instrumental_token and secrets.compare_digest(job.instrumental_token, instrumental_token):
|
||||
# Check expiry if set
|
||||
if job.instrumental_token_expires_at:
|
||||
now = datetime.now(UTC)
|
||||
# Handle timezone-naive datetimes from Firestore
|
||||
expiry = job.instrumental_token_expires_at
|
||||
if expiry.tzinfo is None:
|
||||
expiry = expiry.replace(tzinfo=UTC)
|
||||
|
||||
if now > expiry:
|
||||
logger.warning(f"Instrumental token expired for job {job_id}")
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Instrumental review token has expired. Please request a new review link."
|
||||
)
|
||||
|
||||
logger.info(f"Instrumental access granted via instrumental_token for job {job_id}")
|
||||
return job_id, "instrumental_token"
|
||||
else:
|
||||
logger.warning(f"Invalid instrumental token for job {job_id}")
|
||||
|
||||
# No valid authentication
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Authentication required. Provide either a full access token or a valid instrumental_token for this job."
|
||||
)
|
||||
|
||||
return require_instrumental_auth
|
||||
|
||||
|
||||
# Default instance for most instrumental review endpoints
|
||||
require_instrumental_auth = require_instrumental_auth_factory()
|
||||
@@ -231,7 +231,7 @@ async def _download_and_start_processing(
|
||||
|
||||
try:
|
||||
# Determine if this is a remote torrent download
|
||||
is_torrent_source = selected.get('provider') in ['Redacted', 'OPS']
|
||||
is_torrent_source = selected.get('provider') in ['RED', 'OPS']
|
||||
is_remote_enabled = audio_search_service.is_remote_enabled()
|
||||
|
||||
# For remote torrent downloads, have flacfetch VM upload directly to GCS
|
||||
|
||||
@@ -26,7 +26,7 @@ from backend.services.job_manager import JobManager
|
||||
from backend.services.worker_service import get_worker_service
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.config import get_settings
|
||||
from backend.api.dependencies import require_admin, require_auth
|
||||
from backend.api.dependencies import require_admin, require_auth, require_instrumental_auth
|
||||
from backend.services.auth_service import UserType
|
||||
from backend.services.metrics import metrics
|
||||
|
||||
@@ -494,7 +494,7 @@ async def complete_review(
|
||||
@router.get("/{job_id}/instrumental-options")
|
||||
async def get_instrumental_options(
|
||||
job_id: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
auth_info: Tuple[str, str] = Depends(require_instrumental_auth)
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Get instrumental audio options for user selection.
|
||||
@@ -502,6 +502,8 @@ async def get_instrumental_options(
|
||||
Returns signed URLs for both options:
|
||||
1. Clean instrumental (no backing vocals)
|
||||
2. Instrumental with backing vocals
|
||||
|
||||
Accepts either full auth token or job-specific instrumental_token.
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
@@ -552,7 +554,7 @@ async def get_instrumental_options(
|
||||
@router.get("/{job_id}/instrumental-analysis")
|
||||
async def get_instrumental_analysis(
|
||||
job_id: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
auth_info: Tuple[str, str] = Depends(require_instrumental_auth)
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Get audio analysis data for instrumental selection.
|
||||
@@ -564,6 +566,8 @@ async def get_instrumental_analysis(
|
||||
|
||||
This endpoint enables intelligent instrumental selection by providing
|
||||
detailed analysis of the backing vocals track.
|
||||
|
||||
Accepts either full auth token or job-specific instrumental_token.
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
@@ -630,7 +634,7 @@ async def get_instrumental_analysis(
|
||||
async def stream_audio(
|
||||
job_id: str,
|
||||
stem_type: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
auth_info: Tuple[str, str] = Depends(require_instrumental_auth)
|
||||
):
|
||||
"""
|
||||
Stream an audio file for playback in the browser.
|
||||
@@ -643,6 +647,8 @@ async def stream_audio(
|
||||
|
||||
Returns audio as a streaming response with proper headers for
|
||||
browser audio playback.
|
||||
|
||||
Accepts either full auth token or job-specific instrumental_token.
|
||||
"""
|
||||
from fastapi.responses import StreamingResponse
|
||||
import tempfile
|
||||
@@ -719,6 +725,7 @@ async def stream_audio(
|
||||
async def create_custom_instrumental(
|
||||
job_id: str,
|
||||
request: CreateCustomInstrumentalRequest,
|
||||
auth_info: Tuple[str, str] = Depends(require_instrumental_auth)
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Create a custom instrumental by muting regions of backing vocals.
|
||||
@@ -730,6 +737,8 @@ async def create_custom_instrumental(
|
||||
|
||||
After calling this endpoint, the user can select "custom" in the
|
||||
select-instrumental endpoint.
|
||||
|
||||
Accepts either full auth token or job-specific instrumental_token.
|
||||
"""
|
||||
from backend.services.audio_editing_service import AudioEditingService
|
||||
from karaoke_gen.instrumental_review import MuteRegion
|
||||
@@ -811,7 +820,7 @@ async def create_custom_instrumental(
|
||||
async def get_waveform_data(
|
||||
job_id: str,
|
||||
num_points: int = 500,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
auth_info: Tuple[str, str] = Depends(require_instrumental_auth)
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Get waveform amplitude data for client-side rendering.
|
||||
@@ -829,6 +838,8 @@ async def get_waveform_data(
|
||||
"duration_seconds": 180.5,
|
||||
"num_points": 500
|
||||
}
|
||||
|
||||
Accepts either full auth token or job-specific instrumental_token.
|
||||
"""
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
@@ -870,13 +881,15 @@ async def select_instrumental(
|
||||
job_id: str,
|
||||
selection: InstrumentalSelection,
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
auth_info: Tuple[str, str] = Depends(require_instrumental_auth)
|
||||
) -> dict:
|
||||
"""
|
||||
Submit instrumental selection.
|
||||
|
||||
This is the SECOND critical human-in-the-loop interaction point.
|
||||
After selection, the job proceeds to video generation.
|
||||
|
||||
Accepts either full auth token or job-specific instrumental_token.
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
|
||||
@@ -27,7 +27,7 @@ from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.job_logging import job_log_context, JobLogger
|
||||
from backend.services.tracing import create_span, add_span_attribute, add_span_event
|
||||
from backend.api.dependencies import require_auth
|
||||
from backend.api.dependencies import require_auth, require_review_auth
|
||||
from backend.services.auth_service import UserType
|
||||
|
||||
# LyricsTranscriber imports for preview generation
|
||||
@@ -67,7 +67,7 @@ async def ping(job_id: str):
|
||||
@router.get("/{job_id}/correction-data")
|
||||
async def get_correction_data(
|
||||
job_id: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Get correction data for the review interface.
|
||||
@@ -134,14 +134,21 @@ async def get_correction_data(
|
||||
|
||||
|
||||
@router.get("/{job_id}/audio/{audio_hash}")
|
||||
async def get_audio_with_hash(job_id: str, audio_hash: str):
|
||||
async def get_audio_with_hash(
|
||||
job_id: str,
|
||||
audio_hash: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Stream the audio file for playback (with hash parameter)."""
|
||||
return await _stream_audio(job_id)
|
||||
|
||||
|
||||
@router.get("/{job_id}/audio/")
|
||||
@router.get("/{job_id}/audio")
|
||||
async def get_audio_no_hash(job_id: str):
|
||||
async def get_audio_no_hash(
|
||||
job_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Stream the audio file for playback (without hash parameter)."""
|
||||
return await _stream_audio(job_id)
|
||||
|
||||
@@ -197,7 +204,7 @@ async def _stream_audio(job_id: str):
|
||||
async def complete_review(
|
||||
job_id: str,
|
||||
updated_data: Dict[str, Any],
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Complete the review and save corrected lyrics.
|
||||
@@ -253,7 +260,11 @@ async def complete_review(
|
||||
|
||||
|
||||
@router.post("/{job_id}/handlers")
|
||||
async def update_handlers(job_id: str, enabled_handlers: list):
|
||||
async def update_handlers(
|
||||
job_id: str,
|
||||
enabled_handlers: list,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Update enabled correction handlers (optional feature).
|
||||
|
||||
@@ -268,7 +279,7 @@ async def update_handlers(job_id: str, enabled_handlers: list):
|
||||
async def add_lyrics(
|
||||
job_id: str,
|
||||
data: Dict[str, str],
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Add custom lyrics source and rerun correction.
|
||||
@@ -370,7 +381,7 @@ async def add_lyrics(
|
||||
async def generate_preview_video(
|
||||
job_id: str,
|
||||
updated_data: Dict[str, Any],
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Generate a preview video with the current corrections.
|
||||
@@ -486,7 +497,11 @@ async def generate_preview_video(
|
||||
|
||||
|
||||
@router.get("/{job_id}/preview-video/{preview_hash}")
|
||||
async def get_preview_video(job_id: str, preview_hash: str):
|
||||
async def get_preview_video(
|
||||
job_id: str,
|
||||
preview_hash: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Stream the generated preview video."""
|
||||
storage = StorageService()
|
||||
|
||||
@@ -527,7 +542,11 @@ async def get_preview_video(job_id: str, preview_hash: str):
|
||||
|
||||
|
||||
@router.post("/{job_id}/v1/annotations")
|
||||
async def submit_annotation(job_id: str, annotation: Dict[str, Any]):
|
||||
async def submit_annotation(
|
||||
job_id: str,
|
||||
annotation: Dict[str, Any],
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Submit a correction annotation for ML training data.
|
||||
|
||||
@@ -539,7 +558,10 @@ async def submit_annotation(job_id: str, annotation: Dict[str, Any]):
|
||||
|
||||
|
||||
@router.get("/{job_id}/v1/annotations/stats")
|
||||
async def get_annotation_stats(job_id: str):
|
||||
async def get_annotation_stats(
|
||||
job_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Get annotation statistics."""
|
||||
return {
|
||||
"total_annotations": 0,
|
||||
|
||||
@@ -251,6 +251,12 @@ class Job(BaseModel):
|
||||
finalise_only: bool = False # Skip prep, run only finalisation (requires uploaded prep outputs)
|
||||
keep_brand_code: Optional[str] = None # Preserve existing brand code instead of generating new one
|
||||
|
||||
# Review authentication (Batch 7)
|
||||
review_token: Optional[str] = None # Job-scoped token for lyrics review UI access (generated when entering AWAITING_REVIEW)
|
||||
review_token_expires_at: Optional[datetime] = None # Token expiry time (optional, for extra security)
|
||||
instrumental_token: Optional[str] = None # Job-scoped token for instrumental review UI access (generated when entering AWAITING_INSTRUMENTAL_SELECTION)
|
||||
instrumental_token_expires_at: Optional[datetime] = None # Token expiry time
|
||||
|
||||
# Processing state
|
||||
track_output_dir: Optional[str] = None # Local output directory (temp)
|
||||
audio_hash: Optional[str] = None # Hash for deduplication
|
||||
|
||||
@@ -71,22 +71,30 @@ class AudioSearchService:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
redacted_api_key: Optional[str] = _USE_ENV,
|
||||
red_api_key: Optional[str] = _USE_ENV,
|
||||
red_api_url: Optional[str] = _USE_ENV,
|
||||
ops_api_key: Optional[str] = _USE_ENV,
|
||||
ops_api_url: Optional[str] = _USE_ENV,
|
||||
):
|
||||
"""
|
||||
Initialize the audio search service.
|
||||
|
||||
Args:
|
||||
redacted_api_key: API key for Redacted tracker (optional, uses env if not provided)
|
||||
red_api_key: API key for RED tracker (optional, uses env if not provided)
|
||||
red_api_url: Base URL for RED tracker API (optional, uses env if not provided)
|
||||
ops_api_key: API key for OPS tracker (optional, uses env if not provided)
|
||||
ops_api_url: Base URL for OPS tracker API (optional, uses env if not provided)
|
||||
"""
|
||||
# Use environment variables if not explicitly provided
|
||||
if redacted_api_key is self._USE_ENV:
|
||||
redacted_api_key = os.environ.get("REDACTED_API_KEY")
|
||||
if red_api_key is self._USE_ENV:
|
||||
red_api_key = os.environ.get("RED_API_KEY")
|
||||
if red_api_url is self._USE_ENV:
|
||||
red_api_url = os.environ.get("RED_API_URL")
|
||||
|
||||
if ops_api_key is self._USE_ENV:
|
||||
ops_api_key = os.environ.get("OPS_API_KEY")
|
||||
if ops_api_url is self._USE_ENV:
|
||||
ops_api_url = os.environ.get("OPS_API_URL")
|
||||
|
||||
# Check for remote flacfetch client
|
||||
self._remote_client = get_flacfetch_client()
|
||||
@@ -99,8 +107,10 @@ class AudioSearchService:
|
||||
|
||||
# Delegate to shared FlacFetcher implementation (for local mode or fallback)
|
||||
self._fetcher = FlacFetcher(
|
||||
redacted_api_key=redacted_api_key,
|
||||
red_api_key=red_api_key,
|
||||
red_api_url=red_api_url,
|
||||
ops_api_key=ops_api_key,
|
||||
ops_api_url=ops_api_url,
|
||||
)
|
||||
|
||||
# Cache search results for API-based selection flow
|
||||
@@ -276,7 +286,7 @@ class AudioSearchService:
|
||||
# Check if this was a remote search (torrent sources need remote download)
|
||||
if self._remote_search_id and self._remote_client:
|
||||
# Check if this is a torrent source that needs remote handling
|
||||
is_torrent = result.provider in ["Redacted", "OPS"]
|
||||
is_torrent = result.provider in ["RED", "OPS"]
|
||||
|
||||
if is_torrent:
|
||||
return self._download_remote(result_index, output_dir, output_filename, gcs_path)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
Client for the remote flacfetch HTTP API service.
|
||||
|
||||
This client communicates with a dedicated flacfetch VM that handles:
|
||||
- BitTorrent downloads from private trackers (Redacted, OPS)
|
||||
- BitTorrent downloads from private trackers (RED, OPS)
|
||||
- YouTube downloads
|
||||
- GCS uploads of downloaded files
|
||||
|
||||
|
||||
@@ -280,6 +280,24 @@ class JobManager:
|
||||
if progress is not None:
|
||||
updates['progress'] = progress
|
||||
|
||||
# Generate review token when entering AWAITING_REVIEW state
|
||||
if new_status == JobStatus.AWAITING_REVIEW:
|
||||
from backend.api.dependencies import generate_review_token, get_review_token_expiry
|
||||
review_token = generate_review_token()
|
||||
review_token_expires = get_review_token_expiry(hours=48) # 48 hour expiry
|
||||
updates['review_token'] = review_token
|
||||
updates['review_token_expires_at'] = review_token_expires
|
||||
logger.info(f"Generated review token for job {job_id}, expires in 48 hours")
|
||||
|
||||
# Generate instrumental token when entering AWAITING_INSTRUMENTAL_SELECTION state
|
||||
if new_status == JobStatus.AWAITING_INSTRUMENTAL_SELECTION:
|
||||
from backend.api.dependencies import generate_review_token, get_review_token_expiry
|
||||
instrumental_token = generate_review_token() # Reuse same token generator
|
||||
instrumental_token_expires = get_review_token_expiry(hours=48) # 48 hour expiry
|
||||
updates['instrumental_token'] = instrumental_token
|
||||
updates['instrumental_token_expires_at'] = instrumental_token_expires
|
||||
logger.info(f"Generated instrumental token for job {job_id}, expires in 48 hours")
|
||||
|
||||
# If we have state_data_updates, merge them with existing state_data
|
||||
merged_state_data = None
|
||||
if state_data_updates:
|
||||
@@ -304,6 +322,20 @@ class JobManager:
|
||||
message=message
|
||||
)
|
||||
|
||||
# Apply review token update separately if generated
|
||||
if new_status == JobStatus.AWAITING_REVIEW and 'review_token' in updates:
|
||||
self.firestore.update_job(job_id, {
|
||||
'review_token': updates['review_token'],
|
||||
'review_token_expires_at': updates['review_token_expires_at']
|
||||
})
|
||||
|
||||
# Apply instrumental token update separately if generated
|
||||
if new_status == JobStatus.AWAITING_INSTRUMENTAL_SELECTION and 'instrumental_token' in updates:
|
||||
self.firestore.update_job(job_id, {
|
||||
'instrumental_token': updates['instrumental_token'],
|
||||
'instrumental_token_expires_at': updates['instrumental_token_expires_at']
|
||||
})
|
||||
|
||||
logger.info(f"Job {job_id} transitioned to {new_status}")
|
||||
return True
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ def mock_auth_dependency(request):
|
||||
return
|
||||
|
||||
from backend.services.auth_service import UserType
|
||||
from backend.api.dependencies import require_auth, require_admin
|
||||
from backend.api.dependencies import require_auth, require_admin, require_review_auth, require_instrumental_auth
|
||||
from backend.main import app
|
||||
|
||||
# Create mock auth functions
|
||||
@@ -62,9 +62,19 @@ def mock_auth_dependency(request):
|
||||
"""Mock require_admin to always return valid admin credentials."""
|
||||
return ("test-admin-token", UserType.ADMIN, 999)
|
||||
|
||||
async def mock_require_review_auth(job_id: str = "test123"):
|
||||
"""Mock require_review_auth to always return valid review access."""
|
||||
return (job_id, "full")
|
||||
|
||||
async def mock_require_instrumental_auth(job_id: str = "test123"):
|
||||
"""Mock require_instrumental_auth to always return valid instrumental review access."""
|
||||
return (job_id, "full")
|
||||
|
||||
# Use FastAPI's dependency override system
|
||||
app.dependency_overrides[require_auth] = mock_require_auth
|
||||
app.dependency_overrides[require_admin] = mock_require_admin
|
||||
app.dependency_overrides[require_review_auth] = mock_require_review_auth
|
||||
app.dependency_overrides[require_instrumental_auth] = mock_require_instrumental_auth
|
||||
|
||||
yield
|
||||
|
||||
|
||||
@@ -321,6 +321,7 @@ class TestReviewEndpoints:
|
||||
# Annotations endpoint should accept data (even if it just logs it)
|
||||
response = client.post(
|
||||
f"/api/review/{job_id}/v1/annotations",
|
||||
headers=auth_headers,
|
||||
json={"type": "test", "data": "test annotation"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
@@ -172,26 +172,30 @@ class TestAudioSearchResult:
|
||||
class TestAudioSearchServiceInit:
|
||||
"""Test AudioSearchService initialization."""
|
||||
|
||||
@patch.dict('os.environ', {'REDACTED_API_KEY': '', 'OPS_API_KEY': ''}, clear=False)
|
||||
@patch.dict('os.environ', {'RED_API_KEY': '', 'RED_API_URL': '', 'OPS_API_KEY': '', 'OPS_API_URL': ''}, clear=False)
|
||||
def test_init_with_no_keys(self):
|
||||
"""Test initialization without API keys."""
|
||||
# Pass explicit None to override environment
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
|
||||
# Service should have a FlacFetcher internally
|
||||
assert service._fetcher is not None
|
||||
assert service._cached_results == []
|
||||
|
||||
def test_init_with_keys(self):
|
||||
"""Test initialization with API keys."""
|
||||
"""Test initialization with API keys and URLs."""
|
||||
service = AudioSearchService(
|
||||
redacted_api_key="test_redacted_key",
|
||||
red_api_key="test_red_key",
|
||||
red_api_url="https://red.url",
|
||||
ops_api_key="test_ops_key",
|
||||
ops_api_url="https://ops.url",
|
||||
)
|
||||
|
||||
# Keys are passed to FlacFetcher
|
||||
assert service._fetcher._redacted_api_key == "test_redacted_key"
|
||||
# Keys and URLs are passed to FlacFetcher
|
||||
assert service._fetcher._red_api_key == "test_red_key"
|
||||
assert service._fetcher._red_api_url == "https://red.url"
|
||||
assert service._fetcher._ops_api_key == "test_ops_key"
|
||||
assert service._fetcher._ops_api_url == "https://ops.url"
|
||||
|
||||
def test_init_reads_from_environment(self):
|
||||
"""Test initialization reads keys from environment variables."""
|
||||
@@ -219,7 +223,7 @@ class TestAudioSearchServiceSearch:
|
||||
index=0,
|
||||
)
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._fetcher = Mock()
|
||||
service._fetcher.search.return_value = [mock_result]
|
||||
|
||||
@@ -233,7 +237,8 @@ class TestAudioSearchServiceSearch:
|
||||
|
||||
def test_search_no_results_raises_error(self):
|
||||
"""Test search raises NoResultsError when no results."""
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._remote_client = None # Force local mode to use mocked fetcher
|
||||
service._fetcher = Mock()
|
||||
service._fetcher.search.side_effect = NoResultsError("No results found")
|
||||
|
||||
@@ -249,7 +254,7 @@ class TestAudioSearchServiceSearch:
|
||||
mock_results.append(AudioSearchResult(
|
||||
title=f"Song {i}",
|
||||
artist="Artist",
|
||||
provider=["YouTube", "Redacted", "OPS"][i],
|
||||
provider=["YouTube", "RED", "OPS"][i],
|
||||
url=f"https://example.com/{i}",
|
||||
duration=180 + i * 10,
|
||||
quality=["320kbps", "FLAC", "FLAC"][i],
|
||||
@@ -257,7 +262,8 @@ class TestAudioSearchServiceSearch:
|
||||
index=i,
|
||||
))
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._remote_client = None # Force local mode to use mocked fetcher
|
||||
service._fetcher = Mock()
|
||||
service._fetcher.search.return_value = mock_results
|
||||
|
||||
@@ -285,13 +291,13 @@ class TestAudioSearchServiceSelectBest:
|
||||
AudioSearchResult(
|
||||
title="Waterloo",
|
||||
artist="ABBA",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
url="https://example.com/456",
|
||||
index=1,
|
||||
),
|
||||
]
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._fetcher = Mock()
|
||||
service._fetcher.select_best.return_value = 1
|
||||
|
||||
@@ -302,7 +308,7 @@ class TestAudioSearchServiceSelectBest:
|
||||
|
||||
def test_select_best_empty_list_returns_zero(self):
|
||||
"""Test select_best returns 0 for empty list."""
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._fetcher = Mock()
|
||||
service._fetcher.select_best.return_value = 0
|
||||
|
||||
@@ -316,7 +322,7 @@ class TestAudioSearchServiceDownload:
|
||||
|
||||
def test_download_without_search_raises_error(self):
|
||||
"""Test download without prior search raises error."""
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
|
||||
with pytest.raises(DownloadError) as exc_info:
|
||||
service.download(0, "/tmp")
|
||||
@@ -353,7 +359,8 @@ class TestAudioSearchServiceDownload:
|
||||
quality="FLAC",
|
||||
)
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._remote_client = None # Force local mode to use mocked fetcher
|
||||
service._fetcher = Mock()
|
||||
service._fetcher.search.return_value = [mock_result]
|
||||
service._fetcher.download.return_value = mock_fetch_result
|
||||
@@ -380,7 +387,7 @@ class TestAudioSearchServiceDownload:
|
||||
index=0,
|
||||
)
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._fetcher = Mock()
|
||||
service._fetcher.search.return_value = [mock_result]
|
||||
|
||||
@@ -418,23 +425,23 @@ class TestRemoteDownloadPath:
|
||||
"""Test remote download functionality when flacfetch service is configured.
|
||||
|
||||
These tests verify the code path that uses the remote flacfetch service
|
||||
for torrent downloads (Redacted/OPS providers). This would have caught
|
||||
for torrent downloads (RED/OPS providers). This would have caught
|
||||
the 'extra_info' attribute error.
|
||||
|
||||
The tests directly set up the service state without calling search() to avoid
|
||||
the complexity of mocking async remote search operations.
|
||||
"""
|
||||
|
||||
def test_download_uses_remote_for_redacted_provider(self):
|
||||
"""Test download routes to remote service for Redacted provider.
|
||||
def test_download_uses_remote_for_red_provider(self):
|
||||
"""Test download routes to remote service for RED provider.
|
||||
|
||||
This test would have caught: 'AudioSearchResult' object has no attribute 'extra_info'
|
||||
"""
|
||||
# Create a Redacted result (torrent source)
|
||||
# Create a RED result (torrent source)
|
||||
mock_result = AudioSearchResult(
|
||||
title="Waterloo",
|
||||
artist="ABBA",
|
||||
provider="Redacted", # Torrent provider - should use remote
|
||||
provider="RED", # Torrent provider - should use remote
|
||||
url="", # No URL for torrent sources
|
||||
quality="FLAC 16bit CD",
|
||||
seeders=50,
|
||||
@@ -443,7 +450,7 @@ class TestRemoteDownloadPath:
|
||||
)
|
||||
|
||||
# Create service with mocked remote client
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._fetcher = Mock()
|
||||
|
||||
# Directly set cached results (simulating after search)
|
||||
@@ -459,7 +466,7 @@ class TestRemoteDownloadPath:
|
||||
filepath="gs://bucket/uploads/job123/audio/Waterloo.flac",
|
||||
artist="ABBA",
|
||||
title="Waterloo",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
quality="FLAC 16bit CD",
|
||||
)
|
||||
service._download_remote = Mock(return_value=mock_download_result)
|
||||
@@ -483,7 +490,7 @@ class TestRemoteDownloadPath:
|
||||
index=0,
|
||||
)
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._fetcher = Mock()
|
||||
|
||||
# Directly set cached results
|
||||
@@ -521,7 +528,7 @@ class TestRemoteDownloadPath:
|
||||
index=0,
|
||||
)
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._fetcher = Mock()
|
||||
|
||||
# Directly set cached results
|
||||
@@ -557,13 +564,13 @@ class TestRemoteDownloadPath:
|
||||
mock_result = AudioSearchResult(
|
||||
title="Waterloo",
|
||||
artist="ABBA",
|
||||
provider="Redacted", # Would normally use remote
|
||||
provider="RED", # Would normally use remote
|
||||
url="",
|
||||
quality="FLAC",
|
||||
index=0,
|
||||
)
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._fetcher = Mock()
|
||||
|
||||
# Directly set cached results
|
||||
@@ -578,7 +585,7 @@ class TestRemoteDownloadPath:
|
||||
filepath="/tmp/test.flac",
|
||||
artist="ABBA",
|
||||
title="Waterloo",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
quality="FLAC",
|
||||
)
|
||||
service._fetcher.download.return_value = mock_fetch_result
|
||||
@@ -586,7 +593,7 @@ class TestRemoteDownloadPath:
|
||||
# Call download
|
||||
result = service.download(0, "/tmp")
|
||||
|
||||
# Should use local even though it's Redacted
|
||||
# Should use local even though it's RED
|
||||
service._fetcher.download.assert_called_once()
|
||||
|
||||
def test_download_uses_local_when_no_remote_search_id(self):
|
||||
@@ -594,13 +601,13 @@ class TestRemoteDownloadPath:
|
||||
mock_result = AudioSearchResult(
|
||||
title="Waterloo",
|
||||
artist="ABBA",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
url="",
|
||||
quality="FLAC",
|
||||
index=0,
|
||||
)
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._fetcher = Mock()
|
||||
|
||||
# Directly set cached results
|
||||
@@ -615,7 +622,7 @@ class TestRemoteDownloadPath:
|
||||
filepath="/tmp/test.flac",
|
||||
artist="ABBA",
|
||||
title="Waterloo",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
quality="FLAC",
|
||||
)
|
||||
service._fetcher.download.return_value = mock_fetch_result
|
||||
@@ -634,13 +641,13 @@ class TestRemoteDownloadPath:
|
||||
mock_result = AudioSearchResult(
|
||||
title="Waterloo",
|
||||
artist="ABBA",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
url="",
|
||||
quality="FLAC",
|
||||
index=0,
|
||||
)
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._fetcher = Mock()
|
||||
service._cached_results = [mock_result]
|
||||
|
||||
@@ -650,7 +657,7 @@ class TestRemoteDownloadPath:
|
||||
|
||||
mock_fetch_result = AudioDownloadResult(
|
||||
filepath="/tmp/test.flac", artist="ABBA", title="Waterloo",
|
||||
provider="Redacted", quality="FLAC",
|
||||
provider="RED", quality="FLAC",
|
||||
)
|
||||
service._fetcher.download.return_value = mock_fetch_result
|
||||
service._download_remote = Mock()
|
||||
@@ -683,7 +690,7 @@ class TestRemoteDownloadPath:
|
||||
mock_result = AudioSearchResult(
|
||||
title="Waterloo",
|
||||
artist="ABBA",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
url="",
|
||||
quality="FLAC 16bit CD",
|
||||
seeders=50,
|
||||
@@ -693,7 +700,7 @@ class TestRemoteDownloadPath:
|
||||
# Verify AudioSearchResult doesn't have extra_info
|
||||
assert not hasattr(mock_result, 'extra_info')
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._fetcher = Mock()
|
||||
service._cached_results = [mock_result]
|
||||
service._remote_search_id = "search_123"
|
||||
@@ -704,7 +711,7 @@ class TestRemoteDownloadPath:
|
||||
filepath="/tmp/test.flac",
|
||||
artist="ABBA",
|
||||
title="Waterloo",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
quality="FLAC",
|
||||
)
|
||||
service._download_remote = Mock(return_value=mock_download_result)
|
||||
@@ -712,7 +719,7 @@ class TestRemoteDownloadPath:
|
||||
# This should NOT raise AttributeError: 'AudioSearchResult' object has no attribute 'extra_info'
|
||||
result = service.download(0, "/tmp")
|
||||
|
||||
# Should succeed and use remote download for Redacted provider
|
||||
# Should succeed and use remote download for RED provider
|
||||
service._download_remote.assert_called_once()
|
||||
assert result.filepath == "/tmp/test.flac"
|
||||
|
||||
@@ -775,7 +782,8 @@ class TestFlacfetchIntegration:
|
||||
pytest.importorskip("flacfetch")
|
||||
|
||||
service = AudioSearchService(
|
||||
redacted_api_key=None,
|
||||
red_api_key=None,
|
||||
red_api_url=None,
|
||||
ops_api_key=None,
|
||||
)
|
||||
|
||||
@@ -835,13 +843,13 @@ class TestAudioSearchApiRouteDownload:
|
||||
from backend.api.routes.audio_search import _download_and_start_processing
|
||||
import asyncio
|
||||
|
||||
# Setup mock job with Redacted search result
|
||||
# Setup mock job with RED search result
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Unwanted',
|
||||
'artist': 'Avril Lavigne',
|
||||
'provider': 'Redacted', # Torrent source
|
||||
'provider': 'RED', # Torrent source
|
||||
'quality': 'FLAC 16bit CD',
|
||||
}]
|
||||
}
|
||||
@@ -956,13 +964,13 @@ class TestAudioSearchApiRouteDownload:
|
||||
from backend.api.routes.audio_search import _download_and_start_processing
|
||||
import asyncio
|
||||
|
||||
# Setup mock job with Redacted search result
|
||||
# Setup mock job with RED search result
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Test',
|
||||
'artist': 'Test Artist',
|
||||
'provider': 'Redacted',
|
||||
'provider': 'RED',
|
||||
'quality': 'FLAC',
|
||||
}]
|
||||
}
|
||||
@@ -1012,13 +1020,13 @@ class TestAudioSearchApiRouteDownload:
|
||||
import asyncio
|
||||
import tempfile
|
||||
|
||||
# Setup mock job with Redacted search result
|
||||
# Setup mock job with RED search result
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Test',
|
||||
'artist': 'Test',
|
||||
'provider': 'Redacted', # Torrent source, but remote is disabled
|
||||
'provider': 'RED', # Torrent source, but remote is disabled
|
||||
'quality': 'FLAC',
|
||||
}]
|
||||
}
|
||||
|
||||
@@ -188,7 +188,7 @@ class TestFlacfetchClientSearch:
|
||||
{
|
||||
"title": "Waterloo",
|
||||
"artist": "ABBA",
|
||||
"provider": "Redacted",
|
||||
"provider": "RED",
|
||||
"quality": "FLAC 16bit CD",
|
||||
"seeders": 50,
|
||||
"index": 0,
|
||||
|
||||
@@ -32,7 +32,7 @@ def _create_mock_job(job_id: str = "test123") -> Job:
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(mock_auth_service):
|
||||
def client():
|
||||
"""Create TestClient with mocked workers and job manager."""
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
|
||||
@@ -81,7 +81,7 @@ class TestGetJob:
|
||||
assert data["status"] == "pending"
|
||||
assert data["artist"] == "Test Artist"
|
||||
|
||||
def test_get_nonexistent_job_returns_404(self, mock_worker_service):
|
||||
def test_get_nonexistent_job_returns_404(self, mock_worker_service, auth_headers):
|
||||
"""Test getting non-existent job returns 404."""
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_manager.get_job.return_value = None
|
||||
@@ -133,7 +133,8 @@ class TestCreateJob:
|
||||
"""Test creating job with URL returns 200."""
|
||||
response = client.post(
|
||||
"/api/jobs",
|
||||
json={"url": "https://youtube.com/watch?v=test123"}
|
||||
json={"url": "https://youtube.com/watch?v=test123"},
|
||||
headers=auth_headers
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
@@ -141,7 +142,8 @@ class TestCreateJob:
|
||||
"""Test create response contains job_id."""
|
||||
response = client.post(
|
||||
"/api/jobs",
|
||||
json={"url": "https://youtube.com/watch?v=test"}
|
||||
json={"url": "https://youtube.com/watch?v=test"},
|
||||
headers=auth_headers
|
||||
)
|
||||
data = response.json()
|
||||
assert "job_id" in data
|
||||
@@ -154,7 +156,8 @@ class TestCreateJob:
|
||||
"url": "https://youtube.com/watch?v=test",
|
||||
"artist": "Test Artist",
|
||||
"title": "Test Song"
|
||||
}
|
||||
},
|
||||
headers=auth_headers
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
@@ -167,7 +170,7 @@ class TestDeleteJob:
|
||||
response = client.delete("/api/jobs/test123", headers=auth_headers)
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_delete_nonexistent_job(self, mock_worker_service):
|
||||
def test_delete_nonexistent_job(self, mock_worker_service, auth_headers):
|
||||
"""Test deleting non-existent job."""
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_manager.delete_job.return_value = False
|
||||
@@ -194,7 +197,8 @@ class TestCancelJob:
|
||||
mock_job_manager.cancel_job.return_value = mock_job
|
||||
response = client.post(
|
||||
"/api/jobs/test123/cancel",
|
||||
json={}
|
||||
json={},
|
||||
headers=auth_headers
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
@@ -222,7 +226,8 @@ class TestSubmitCorrections:
|
||||
"lines": [],
|
||||
"metadata": {"source": "test"}
|
||||
}
|
||||
}
|
||||
},
|
||||
headers=auth_headers
|
||||
)
|
||||
# Should be 200 or validation error
|
||||
assert response.status_code in [200, 400, 422]
|
||||
@@ -235,7 +240,8 @@ class TestSelectInstrumental:
|
||||
"""Test instrumental selection requires selection field."""
|
||||
response = client.post(
|
||||
"/api/jobs/test123/select-instrumental",
|
||||
json={} # Missing selection field
|
||||
json={}, # Missing selection field
|
||||
headers=auth_headers
|
||||
)
|
||||
# Missing field should cause validation error
|
||||
assert response.status_code == 422
|
||||
|
||||
@@ -16,12 +16,20 @@ from unittest.mock import Mock, MagicMock, patch, AsyncMock
|
||||
from io import BytesIO
|
||||
|
||||
# Test the remote CLI's style parsing
|
||||
# Skip this class if flacfetch is not properly installed (remote_cli depends on it)
|
||||
try:
|
||||
from karaoke_gen.utils.remote_cli import RemoteKaraokeClient, Config
|
||||
_remote_cli_available = True
|
||||
except ImportError:
|
||||
_remote_cli_available = False
|
||||
|
||||
|
||||
@pytest.mark.skipif(not _remote_cli_available, reason="flacfetch not properly installed")
|
||||
class TestRemoteCLIStyleParsing:
|
||||
"""Test that remote CLI correctly parses style_params.json."""
|
||||
|
||||
def test_parse_style_params_extracts_file_paths(self):
|
||||
"""Test that _parse_style_params extracts all file references."""
|
||||
from karaoke_gen.utils.remote_cli import RemoteKaraokeClient, Config
|
||||
|
||||
# Create a mock style_params.json
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
@@ -79,7 +87,6 @@ class TestRemoteCLIStyleParsing:
|
||||
|
||||
def test_parse_style_params_handles_missing_files(self):
|
||||
"""Test that _parse_style_params ignores non-existent files."""
|
||||
from karaoke_gen.utils.remote_cli import RemoteKaraokeClient, Config
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
style_params = {
|
||||
|
||||
@@ -10,6 +10,14 @@ from io import BytesIO
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def upload_auth_headers():
|
||||
"""Auth headers for file upload tests (no Content-Type, let multipart work)."""
|
||||
return {
|
||||
"Authorization": "Bearer test-admin-token"
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job():
|
||||
"""Create a standard mock job."""
|
||||
@@ -47,7 +55,7 @@ def mock_services(mock_job):
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(mock_services, mock_auth_service):
|
||||
def client(mock_services):
|
||||
"""Create TestClient with mocked dependencies."""
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
@@ -65,37 +73,41 @@ def client(mock_services, mock_auth_service):
|
||||
class TestFileUploadEndpoint:
|
||||
"""Tests for POST /api/jobs/upload."""
|
||||
|
||||
def test_upload_flac_returns_200(self, client, mock_services, auth_headers):
|
||||
def test_upload_flac_returns_200(self, client, mock_services, upload_auth_headers):
|
||||
"""Test uploading FLAC file returns 200."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.flac", BytesIO(b"fake audio"), "audio/flac")},
|
||||
data={"artist": "Test Artist", "title": "Test Song"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_upload_mp3_returns_200(self, client, mock_services, auth_headers):
|
||||
def test_upload_mp3_returns_200(self, client, mock_services, upload_auth_headers):
|
||||
"""Test uploading MP3 file returns 200."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.mp3", BytesIO(b"fake audio"), "audio/mpeg")},
|
||||
data={"artist": "Test Artist", "title": "Test Song"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_upload_wav_returns_200(self, client, mock_services, auth_headers):
|
||||
def test_upload_wav_returns_200(self, client, mock_services, upload_auth_headers):
|
||||
"""Test uploading WAV file returns 200."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.wav", BytesIO(b"fake audio"), "audio/wav")},
|
||||
data={"artist": "Test Artist", "title": "Test Song"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_upload_returns_job_id(self, client, mock_services, auth_headers):
|
||||
def test_upload_returns_job_id(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload response contains job_id."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.flac", BytesIO(b"fake audio"), "audio/flac")},
|
||||
data={"artist": "Test", "title": "Song"}
|
||||
)
|
||||
@@ -103,10 +115,11 @@ class TestFileUploadEndpoint:
|
||||
assert "job_id" in data
|
||||
assert data["status"] == "success"
|
||||
|
||||
def test_upload_returns_filename(self, client, mock_services, auth_headers):
|
||||
def test_upload_returns_filename(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload response contains original filename."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("my_song.flac", BytesIO(b"fake audio"), "audio/flac")},
|
||||
data={"artist": "Test", "title": "Song"}
|
||||
)
|
||||
@@ -114,84 +127,93 @@ class TestFileUploadEndpoint:
|
||||
assert "filename" in data
|
||||
assert data["filename"] == "my_song.flac"
|
||||
|
||||
def test_upload_rejects_txt_file(self, client, mock_services, auth_headers):
|
||||
def test_upload_rejects_txt_file(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload rejects text files."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.txt", BytesIO(b"not audio"), "text/plain")},
|
||||
data={"artist": "Test", "title": "Song"}
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
def test_upload_rejects_pdf_file(self, client, mock_services, auth_headers):
|
||||
def test_upload_rejects_pdf_file(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload rejects PDF files."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("doc.pdf", BytesIO(b"pdf content"), "application/pdf")},
|
||||
data={"artist": "Test", "title": "Song"}
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
def test_upload_rejects_exe_file(self, client, mock_services, auth_headers):
|
||||
def test_upload_rejects_exe_file(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload rejects executable files."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("app.exe", BytesIO(b"exe content"), "application/octet-stream")},
|
||||
data={"artist": "Test", "title": "Song"}
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
def test_upload_requires_artist(self, client, mock_services, auth_headers):
|
||||
def test_upload_requires_artist(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload requires artist field."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.flac", BytesIO(b"audio"), "audio/flac")},
|
||||
data={"title": "Song"} # Missing artist
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_upload_requires_title(self, client, mock_services, auth_headers):
|
||||
def test_upload_requires_title(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload requires title field."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.flac", BytesIO(b"audio"), "audio/flac")},
|
||||
data={"artist": "Artist"} # Missing title
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_upload_requires_file(self, client, mock_services, auth_headers):
|
||||
def test_upload_requires_file(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload requires file."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
data={"artist": "Artist", "title": "Song"}
|
||||
# Missing file
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_upload_triggers_workers(self, client, mock_services, auth_headers):
|
||||
def test_upload_triggers_workers(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload triggers audio and lyrics workers."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.flac", BytesIO(b"audio"), "audio/flac")},
|
||||
data={"artist": "Test", "title": "Song"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
# Workers should be triggered in background
|
||||
|
||||
def test_upload_creates_job(self, client, mock_services, auth_headers):
|
||||
def test_upload_creates_job(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload creates job in job manager."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.flac", BytesIO(b"audio"), "audio/flac")},
|
||||
data={"artist": "Test", "title": "Song"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
mock_services['job_manager'].create_job.assert_called()
|
||||
|
||||
def test_upload_stores_file_to_gcs(self, client, mock_services, auth_headers):
|
||||
def test_upload_stores_file_to_gcs(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload stores file to GCS."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.flac", BytesIO(b"audio"), "audio/flac")},
|
||||
data={"artist": "Test", "title": "Song"}
|
||||
)
|
||||
@@ -202,28 +224,31 @@ class TestFileUploadEndpoint:
|
||||
class TestUploadValidation:
|
||||
"""Tests for upload validation logic."""
|
||||
|
||||
def test_upload_accepts_m4a(self, client, mock_services, auth_headers):
|
||||
def test_upload_accepts_m4a(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload accepts M4A files."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.m4a", BytesIO(b"audio"), "audio/mp4")},
|
||||
data={"artist": "Test", "title": "Song"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_upload_accepts_ogg(self, client, mock_services, auth_headers):
|
||||
def test_upload_accepts_ogg(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload accepts OGG files."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.ogg", BytesIO(b"audio"), "audio/ogg")},
|
||||
data={"artist": "Test", "title": "Song"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_upload_accepts_aac(self, client, mock_services, auth_headers):
|
||||
def test_upload_accepts_aac(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload accepts AAC files."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.aac", BytesIO(b"audio"), "audio/aac")},
|
||||
data={"artist": "Test", "title": "Song"}
|
||||
)
|
||||
|
||||
+1
-1
@@ -76,7 +76,7 @@ steps:
|
||||
--max-instances 50 \
|
||||
--min-instances 0 \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=$PROJECT_ID,GCS_BUCKET_NAME=karaoke-gen-storage-$PROJECT_ID,FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,AUDIO_SEPARATOR_API_URL=https://nomadkaraoke--audio-separator-api.modal.run,KARAOKE_GEN_VERSION=$$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1" \
|
||||
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,REDACTED_API_KEY=redacted-api-key:latest,OPS_API_KEY=ops-api-key:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest"
|
||||
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest"
|
||||
|
||||
images:
|
||||
- 'us-central1-docker.pkg.dev/$PROJECT_ID/karaoke-repo/karaoke-backend:latest'
|
||||
|
||||
@@ -21,6 +21,7 @@ coverage:
|
||||
default:
|
||||
target: 70% # New code should also meet 70%
|
||||
threshold: 5% # More lenient for patches
|
||||
only_pulls: true # Only run on PRs, not on main branch pushes
|
||||
|
||||
# Disable PR comments entirely since we're satisfied with 70%+ coverage
|
||||
# Status checks will still appear on the PR
|
||||
|
||||
@@ -681,8 +681,10 @@ The karaoke-gen system supports multiple interfaces to the same core functionali
|
||||
| `dropbox-oauth-credentials` | ✅ | Dropbox API OAuth tokens |
|
||||
| `gdrive-service-account` | ✅ | Google Drive service account |
|
||||
| `discord-webhook-url` | ✅ | Default Discord webhook |
|
||||
| `redacted-api-key` | ⏳ | Redacted tracker API key (flacfetch audio search) |
|
||||
| `ops-api-key` | ⏳ | OPS/Orpheus tracker API key (flacfetch audio search) |
|
||||
| `red-api-key` | ⏳ | RED tracker API key (flacfetch audio search) |
|
||||
| `red-api-url` | ⏳ | RED tracker base URL (flacfetch audio search) |
|
||||
| `ops-api-key` | ⏳ | OPS tracker API key (flacfetch audio search) |
|
||||
| `ops-api-url` | ⏳ | OPS tracker base URL (flacfetch audio search) |
|
||||
|
||||
### Default Distribution Settings
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ This violates DRY and caused a bug where the backend's import wasn't updated whe
|
||||
| Component | Local (`audio_fetcher.py`) | Backend (`audio_search_service.py`) |
|
||||
|-----------|---------------------------|-------------------------------------|
|
||||
| `_get_manager()` | ✅ 40 lines | ❌ 35 lines (copy) |
|
||||
| Provider setup | ✅ Redacted, OPS, YouTube | ❌ Same, diverged |
|
||||
| Provider setup | ✅ RED, OPS, YouTube | ❌ Same, diverged |
|
||||
| `search()` | ✅ Full implementation | ❌ Similar, diverged |
|
||||
| `download()` | ✅ With downloaders | ⚠️ Different, simpler |
|
||||
| `AudioSearchResult` | ✅ Dataclass | ❌ Duplicate, different fields |
|
||||
@@ -64,11 +64,13 @@ class AudioSearchService:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
redacted_api_key: Optional[str] = None,
|
||||
red_api_key: Optional[str] = None,
|
||||
red_api_url: Optional[str] = None,
|
||||
ops_api_key: Optional[str] = None,
|
||||
):
|
||||
self._fetcher = FlacFetcher(
|
||||
redacted_api_key=redacted_api_key,
|
||||
red_api_key=red_api_key,
|
||||
red_api_url=red_api_url,
|
||||
ops_api_key=ops_api_key,
|
||||
)
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ This bug existed in production code but wasn't caught by automated tests because
|
||||
|
||||
### Bug #2: Missing `gcs_path` Parameter in API Route (Fixed 2025-12-22)
|
||||
```
|
||||
Error handling audio selection: Error selecting audio: {'detail': "Download failed: [Errno 2] No such file or directory: '/var/lib/transmission-daemon/downloads/Avril Lavigne - Unwanted (Album, 2002, CD, 16bit, Redacted).flac'"}
|
||||
Error handling audio selection: Error selecting audio: {'detail': "Download failed: [Errno 2] No such file or directory: '/var/lib/transmission-daemon/downloads/Avril Lavigne - Unwanted (Album, 2002, CD, 16bit, RED).flac'"}
|
||||
```
|
||||
|
||||
The backend API route `_download_and_start_processing` in `audio_search.py` was not passing the `gcs_path` parameter to `audio_search_service.download()`. Without this parameter, the remote `flacfetch` VM would download the file locally but not upload it to GCS. The backend then tried to open the VM's local path (`/var/lib/transmission-daemon/downloads/...`) which doesn't exist on Cloud Run.
|
||||
@@ -30,7 +30,7 @@ The backend API route `_download_and_start_processing` in `audio_search.py` was
|
||||
|
||||
## Root Cause Analysis
|
||||
|
||||
1. **Missing remote code path tests**: The download routing logic for `provider in ["Redacted", "OPS"]` was never exercised
|
||||
1. **Missing remote code path tests**: The download routing logic for `provider in ["RED", "OPS"]` was never exercised
|
||||
2. **State not set up for remote scenario**: Tests never configured `_remote_search_id` and `_remote_client` together
|
||||
3. **`FlacfetchClient` had zero tests**: The entire HTTP client was untested
|
||||
4. **Tests mocked at wrong level**: Tests mocked `service._fetcher` completely, bypassing the routing logic
|
||||
@@ -126,7 +126,7 @@ def test_upload_handles_network_error(self):
|
||||
def test_download_routes_to_remote_for_torrent_providers(self):
|
||||
service._remote_client = Mock()
|
||||
service._remote_search_id = "search_123"
|
||||
service._cached_results = [result_with_provider_redacted]
|
||||
service._cached_results = [result_with_provider_red]
|
||||
|
||||
service.download(0, "/tmp")
|
||||
|
||||
@@ -156,7 +156,7 @@ class TestAudioSearchApiRouteDownload:
|
||||
# Mock the audio_search_service.download to capture the call
|
||||
mock_audio_search_service = Mock()
|
||||
mock_audio_search_service.download.return_value = AudioDownloadResult(
|
||||
filepath="gs://bucket/path.flac", artist="A", title="T", provider="Redacted", quality="FLAC"
|
||||
filepath="gs://bucket/path.flac", artist="A", title="T", provider="RED", quality="FLAC"
|
||||
)
|
||||
|
||||
result = await _download_and_start_processing(job_id="job1", ...)
|
||||
|
||||
@@ -14,7 +14,7 @@ BitTorrent downloads don't work reliably in Cloud Run due to:
|
||||
- DHT peer discovery blocked
|
||||
- Container timeout limits (max 60 min)
|
||||
|
||||
This prevents downloading lossless audio from private trackers (Redacted, OPS) via the remote backend.
|
||||
This prevents downloading lossless audio from private trackers (RED, OPS) via the remote backend.
|
||||
|
||||
## Solution Overview
|
||||
|
||||
@@ -41,7 +41,7 @@ This approach provides clean separation of concerns:
|
||||
│ │ AudioSearchService │ ────────────▶ │ POST /search │ │
|
||||
│ │ │ │ │ │
|
||||
│ │ │ 2. Results │ Providers: │ │
|
||||
│ │ │ ◀──────────── │ • Redacted (FLAC) │ │
|
||||
│ │ │ ◀──────────── │ • RED (FLAC) │ │
|
||||
│ │ │ │ • OPS (FLAC) │ │
|
||||
│ │ │ 3. Download │ • YouTube (fallback) │ │
|
||||
│ │ │ ────────────▶ │ │ │
|
||||
@@ -147,7 +147,7 @@ POST /search
|
||||
"index": 0,
|
||||
"title": "Waterloo",
|
||||
"artist": "ABBA",
|
||||
"provider": "Redacted",
|
||||
"provider": "RED",
|
||||
"quality": "FLAC 16bit CD",
|
||||
"seeders": 45,
|
||||
"size_bytes": 31457280,
|
||||
@@ -184,7 +184,7 @@ GET /download/{download_id}/status
|
||||
"peers": 3,
|
||||
"download_speed_kbps": 1250.5,
|
||||
"eta_seconds": 120,
|
||||
"provider": "Redacted",
|
||||
"provider": "RED",
|
||||
"title": "ABBA - Waterloo",
|
||||
"output_path": null, # Set when complete (local path)
|
||||
"gcs_path": null, # Set when uploaded to GCS
|
||||
@@ -248,7 +248,7 @@ GET /health
|
||||
"free_gb": 12
|
||||
},
|
||||
"providers": {
|
||||
"redacted": true,
|
||||
"red": true,
|
||||
"ops": true,
|
||||
"youtube": true
|
||||
}
|
||||
@@ -418,7 +418,8 @@ pip install -e ".[api]"
|
||||
|
||||
# Get secrets from metadata/Secret Manager
|
||||
FLACFETCH_API_KEY=$(gcloud secrets versions access latest --secret=flacfetch-api-key)
|
||||
REDACTED_API_KEY=$(gcloud secrets versions access latest --secret=redacted-api-key)
|
||||
RED_API_KEY=$(gcloud secrets versions access latest --secret=red-api-key)
|
||||
RED_API_URL=$(gcloud secrets versions access latest --secret=red-api-url)
|
||||
OPS_API_KEY=$(gcloud secrets versions access latest --secret=ops-api-key)
|
||||
GCS_BUCKET=$(curl -s "http://metadata.google.internal/computeMetadata/v1/instance/attributes/gcs-bucket" -H "Metadata-Flavor: Google")
|
||||
|
||||
@@ -433,7 +434,8 @@ Type=simple
|
||||
User=root
|
||||
WorkingDirectory=/opt/flacfetch
|
||||
Environment="FLACFETCH_API_KEY=${FLACFETCH_API_KEY}"
|
||||
Environment="REDACTED_API_KEY=${REDACTED_API_KEY}"
|
||||
Environment="RED_API_KEY=${RED_API_KEY}"
|
||||
Environment="RED_API_URL=${RED_API_URL}"
|
||||
Environment="OPS_API_KEY=${OPS_API_KEY}"
|
||||
Environment="GCS_BUCKET=${GCS_BUCKET}"
|
||||
Environment="FLACFETCH_KEEP_SEEDING=true"
|
||||
@@ -650,7 +652,8 @@ FLACFETCH_API_PORT=8080 # Default: 8080
|
||||
FLACFETCH_API_HOST=0.0.0.0 # Default: 0.0.0.0
|
||||
|
||||
# Tracker API Keys
|
||||
REDACTED_API_KEY=<key> # For Redacted provider
|
||||
RED_API_KEY=<key> # For RED provider
|
||||
RED_API_URL=<url> # For RED provider base URL
|
||||
OPS_API_KEY=<key> # For OPS provider
|
||||
|
||||
# GCS Upload (optional)
|
||||
@@ -702,7 +705,7 @@ If flacfetch service fails:
|
||||
## Success Criteria
|
||||
|
||||
- [x] Flacfetch HTTP API accepts search requests and returns results
|
||||
- [x] Downloads complete successfully for Redacted/OPS sources
|
||||
- [x] Downloads complete successfully for RED/OPS sources
|
||||
- [x] Downloaded files upload to GCS automatically
|
||||
- [x] Torrents continue seeding after download
|
||||
- [x] Disk cleanup triggers automatically when space is low
|
||||
@@ -739,7 +742,7 @@ If flacfetch service fails:
|
||||
- GCP VM: `flacfetch-service` (e2-small, us-central1-a)
|
||||
- Static IP: `104.198.214.26` (whitelisted with trackers)
|
||||
- Firewall rules: TCP/UDP 51413 (BitTorrent), TCP 8080 (API)
|
||||
- Secrets: `flacfetch-api-key`, `redacted-api-key`, `ops-api-key`, `flacfetch-api-url`
|
||||
- Secrets: `flacfetch-api-key`, `red-api-key`, `red-api-url`, `ops-api-key`, `ops-api-url`, `flacfetch-api-url`
|
||||
- GitHub Actions deployer has `compute.admin` and `compute.osLogin` roles
|
||||
|
||||
#### Phase 3: Backend Integration ✅
|
||||
@@ -756,7 +759,7 @@ If flacfetch service fails:
|
||||
|
||||
#### Phase 5: CLI & Testing ✅
|
||||
- `flacfetch-remote` CLI added for testing remote API
|
||||
- Downloads file locally with descriptive filenames (e.g., `Artist - Title (Album, 2022, CD, 16bit, Redacted).flac`)
|
||||
- Downloads file locally with descriptive filenames (e.g., `Artist - Title (Album, 2022, CD, 16bit, RED).flac`)
|
||||
- 70%+ unit test coverage requirement enforced
|
||||
- Integration tests for API routes
|
||||
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
# Instrumental Review: Original Audio Tab Support
|
||||
|
||||
**Date:** 2025-12-22
|
||||
**Version:** 0.75.12
|
||||
|
||||
## Summary
|
||||
|
||||
Added support for an "Original Audio" tab in the Instrumental Review UI, allowing users to compare the original audio (with lead vocals) alongside the backing vocals, clean instrumental, and instrumental with backing vocals options. This helps users make better decisions about whether certain audio regions are actually backing vocals or need to be muted.
|
||||
|
||||
## Problem
|
||||
|
||||
When reviewing backing vocals in the Instrumental Review UI, users couldn't hear the original full song to compare and determine whether detected regions were actually backing vocals or if they needed to be muted. This made it difficult to make informed decisions about the instrumental selection.
|
||||
|
||||
## Solution
|
||||
|
||||
The Instrumental Review HTML UI already had built-in support for displaying an "Original Audio" tab when `hasOriginal` flag was set, but this feature was not being activated because the `original_audio_path` parameter was not being passed to the `InstrumentalReviewServer`.
|
||||
|
||||
### Changes Made
|
||||
|
||||
1. **`karaoke_gen/utils/gen_cli.py`** (lines 203-217, 239):
|
||||
- Added code to locate the original audio file from the track data (`track.get("input_audio_wav")`)
|
||||
- Resolved the path relative to the track directory
|
||||
- Passed `original_audio_path` parameter when initializing `InstrumentalReviewServer`
|
||||
|
||||
2. **`scripts/test-instrumental-review.py`**:
|
||||
- Added optional `--original` command-line argument
|
||||
- Added validation for the original audio file path
|
||||
- Passed `original_audio_path` parameter to `InstrumentalReviewServer`
|
||||
|
||||
3. **`tests/unit/test_instrumental_review/test_server.py`**:
|
||||
- Added `test_server_initialization_with_original_audio()` to verify server properly stores the original audio path
|
||||
- Added `test_get_analysis_with_original_audio()` to verify the API properly exposes `has_original` flag and original audio URL
|
||||
|
||||
4. **`pyproject.toml`**:
|
||||
- Bumped version from 0.75.11 to 0.75.12
|
||||
|
||||
## How It Works
|
||||
|
||||
### Backend Flow
|
||||
|
||||
1. When the instrumental review is triggered, the system:
|
||||
- Locates the original audio file (`input_audio_wav` from the track data)
|
||||
- Resolves the path relative to the working directory
|
||||
- Passes it to `InstrumentalReviewServer` as `original_audio_path`
|
||||
|
||||
2. The server exposes the original audio through:
|
||||
- `/api/audio/original` endpoint (serves the audio file)
|
||||
- `has_original: true` flag in the analysis response
|
||||
|
||||
### Frontend Flow
|
||||
|
||||
The HTML UI (already implemented in `karaoke_gen/instrumental_review/static/index.html`):
|
||||
- Checks `hasOriginal` flag from the API
|
||||
- Conditionally shows "Original" tab in the audio toggle group (line 697-699)
|
||||
- Provides audio player that switches between:
|
||||
- **Original Audio** - Full song with lead vocals
|
||||
- **Backing Vocals Only** - Isolated backing vocals
|
||||
- **Pure Instrumental** - Clean instrumental (no vocals)
|
||||
- **Instrumental + Backing** - Instrumental with backing vocals included
|
||||
- **Custom** - User-created muted regions
|
||||
|
||||
### Usage
|
||||
|
||||
When running the local CLI:
|
||||
```bash
|
||||
karaoke-gen "Artist" "Song Title"
|
||||
```
|
||||
|
||||
During the instrumental review phase, the UI will now automatically show the "Original Audio" tab if the original audio file is available.
|
||||
|
||||
For testing:
|
||||
```bash
|
||||
python scripts/test-instrumental-review.py \
|
||||
backing_vocals.flac \
|
||||
clean_instrumental.flac \
|
||||
--with_backing instrumental_with_backing.flac \
|
||||
--original original.wav
|
||||
```
|
||||
|
||||
## Files Modified
|
||||
|
||||
- `karaoke_gen/utils/gen_cli.py` - Added original audio path detection and passing
|
||||
- `scripts/test-instrumental-review.py` - Added --original argument support
|
||||
- `tests/unit/test_instrumental_review/test_server.py` - Added tests for original audio functionality
|
||||
- `pyproject.toml` - Version bump
|
||||
|
||||
## Testing
|
||||
|
||||
All 139 tests in `tests/unit/test_instrumental_review/` pass, including:
|
||||
- `TestServerInitialization::test_server_initialization_with_original_audio` - Verifies server stores original audio path
|
||||
- `TestServerAPIEndpoints::test_get_analysis_with_original_audio` - Verifies API exposes original audio properly
|
||||
|
||||
## Benefits
|
||||
|
||||
1. **Better Decision Making**: Users can hear the full original song to compare against backing vocals
|
||||
2. **Improved Accuracy**: Easier to identify if detected regions are truly backing vocals or artifacts
|
||||
3. **No UI Changes Required**: Leveraged existing UI capabilities that were already built-in
|
||||
4. **Backward Compatible**: If no original audio is provided, the tab simply doesn't appear
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
- The original audio feature is optional - if the file is not available, the tab won't appear
|
||||
- The server already had the route handler for serving original audio (`/api/audio/original`)
|
||||
- The HTML UI already had the conditional rendering logic for the "Original" tab
|
||||
- The main change was ensuring the `original_audio_path` parameter was properly populated and passed through
|
||||
|
||||
-1
Submodule flacfetch deleted from 35ae8994b8.
@@ -95,9 +95,13 @@ echo -n "your-genius-key" | \
|
||||
echo -n "https://your-modal-url" | \
|
||||
gcloud secrets versions add audio-separator-api-url --data-file=-
|
||||
|
||||
# Add Redacted API key (for flacfetch audio search - private tracker)
|
||||
echo -n "your-redacted-api-key" | \
|
||||
gcloud secrets versions add redacted-api-key --data-file=-
|
||||
# Add RED API key (for flacfetch audio search - private tracker)
|
||||
echo -n "your-red-api-key" | \
|
||||
gcloud secrets versions add red-api-key --data-file=-
|
||||
|
||||
# Add RED API URL (for flacfetch audio search - private tracker)
|
||||
echo -n "https://your.red.url" | \
|
||||
gcloud secrets versions add red-api-url --data-file=-
|
||||
|
||||
# Add OPS API key (for flacfetch audio search - private tracker)
|
||||
echo -n "your-ops-api-key" | \
|
||||
|
||||
@@ -246,13 +246,44 @@ workload_identity_provider = gcp.iam.WorkloadIdentityPoolProvider(
|
||||
)
|
||||
|
||||
# Allow GitHub Actions to impersonate the service account
|
||||
# Both karaoke-gen and flacfetch repos need access
|
||||
github_actions_wif_binding = gcp.serviceaccount.IAMBinding(
|
||||
"github-actions-wif-binding",
|
||||
service_account_id=github_actions_sa.name,
|
||||
role="roles/iam.workloadIdentityUser",
|
||||
members=[workload_identity_pool.name.apply(
|
||||
lambda pool_name: f"principalSet://iam.googleapis.com/{pool_name}/attribute.repository/nomadkaraoke/karaoke-gen"
|
||||
)],
|
||||
members=[
|
||||
workload_identity_pool.name.apply(
|
||||
lambda pool_name: f"principalSet://iam.googleapis.com/{pool_name}/attribute.repository/nomadkaraoke/karaoke-gen"
|
||||
),
|
||||
workload_identity_pool.name.apply(
|
||||
lambda pool_name: f"principalSet://iam.googleapis.com/{pool_name}/attribute.repository/nomadkaraoke/flacfetch"
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
# Grant Compute Engine permissions for flacfetch VM deployment
|
||||
# Needed for gcloud compute ssh to update the VM
|
||||
github_actions_compute_admin = gcp.projects.IAMMember(
|
||||
"github-actions-compute-admin",
|
||||
project=project_id,
|
||||
role="roles/compute.instanceAdmin.v1",
|
||||
member=github_actions_sa.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
# Grant OS Login permissions for SSH access
|
||||
github_actions_os_login = gcp.projects.IAMMember(
|
||||
"github-actions-os-login",
|
||||
project=project_id,
|
||||
role="roles/compute.osLogin",
|
||||
member=github_actions_sa.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
# Grant IAP tunnel user for secure SSH (used by gcloud compute ssh)
|
||||
github_actions_iap_tunnel = gcp.projects.IAMMember(
|
||||
"github-actions-iap-tunnel",
|
||||
project=project_id,
|
||||
role="roles/iap.tunnelResourceAccessor",
|
||||
member=github_actions_sa.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
# ==================== Cloud Tasks Queues (Phase 1 Scalability) ====================
|
||||
@@ -455,10 +486,19 @@ audio_separator_secret = secretmanager.Secret(
|
||||
),
|
||||
)
|
||||
|
||||
# Redacted API Key Secret (for flacfetch audio search)
|
||||
redacted_api_key_secret = secretmanager.Secret(
|
||||
"redacted-api-key",
|
||||
secret_id="redacted-api-key",
|
||||
# RED API Key Secret (for flacfetch audio search)
|
||||
red_api_key_secret = secretmanager.Secret(
|
||||
"red-api-key",
|
||||
secret_id="red-api-key",
|
||||
replication=secretmanager.SecretReplicationArgs(
|
||||
auto=secretmanager.SecretReplicationAutoArgs(),
|
||||
),
|
||||
)
|
||||
|
||||
# RED API URL Secret (for flacfetch audio search)
|
||||
red_api_url_secret = secretmanager.Secret(
|
||||
"red-api-url",
|
||||
secret_id="red-api-url",
|
||||
replication=secretmanager.SecretReplicationArgs(
|
||||
auto=secretmanager.SecretReplicationAutoArgs(),
|
||||
),
|
||||
@@ -473,6 +513,15 @@ ops_api_key_secret = secretmanager.Secret(
|
||||
),
|
||||
)
|
||||
|
||||
# OPS API URL Secret (for flacfetch audio search)
|
||||
ops_api_url_secret = secretmanager.Secret(
|
||||
"ops-api-url",
|
||||
secret_id="ops-api-url",
|
||||
replication=secretmanager.SecretReplicationArgs(
|
||||
auto=secretmanager.SecretReplicationAutoArgs(),
|
||||
),
|
||||
)
|
||||
|
||||
# Create Cloud Run Domain Mapping
|
||||
# Maps api.nomadkaraoke.com to the karaoke-backend service
|
||||
domain_mapping = cloudrun.DomainMapping(
|
||||
@@ -658,8 +707,10 @@ pip install -e ".[api]"
|
||||
# Get secrets from Secret Manager
|
||||
echo "Fetching secrets from Secret Manager..."
|
||||
FLACFETCH_API_KEY=$(gcloud secrets versions access latest --secret=flacfetch-api-key 2>/dev/null || echo "")
|
||||
REDACTED_API_KEY=$(gcloud secrets versions access latest --secret=redacted-api-key 2>/dev/null || echo "")
|
||||
RED_API_KEY=$(gcloud secrets versions access latest --secret=red-api-key 2>/dev/null || echo "")
|
||||
RED_API_URL=$(gcloud secrets versions access latest --secret=red-api-url 2>/dev/null || echo "")
|
||||
OPS_API_KEY=$(gcloud secrets versions access latest --secret=ops-api-key 2>/dev/null || echo "")
|
||||
OPS_API_URL=$(gcloud secrets versions access latest --secret=ops-api-url 2>/dev/null || echo "")
|
||||
|
||||
# Get bucket name from project metadata
|
||||
GCS_BUCKET=$(gcloud compute project-info describe --format='value(commonInstanceMetadata.items.gcs-bucket)' 2>/dev/null || echo "")
|
||||
@@ -684,8 +735,10 @@ Type=simple
|
||||
User=root
|
||||
WorkingDirectory=/opt/flacfetch
|
||||
Environment="FLACFETCH_API_KEY=${FLACFETCH_API_KEY}"
|
||||
Environment="REDACTED_API_KEY=${REDACTED_API_KEY}"
|
||||
Environment="RED_API_KEY=${RED_API_KEY}"
|
||||
Environment="RED_API_URL=${RED_API_URL}"
|
||||
Environment="OPS_API_KEY=${OPS_API_KEY}"
|
||||
Environment="OPS_API_URL=${OPS_API_URL}"
|
||||
Environment="GCS_BUCKET=${GCS_BUCKET}"
|
||||
Environment="FLACFETCH_KEEP_SEEDING=true"
|
||||
Environment="FLACFETCH_MIN_FREE_GB=5"
|
||||
|
||||
@@ -252,8 +252,10 @@ class FlacFetchAudioFetcher(AudioFetcher):
|
||||
def __init__(
|
||||
self,
|
||||
logger: Optional[logging.Logger] = None,
|
||||
redacted_api_key: Optional[str] = None,
|
||||
red_api_key: Optional[str] = None,
|
||||
red_api_url: Optional[str] = None,
|
||||
ops_api_key: Optional[str] = None,
|
||||
ops_api_url: Optional[str] = None,
|
||||
provider_priority: Optional[List[str]] = None,
|
||||
):
|
||||
"""
|
||||
@@ -261,13 +263,17 @@ class FlacFetchAudioFetcher(AudioFetcher):
|
||||
|
||||
Args:
|
||||
logger: Logger instance for output
|
||||
redacted_api_key: API key for Redacted tracker (optional)
|
||||
red_api_key: API key for RED tracker (optional)
|
||||
red_api_url: Base URL for RED tracker API (optional, required if using RED)
|
||||
ops_api_key: API key for OPS tracker (optional)
|
||||
ops_api_url: Base URL for OPS tracker API (optional, required if using OPS)
|
||||
provider_priority: Custom provider priority order (optional)
|
||||
"""
|
||||
self.logger = logger or logging.getLogger(__name__)
|
||||
self._redacted_api_key = redacted_api_key or os.environ.get("REDACTED_API_KEY")
|
||||
self._red_api_key = red_api_key or os.environ.get("RED_API_KEY")
|
||||
self._red_api_url = red_api_url or os.environ.get("RED_API_URL")
|
||||
self._ops_api_key = ops_api_key or os.environ.get("OPS_API_KEY")
|
||||
self._ops_api_url = ops_api_url or os.environ.get("OPS_API_URL")
|
||||
self._provider_priority = provider_priority
|
||||
self._manager = None
|
||||
self._transmission_available = None # Cached result of Transmission check
|
||||
@@ -276,7 +282,7 @@ class FlacFetchAudioFetcher(AudioFetcher):
|
||||
"""
|
||||
Check if Transmission daemon is available for torrent downloads.
|
||||
|
||||
This prevents adding tracker providers (Redacted/OPS) when Transmission
|
||||
This prevents adding tracker providers (RED/OPS) when Transmission
|
||||
isn't running, which would result in search results that can't be downloaded.
|
||||
|
||||
Returns:
|
||||
@@ -340,27 +346,31 @@ class FlacFetchAudioFetcher(AudioFetcher):
|
||||
f"Transmission={transmission_available}, can_use_trackers={can_use_trackers}"
|
||||
)
|
||||
|
||||
if not can_use_trackers and (self._redacted_api_key or self._ops_api_key):
|
||||
if not can_use_trackers and (self._red_api_key or self._ops_api_key):
|
||||
self.logger.warning(
|
||||
"[FlacFetcher] Tracker providers (Redacted/OPS) DISABLED: "
|
||||
"[FlacFetcher] Tracker providers (RED/OPS) DISABLED: "
|
||||
f"TorrentDownloader={has_torrent_downloader}, Transmission={transmission_available}. "
|
||||
"Only YouTube sources will be used."
|
||||
)
|
||||
|
||||
# Add providers and downloaders based on available API keys
|
||||
if self._redacted_api_key and can_use_trackers:
|
||||
from flacfetch.providers.redacted import RedactedProvider
|
||||
# Add providers and downloaders based on available API keys and URLs
|
||||
if self._red_api_key and self._red_api_url and can_use_trackers:
|
||||
from flacfetch.providers.red import REDProvider
|
||||
|
||||
self._manager.add_provider(RedactedProvider(api_key=self._redacted_api_key))
|
||||
self._manager.register_downloader("Redacted", TorrentDownloader())
|
||||
self.logger.info("[FlacFetcher] Added Redacted provider with TorrentDownloader")
|
||||
self._manager.add_provider(REDProvider(api_key=self._red_api_key, base_url=self._red_api_url))
|
||||
self._manager.register_downloader("RED", TorrentDownloader())
|
||||
self.logger.info("[FlacFetcher] Added RED provider with TorrentDownloader")
|
||||
elif self._red_api_key and not self._red_api_url:
|
||||
self.logger.warning("[FlacFetcher] RED_API_KEY set but RED_API_URL not set - RED provider disabled")
|
||||
|
||||
if self._ops_api_key and can_use_trackers:
|
||||
if self._ops_api_key and self._ops_api_url and can_use_trackers:
|
||||
from flacfetch.providers.ops import OPSProvider
|
||||
|
||||
self._manager.add_provider(OPSProvider(api_key=self._ops_api_key))
|
||||
self._manager.add_provider(OPSProvider(api_key=self._ops_api_key, base_url=self._ops_api_url))
|
||||
self._manager.register_downloader("OPS", TorrentDownloader())
|
||||
self.logger.info("[FlacFetcher] Added OPS provider with TorrentDownloader")
|
||||
elif self._ops_api_key and not self._ops_api_url:
|
||||
self.logger.warning("[FlacFetcher] OPS_API_KEY set but OPS_API_URL not set - OPS provider disabled")
|
||||
|
||||
# Always add YouTube as a fallback provider with its downloader
|
||||
self._manager.add_provider(YoutubeProvider())
|
||||
@@ -860,22 +870,28 @@ FlacFetcher = FlacFetchAudioFetcher
|
||||
|
||||
def create_audio_fetcher(
|
||||
logger: Optional[logging.Logger] = None,
|
||||
redacted_api_key: Optional[str] = None,
|
||||
red_api_key: Optional[str] = None,
|
||||
red_api_url: Optional[str] = None,
|
||||
ops_api_key: Optional[str] = None,
|
||||
ops_api_url: Optional[str] = None,
|
||||
) -> AudioFetcher:
|
||||
"""
|
||||
Factory function to create an appropriate AudioFetcher instance.
|
||||
|
||||
Args:
|
||||
logger: Logger instance for output
|
||||
redacted_api_key: API key for Redacted tracker (optional)
|
||||
red_api_key: API key for RED tracker (optional)
|
||||
red_api_url: Base URL for RED tracker API (optional, required if using RED)
|
||||
ops_api_key: API key for OPS tracker (optional)
|
||||
ops_api_url: Base URL for OPS tracker API (optional, required if using OPS)
|
||||
|
||||
Returns:
|
||||
An AudioFetcher instance
|
||||
"""
|
||||
return FlacFetchAudioFetcher(
|
||||
logger=logger,
|
||||
redacted_api_key=redacted_api_key,
|
||||
red_api_key=red_api_key,
|
||||
red_api_url=red_api_url,
|
||||
ops_api_key=ops_api_key,
|
||||
ops_api_url=ops_api_url,
|
||||
)
|
||||
@@ -598,7 +598,22 @@
|
||||
let animationFrameId = null;
|
||||
let currentAudioElement = null; // Track audio element reference for listener management
|
||||
|
||||
const API_BASE = '/api/jobs/local';
|
||||
// Parse URL parameters for cloud mode
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const encodedBaseApiUrl = urlParams.get('baseApiUrl');
|
||||
const instrumentalToken = urlParams.get('instrumentalToken');
|
||||
|
||||
// Determine API base URL - cloud mode uses provided URL, local mode uses default
|
||||
const API_BASE = encodedBaseApiUrl
|
||||
? decodeURIComponent(encodedBaseApiUrl)
|
||||
: '/api/jobs/local';
|
||||
|
||||
// Helper to add token to URL if available
|
||||
function addTokenToUrl(url) {
|
||||
if (!instrumentalToken) return url;
|
||||
const separator = url.includes('?') ? '&' : '?';
|
||||
return `${url}${separator}instrumental_token=${encodeURIComponent(instrumentalToken)}`;
|
||||
}
|
||||
|
||||
// HTML escape helper to prevent XSS
|
||||
function escapeHtml(str) {
|
||||
@@ -617,8 +632,8 @@
|
||||
async function init() {
|
||||
try {
|
||||
const [analysisRes, waveformRes] = await Promise.all([
|
||||
fetch(`${API_BASE}/instrumental-analysis`),
|
||||
fetch(`${API_BASE}/waveform-data?num_points=1000`)
|
||||
fetch(addTokenToUrl(`${API_BASE}/instrumental-analysis`)),
|
||||
fetch(addTokenToUrl(`${API_BASE}/waveform-data?num_points=1000`))
|
||||
]);
|
||||
|
||||
if (!analysisRes.ok) throw new Error('Failed to load analysis');
|
||||
@@ -1120,15 +1135,23 @@
|
||||
}
|
||||
|
||||
function getAudioUrl() {
|
||||
const urls = {
|
||||
original: '/api/audio/original',
|
||||
backing: '/api/audio/backing_vocals',
|
||||
clean: '/api/audio/clean_instrumental',
|
||||
with_backing: '/api/audio/with_backing',
|
||||
custom: '/api/audio/custom_instrumental',
|
||||
uploaded: '/api/audio/uploaded_instrumental'
|
||||
const stemTypes = {
|
||||
original: 'original',
|
||||
backing: 'backing_vocals',
|
||||
clean: 'clean_instrumental',
|
||||
with_backing: 'with_backing',
|
||||
custom: 'custom_instrumental',
|
||||
uploaded: 'uploaded_instrumental'
|
||||
};
|
||||
return urls[activeAudio] || urls.backing;
|
||||
const stemType = stemTypes[activeAudio] || stemTypes.backing;
|
||||
|
||||
// Cloud mode uses /audio-stream/{stem_type}, local mode uses /api/audio/{stem_type}
|
||||
const isCloudMode = !!encodedBaseApiUrl;
|
||||
const url = isCloudMode
|
||||
? `${API_BASE}/audio-stream/${stemType}`
|
||||
: `/api/audio/${stemType}`;
|
||||
|
||||
return addTokenToUrl(url);
|
||||
}
|
||||
|
||||
function formatTime(seconds) {
|
||||
@@ -1295,7 +1318,7 @@
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
|
||||
const response = await fetch(`${API_BASE}/upload-instrumental`, {
|
||||
const response = await fetch(addTokenToUrl(`${API_BASE}/upload-instrumental`), {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
@@ -1354,7 +1377,7 @@
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/create-custom-instrumental`, {
|
||||
const response = await fetch(addTokenToUrl(`${API_BASE}/create-custom-instrumental`), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ mute_regions: muteRegions })
|
||||
@@ -1404,7 +1427,7 @@
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/select-instrumental`, {
|
||||
const response = await fetch(addTokenToUrl(`${API_BASE}/select-instrumental`), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ selection: selectedOption })
|
||||
|
||||
@@ -352,8 +352,8 @@ def create_parser(prog: str = "karaoke-gen") -> argparse.ArgumentParser:
|
||||
)
|
||||
remote_group.add_argument(
|
||||
"--review-ui-url",
|
||||
default=os.environ.get('REVIEW_UI_URL', os.environ.get('LYRICS_REVIEW_UI_URL', 'https://lyrics.nomadkaraoke.com')),
|
||||
help="Lyrics review UI URL. Default: 'https://lyrics.nomadkaraoke.com'. "
|
||||
default=os.environ.get('REVIEW_UI_URL', os.environ.get('LYRICS_REVIEW_UI_URL', 'https://gen.nomadkaraoke.com/lyrics')),
|
||||
help="Lyrics review UI URL. Default: 'https://gen.nomadkaraoke.com/lyrics'. "
|
||||
"Use 'http://localhost:5173' for Vite dev server during development. "
|
||||
"(env: REVIEW_UI_URL or LYRICS_REVIEW_UI_URL)",
|
||||
)
|
||||
|
||||
@@ -200,6 +200,15 @@ def run_instrumental_review(track: dict, logger: logging.Logger) -> str | None:
|
||||
with_backing_path = resolved_path
|
||||
break
|
||||
|
||||
# Find the original audio file (with vocals)
|
||||
original_audio_path = None
|
||||
raw_original_path = track.get("input_audio_wav")
|
||||
if raw_original_path:
|
||||
original_audio_path = _resolve_path_for_cwd(raw_original_path, track_dir)
|
||||
if not os.path.exists(original_audio_path):
|
||||
logger.warning(f"Original audio file not found: {original_audio_path}")
|
||||
original_audio_path = None
|
||||
|
||||
try:
|
||||
logger.info("=== Starting Instrumental Review ===")
|
||||
logger.info(f"Analyzing backing vocals: {backing_vocals_path}")
|
||||
@@ -236,6 +245,7 @@ def run_instrumental_review(track: dict, logger: logging.Logger) -> str | None:
|
||||
backing_vocals_path=backing_vocals_path,
|
||||
clean_instrumental_path=clean_instrumental_path,
|
||||
with_backing_path=with_backing_path,
|
||||
original_audio_path=original_audio_path,
|
||||
)
|
||||
|
||||
# Start server and open browser, wait for selection
|
||||
|
||||
@@ -1398,16 +1398,21 @@ class JobMonitor:
|
||||
base_api_url = f"{self.config.service_url}/api/review/{job_id}"
|
||||
encoded_api_url = urllib.parse.quote(base_api_url, safe='')
|
||||
|
||||
# Try to get audio hash from job data
|
||||
# Try to get audio hash and review token from job data
|
||||
audio_hash = ''
|
||||
review_token = ''
|
||||
try:
|
||||
job_data = self.client.get_job(job_id)
|
||||
audio_hash = job_data.get('audio_hash', '')
|
||||
review_token = job_data.get('review_token', '')
|
||||
except Exception:
|
||||
audio_hash = ''
|
||||
pass
|
||||
|
||||
url = f"{self.config.review_ui_url}/?baseApiUrl={encoded_api_url}"
|
||||
if audio_hash:
|
||||
url += f"&audioHash={audio_hash}"
|
||||
if review_token:
|
||||
url += f"&reviewToken={review_token}"
|
||||
|
||||
self.logger.info(f"Opening lyrics review UI: {url}")
|
||||
self.open_browser(url)
|
||||
@@ -1670,7 +1675,25 @@ class JobMonitor:
|
||||
|
||||
def _open_instrumental_review_and_wait(self, job_id: str) -> None:
|
||||
"""Open browser to instrumental review UI and wait for selection."""
|
||||
review_url = f"{self.config.review_ui_url}/jobs/{job_id}/instrumental-review"
|
||||
# Get instrumental token from job data
|
||||
instrumental_token = ''
|
||||
try:
|
||||
job_data = self.client.get_job(job_id)
|
||||
instrumental_token = job_data.get('instrumental_token', '')
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Build the review URL with API endpoint and token
|
||||
# The instrumental UI is hosted at /instrumental/ on the frontend domain
|
||||
base_api_url = f"{self.config.service_url}/api/jobs/{job_id}"
|
||||
encoded_api_url = urllib.parse.quote(base_api_url, safe='')
|
||||
|
||||
# Use /instrumental/ path on the frontend (same domain as review_ui_url but different path)
|
||||
# review_ui_url is like https://gen.nomadkaraoke.com/lyrics, we want /instrumental/
|
||||
frontend_base = self.config.review_ui_url.rsplit('/', 1)[0] # Remove /lyrics
|
||||
review_url = f"{frontend_base}/instrumental/?baseApiUrl={encoded_api_url}"
|
||||
if instrumental_token:
|
||||
review_url += f"&instrumentalToken={instrumental_token}"
|
||||
|
||||
self.logger.info("")
|
||||
self.logger.info("=" * 60)
|
||||
|
||||
@@ -19,25 +19,27 @@ export default function App() {
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
const encodedApiUrl = params.get('baseApiUrl')
|
||||
const audioHashParam = params.get('audioHash')
|
||||
const reviewTokenParam = params.get('reviewToken')
|
||||
|
||||
if (encodedApiUrl) {
|
||||
const baseApiUrl = decodeURIComponent(encodedApiUrl)
|
||||
setApiClient(new LiveApiClient(baseApiUrl))
|
||||
// Pass reviewToken to LiveApiClient for authentication
|
||||
setApiClient(new LiveApiClient(baseApiUrl, reviewTokenParam || undefined))
|
||||
setIsReadOnly(false)
|
||||
if (audioHashParam) {
|
||||
setAudioHash(audioHashParam)
|
||||
}
|
||||
// Fetch initial data
|
||||
fetchData(baseApiUrl)
|
||||
fetchData(baseApiUrl, reviewTokenParam || undefined)
|
||||
} else {
|
||||
setApiClient(new FileOnlyClient())
|
||||
setIsReadOnly(true)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const fetchData = async (baseUrl: string) => {
|
||||
const fetchData = async (baseUrl: string, reviewToken?: string) => {
|
||||
try {
|
||||
const client = new LiveApiClient(baseUrl)
|
||||
const client = new LiveApiClient(baseUrl, reviewToken)
|
||||
const data = await client.getCorrectionData()
|
||||
// console.log('Full correction data from API:', data)
|
||||
setData(data)
|
||||
|
||||
@@ -35,14 +35,29 @@ interface AddLyricsRequest {
|
||||
}
|
||||
|
||||
export class LiveApiClient implements ApiClient {
|
||||
constructor(private baseUrl: string) {
|
||||
private reviewToken?: string;
|
||||
|
||||
constructor(private baseUrl: string, reviewToken?: string) {
|
||||
this.baseUrl = baseUrl.replace(/\/$/, '')
|
||||
this.reviewToken = reviewToken
|
||||
}
|
||||
|
||||
public isUpdatingHandlers = false;
|
||||
|
||||
/**
|
||||
* Build URL with reviewToken query parameter if available
|
||||
*/
|
||||
private buildUrl(path: string): string {
|
||||
const url = `${this.baseUrl}${path}`
|
||||
if (this.reviewToken) {
|
||||
const separator = url.includes('?') ? '&' : '?'
|
||||
return `${url}${separator}review_token=${encodeURIComponent(this.reviewToken)}`
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
async getCorrectionData(): Promise<CorrectionData> {
|
||||
const response = await fetch(`${this.baseUrl}/correction-data`);
|
||||
const response = await fetch(this.buildUrl('/correction-data'));
|
||||
if (!response.ok) {
|
||||
throw new Error(`API error: ${response.statusText}`);
|
||||
}
|
||||
@@ -64,7 +79,7 @@ export class LiveApiClient implements ApiClient {
|
||||
corrected_segments: data.corrected_segments
|
||||
};
|
||||
|
||||
const response = await fetch(`${this.baseUrl}/complete`, {
|
||||
const response = await fetch(this.buildUrl('/complete'), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -78,7 +93,7 @@ export class LiveApiClient implements ApiClient {
|
||||
}
|
||||
|
||||
getAudioUrl(audioHash: string): string {
|
||||
return `${this.baseUrl}/audio/${audioHash}`
|
||||
return this.buildUrl(`/audio/${audioHash}`)
|
||||
}
|
||||
|
||||
async generatePreviewVideo(data: CorrectionData): Promise<PreviewVideoResponse> {
|
||||
@@ -88,7 +103,7 @@ export class LiveApiClient implements ApiClient {
|
||||
corrected_segments: data.corrected_segments
|
||||
};
|
||||
|
||||
const response = await fetch(`${this.baseUrl}/preview-video`, {
|
||||
const response = await fetch(this.buildUrl('/preview-video'), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -107,7 +122,7 @@ export class LiveApiClient implements ApiClient {
|
||||
}
|
||||
|
||||
getPreviewVideoUrl(previewHash: string): string {
|
||||
return `${this.baseUrl}/preview-video/${previewHash}`;
|
||||
return this.buildUrl(`/preview-video/${previewHash}`);
|
||||
}
|
||||
|
||||
async updateHandlers(enabledHandlers: string[]): Promise<CorrectionData> {
|
||||
@@ -116,7 +131,7 @@ export class LiveApiClient implements ApiClient {
|
||||
console.log('API: Set isUpdatingHandlers to', this.isUpdatingHandlers);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.baseUrl}/handlers`, {
|
||||
const response = await fetch(this.buildUrl('/handlers'), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -147,7 +162,7 @@ export class LiveApiClient implements ApiClient {
|
||||
lyrics
|
||||
};
|
||||
|
||||
const response = await fetch(`${this.baseUrl}/add-lyrics`, {
|
||||
const response = await fetch(this.buildUrl('/add-lyrics'), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -170,7 +185,7 @@ export class LiveApiClient implements ApiClient {
|
||||
async submitAnnotations(annotations: Omit<CorrectionAnnotation, 'annotation_id' | 'timestamp'>[]): Promise<void> {
|
||||
// Submit each annotation to the backend
|
||||
for (const annotation of annotations) {
|
||||
const response = await fetch(`${this.baseUrl}/v1/annotations`, {
|
||||
const response = await fetch(this.buildUrl('/v1/annotations'), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -186,7 +201,7 @@ export class LiveApiClient implements ApiClient {
|
||||
}
|
||||
|
||||
async getAnnotationStats(): Promise<any> {
|
||||
const response = await fetch(`${this.baseUrl}/v1/annotations/stats`);
|
||||
const response = await fetch(this.buildUrl('/v1/annotations/stats'));
|
||||
if (!response.ok) {
|
||||
throw new Error(`API error: ${response.statusText}`);
|
||||
}
|
||||
|
||||
Generated
+10
-10
@@ -1873,14 +1873,14 @@ platformdirs = ">=4.3.6"
|
||||
|
||||
[[package]]
|
||||
name = "flacfetch"
|
||||
version = "0.7.3"
|
||||
version = "0.8.0"
|
||||
description = "Search and download high-quality audio from multiple sources"
|
||||
optional = false
|
||||
python-versions = ">=3.8"
|
||||
groups = ["main"]
|
||||
files = [
|
||||
{file = "flacfetch-0.7.3-py3-none-any.whl", hash = "sha256:0393aaef3a4817bb3018773e5b0d8d1a69d5fdaedb577b4d516e48480e347c59"},
|
||||
{file = "flacfetch-0.7.3.tar.gz", hash = "sha256:eb63c7b0cd34e27d9f6b43964f68d3a1177f6db450b2367bc0f4434d4de5253c"},
|
||||
{file = "flacfetch-0.8.0-py3-none-any.whl", hash = "sha256:a684f902a95f4d89f5ca0d7577e56fc17024f07d89fa198f5505300c25ba4c50"},
|
||||
{file = "flacfetch-0.8.0.tar.gz", hash = "sha256:53eaae2e85099f05d6a667c13edbcac650faeacd366400db5b564c4a48b1fc9d"},
|
||||
]
|
||||
|
||||
[package.dependencies]
|
||||
@@ -3305,14 +3305,14 @@ pydantic = ">=2.7.4,<3.0.0"
|
||||
|
||||
[[package]]
|
||||
name = "langchain-core"
|
||||
version = "1.2.4"
|
||||
version = "1.2.5"
|
||||
description = "Building applications with LLMs through composability"
|
||||
optional = false
|
||||
python-versions = "<4.0.0,>=3.10.0"
|
||||
groups = ["main"]
|
||||
files = [
|
||||
{file = "langchain_core-1.2.4-py3-none-any.whl", hash = "sha256:29ced7690688c85d66a797eb2866815f55c90cc83a94cf8b0ecad949e913f99f"},
|
||||
{file = "langchain_core-1.2.4.tar.gz", hash = "sha256:1e01c06f98b9904af0de39d2a290d11b4c4e07888dacbbf4bdc7cef259f5a80e"},
|
||||
{file = "langchain_core-1.2.5-py3-none-any.whl", hash = "sha256:3255944ef4e21b2551facb319bfc426057a40247c0a05de5bd6f2fc021fbfa34"},
|
||||
{file = "langchain_core-1.2.5.tar.gz", hash = "sha256:d674f6df42f07e846859b9d3afe547cad333d6bf9763e92c88eb4f8aaedcd3cc"},
|
||||
]
|
||||
|
||||
[package.dependencies]
|
||||
@@ -6265,14 +6265,14 @@ setuptools = ">=42.0.0"
|
||||
|
||||
[[package]]
|
||||
name = "pyparsing"
|
||||
version = "3.2.5"
|
||||
version = "3.3.1"
|
||||
description = "pyparsing - Classes and methods to define and execute parsing grammars"
|
||||
optional = false
|
||||
python-versions = ">=3.9"
|
||||
groups = ["main"]
|
||||
files = [
|
||||
{file = "pyparsing-3.2.5-py3-none-any.whl", hash = "sha256:e38a4f02064cf41fe6593d328d0512495ad1f3d8a91c4f73fc401b3079a59a5e"},
|
||||
{file = "pyparsing-3.2.5.tar.gz", hash = "sha256:2df8d5b7b2802ef88e8d016a2eb9c7aeaa923529cd251ed0fe4608275d4105b6"},
|
||||
{file = "pyparsing-3.3.1-py3-none-any.whl", hash = "sha256:023b5e7e5520ad96642e2c6db4cb683d3970bd640cdf7115049a6e9c3682df82"},
|
||||
{file = "pyparsing-3.3.1.tar.gz", hash = "sha256:47fad0f17ac1e2cad3de3b458570fbc9b03560aa029ed5e16ee5554da9a2251c"},
|
||||
]
|
||||
|
||||
[package.extras]
|
||||
@@ -9569,4 +9569,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 = "77a62e54574abcfc2e2b1238052768695dc0c6c94c72e2250b110ef1470d4d2b"
|
||||
content-hash = "1e643f63a31d7a34f6c583c4043bc53bd689f68ce93f5cda0c54e49a348222ff"
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.75.15"
|
||||
version = "0.75.23"
|
||||
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.3"
|
||||
flacfetch = ">=0.8"
|
||||
lyricsgenius = ">=3"
|
||||
fetch-lyrics-from-genius = ">=0.1"
|
||||
pillow = ">=10.1"
|
||||
|
||||
@@ -57,6 +57,11 @@ def main():
|
||||
default=None,
|
||||
help="Optional: Path to instrumental with backing vocals file"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--original",
|
||||
default=None,
|
||||
help="Optional: Path to original audio file (with vocals) for comparison"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--port",
|
||||
type=int,
|
||||
@@ -82,6 +87,9 @@ def main():
|
||||
if args.with_backing and not os.path.exists(args.with_backing):
|
||||
logger.error(f"With backing file not found: {args.with_backing}")
|
||||
sys.exit(1)
|
||||
if args.original and not os.path.exists(args.original):
|
||||
logger.error(f"Original audio file not found: {args.original}")
|
||||
sys.exit(1)
|
||||
|
||||
# Extract base name from backing vocals file
|
||||
base_name = os.path.basename(args.backing_vocals)
|
||||
@@ -102,6 +110,8 @@ def main():
|
||||
logger.info(f"Clean instrumental: {args.clean_instrumental}")
|
||||
if args.with_backing:
|
||||
logger.info(f"With backing: {args.with_backing}")
|
||||
if args.original:
|
||||
logger.info(f"Original audio: {args.original}")
|
||||
logger.info(f"Base name: {base_name}")
|
||||
logger.info(f"Output dir: {output_dir}")
|
||||
logger.info("")
|
||||
@@ -161,6 +171,7 @@ def main():
|
||||
backing_vocals_path=args.backing_vocals,
|
||||
clean_instrumental_path=args.clean_instrumental,
|
||||
with_backing_path=args.with_backing,
|
||||
original_audio_path=args.original,
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
@@ -83,7 +83,7 @@ class TestAudioSearchResult:
|
||||
title="Test Song",
|
||||
artist="Test Artist",
|
||||
url="https://example.com/song",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
duration=240,
|
||||
quality="FLAC",
|
||||
source_id="123456",
|
||||
@@ -124,7 +124,7 @@ class TestAudioSearchResult:
|
||||
title="Test Song",
|
||||
artist="Test Artist",
|
||||
url="https://example.com/song",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
duration=240,
|
||||
quality="FLAC 24bit",
|
||||
source_id="abc123",
|
||||
@@ -136,7 +136,7 @@ class TestAudioSearchResult:
|
||||
assert data["title"] == "Test Song"
|
||||
assert data["artist"] == "Test Artist"
|
||||
assert data["url"] == "https://example.com/song"
|
||||
assert data["provider"] == "Redacted"
|
||||
assert data["provider"] == "RED"
|
||||
assert data["duration"] == 240
|
||||
assert data["quality"] == "FLAC 24bit"
|
||||
assert data["source_id"] == "abc123"
|
||||
@@ -172,14 +172,14 @@ class TestAudioSearchResult:
|
||||
title="Test Song",
|
||||
artist="Test Artist",
|
||||
url="https://example.com/song",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
raw_result=MockRelease(),
|
||||
)
|
||||
data = result.to_dict()
|
||||
|
||||
# Basic fields
|
||||
assert data["title"] == "Test Song"
|
||||
assert data["provider"] == "Redacted"
|
||||
assert data["provider"] == "RED"
|
||||
|
||||
# Release-specific fields should be included
|
||||
assert data["year"] == 2024
|
||||
@@ -228,7 +228,7 @@ class TestAudioSearchResult:
|
||||
"title": "Test Song",
|
||||
"artist": "Test Artist",
|
||||
"url": "https://example.com/song",
|
||||
"provider": "Redacted",
|
||||
"provider": "RED",
|
||||
"duration": 240,
|
||||
"quality": "FLAC 24bit",
|
||||
"source_id": "abc123",
|
||||
@@ -241,7 +241,7 @@ class TestAudioSearchResult:
|
||||
assert result.title == "Test Song"
|
||||
assert result.artist == "Test Artist"
|
||||
assert result.url == "https://example.com/song"
|
||||
assert result.provider == "Redacted"
|
||||
assert result.provider == "RED"
|
||||
assert result.duration == 240
|
||||
assert result.quality == "FLAC 24bit"
|
||||
assert result.source_id == "abc123"
|
||||
@@ -268,7 +268,7 @@ class TestAudioSearchResult:
|
||||
title="Test Song",
|
||||
artist="Test Artist",
|
||||
url="https://example.com/song",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
duration=240,
|
||||
quality="FLAC",
|
||||
source_id="abc123",
|
||||
@@ -315,7 +315,7 @@ class TestAudioFetchResult:
|
||||
filepath="/path/to/song.flac",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
duration=180,
|
||||
quality="FLAC 24bit",
|
||||
)
|
||||
@@ -345,7 +345,7 @@ class TestAudioFetchResult:
|
||||
filepath="/path/to/song.flac",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
duration=180,
|
||||
quality="FLAC 24bit",
|
||||
)
|
||||
@@ -354,7 +354,7 @@ class TestAudioFetchResult:
|
||||
assert data["filepath"] == "/path/to/song.flac"
|
||||
assert data["artist"] == "Test Artist"
|
||||
assert data["title"] == "Test Song"
|
||||
assert data["provider"] == "Redacted"
|
||||
assert data["provider"] == "RED"
|
||||
assert data["duration"] == 180
|
||||
assert data["quality"] == "FLAC 24bit"
|
||||
|
||||
@@ -381,7 +381,7 @@ class TestAudioFetchResult:
|
||||
"filepath": "/path/to/song.flac",
|
||||
"artist": "Test Artist",
|
||||
"title": "Test Song",
|
||||
"provider": "Redacted",
|
||||
"provider": "RED",
|
||||
"duration": 180,
|
||||
"quality": "FLAC 24bit",
|
||||
}
|
||||
@@ -390,7 +390,7 @@ class TestAudioFetchResult:
|
||||
assert result.filepath == "/path/to/song.flac"
|
||||
assert result.artist == "Test Artist"
|
||||
assert result.title == "Test Song"
|
||||
assert result.provider == "Redacted"
|
||||
assert result.provider == "RED"
|
||||
assert result.duration == 180
|
||||
assert result.quality == "FLAC 24bit"
|
||||
|
||||
@@ -412,7 +412,7 @@ class TestAudioFetchResult:
|
||||
filepath="/path/to/song.flac",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
duration=180,
|
||||
quality="FLAC 24bit",
|
||||
)
|
||||
@@ -503,26 +503,32 @@ class TestFlacFetchAudioFetcher:
|
||||
def test_init_default(self):
|
||||
"""Test default initialization without environment variables."""
|
||||
# Clear env vars to test default behavior
|
||||
with patch.dict(os.environ, {"REDACTED_API_KEY": "", "OPS_API_KEY": ""}, clear=False):
|
||||
with patch.dict(os.environ, {"RED_API_KEY": "", "RED_API_URL": "", "OPS_API_KEY": "", "OPS_API_URL": ""}, clear=False):
|
||||
fetcher = FlacFetchAudioFetcher()
|
||||
assert fetcher._manager is None
|
||||
|
||||
def test_init_with_api_keys(self, mock_logger):
|
||||
"""Test initialization with API keys."""
|
||||
"""Test initialization with API keys and URLs."""
|
||||
fetcher = FlacFetchAudioFetcher(
|
||||
logger=mock_logger,
|
||||
redacted_api_key="red_key",
|
||||
red_api_key="red_key",
|
||||
red_api_url="https://red.api.url",
|
||||
ops_api_key="ops_key",
|
||||
ops_api_url="https://ops.api.url",
|
||||
)
|
||||
assert fetcher._redacted_api_key == "red_key"
|
||||
assert fetcher._red_api_key == "red_key"
|
||||
assert fetcher._red_api_url == "https://red.api.url"
|
||||
assert fetcher._ops_api_key == "ops_key"
|
||||
assert fetcher._ops_api_url == "https://ops.api.url"
|
||||
|
||||
@patch.dict(os.environ, {"REDACTED_API_KEY": "env_red_key", "OPS_API_KEY": "env_ops_key"})
|
||||
@patch.dict(os.environ, {"RED_API_KEY": "env_red_key", "RED_API_URL": "https://env.red.url", "OPS_API_KEY": "env_ops_key", "OPS_API_URL": "https://env.ops.url"})
|
||||
def test_init_from_environment(self, mock_logger):
|
||||
"""Test initialization reads API keys from environment."""
|
||||
"""Test initialization reads API keys and URLs from environment."""
|
||||
fetcher = FlacFetchAudioFetcher(logger=mock_logger)
|
||||
assert fetcher._redacted_api_key == "env_red_key"
|
||||
assert fetcher._red_api_key == "env_red_key"
|
||||
assert fetcher._red_api_url == "https://env.red.url"
|
||||
assert fetcher._ops_api_key == "env_ops_key"
|
||||
assert fetcher._ops_api_url == "https://env.ops.url"
|
||||
|
||||
@patch('karaoke_gen.audio_fetcher.FlacFetchAudioFetcher._get_manager')
|
||||
def test_search_success(self, mock_get_manager, fetcher):
|
||||
@@ -784,7 +790,7 @@ class TestFlacFetchAudioFetcher:
|
||||
index=0, raw_result=raw_result_1,
|
||||
),
|
||||
AudioSearchResult(
|
||||
title="Song 2", artist="Artist", url="url2", provider="Redacted",
|
||||
title="Song 2", artist="Artist", url="url2", provider="RED",
|
||||
index=1, raw_result=raw_result_2,
|
||||
),
|
||||
AudioSearchResult(
|
||||
@@ -839,7 +845,7 @@ class TestFlacFetchAudioFetcher:
|
||||
index=0, raw_result=None,
|
||||
),
|
||||
AudioSearchResult(
|
||||
title="Song 2", artist="Artist", url="url2", provider="Redacted",
|
||||
title="Song 2", artist="Artist", url="url2", provider="RED",
|
||||
index=1, raw_result=None,
|
||||
),
|
||||
]
|
||||
@@ -924,11 +930,15 @@ class TestFlacFetcherAlias:
|
||||
"""Test FlacFetcher alias passes parameters correctly."""
|
||||
from karaoke_gen.audio_fetcher import FlacFetcher
|
||||
fetcher = FlacFetcher(
|
||||
redacted_api_key="test_key",
|
||||
red_api_key="test_key",
|
||||
red_api_url="https://red.url",
|
||||
ops_api_key="ops_key",
|
||||
ops_api_url="https://ops.url",
|
||||
)
|
||||
assert fetcher._redacted_api_key == "test_key"
|
||||
assert fetcher._red_api_key == "test_key"
|
||||
assert fetcher._red_api_url == "https://red.url"
|
||||
assert fetcher._ops_api_key == "ops_key"
|
||||
assert fetcher._ops_api_url == "https://ops.url"
|
||||
|
||||
|
||||
class TestCreateAudioFetcher:
|
||||
@@ -944,12 +954,16 @@ class TestCreateAudioFetcher:
|
||||
logger = MagicMock()
|
||||
fetcher = create_audio_fetcher(
|
||||
logger=logger,
|
||||
redacted_api_key="red_key",
|
||||
red_api_key="red_key",
|
||||
red_api_url="https://red.url",
|
||||
ops_api_key="ops_key",
|
||||
ops_api_url="https://ops.url",
|
||||
)
|
||||
assert fetcher.logger == logger
|
||||
assert fetcher._redacted_api_key == "red_key"
|
||||
assert fetcher._red_api_key == "red_key"
|
||||
assert fetcher._red_api_url == "https://red.url"
|
||||
assert fetcher._ops_api_key == "ops_key"
|
||||
assert fetcher._ops_api_url == "https://ops.url"
|
||||
|
||||
|
||||
class TestFlacFetchManagerInitialization:
|
||||
@@ -962,13 +976,17 @@ class TestFlacFetchManagerInitialization:
|
||||
assert fetcher._manager is None
|
||||
|
||||
def test_api_keys_stored_at_init(self):
|
||||
"""Test API keys are stored at init for later use."""
|
||||
"""Test API keys and URLs are stored at init for later use."""
|
||||
fetcher = FlacFetchAudioFetcher(
|
||||
redacted_api_key="red_key",
|
||||
red_api_key="red_key",
|
||||
red_api_url="https://red.url",
|
||||
ops_api_key="ops_key",
|
||||
ops_api_url="https://ops.url",
|
||||
)
|
||||
assert fetcher._redacted_api_key == "red_key"
|
||||
assert fetcher._red_api_key == "red_key"
|
||||
assert fetcher._red_api_url == "https://red.url"
|
||||
assert fetcher._ops_api_key == "ops_key"
|
||||
assert fetcher._ops_api_url == "https://ops.url"
|
||||
|
||||
|
||||
class TestGetManagerIntegration:
|
||||
@@ -1015,46 +1033,46 @@ class TestGetManagerIntegration:
|
||||
assert "YouTube" in manager._downloader_map, \
|
||||
"YouTube downloader must be registered to download from YouTube"
|
||||
|
||||
def test_get_manager_registers_redacted_with_api_key_and_transmission(self):
|
||||
"""Test that Redacted provider is registered when API key AND Transmission are available."""
|
||||
fetcher = FlacFetchAudioFetcher(redacted_api_key="test_key")
|
||||
def test_get_manager_registers_red_with_api_key_url_and_transmission(self):
|
||||
"""Test that RED provider is registered when API key, URL AND Transmission are available."""
|
||||
fetcher = FlacFetchAudioFetcher(red_api_key="test_key", red_api_url="https://red.url")
|
||||
|
||||
# Mock Transmission as available
|
||||
with patch.object(fetcher, '_check_transmission_available', return_value=True):
|
||||
manager = fetcher._get_manager()
|
||||
|
||||
# Verify Redacted provider is registered
|
||||
# Verify RED provider is registered
|
||||
provider_names = [p.name for p in manager.providers]
|
||||
assert "Redacted" in provider_names
|
||||
assert "RED" in provider_names
|
||||
|
||||
# Verify Redacted downloader is registered (if TorrentDownloader is available)
|
||||
# Verify RED downloader is registered (if TorrentDownloader is available)
|
||||
try:
|
||||
from flacfetch.downloaders.torrent import TorrentDownloader
|
||||
assert "Redacted" in manager._downloader_map, \
|
||||
"Redacted downloader must be registered when TorrentDownloader is available"
|
||||
assert "RED" in manager._downloader_map, \
|
||||
"RED downloader must be registered when TorrentDownloader is available"
|
||||
except ImportError:
|
||||
# TorrentDownloader not available, which is okay
|
||||
pass
|
||||
|
||||
def test_get_manager_skips_redacted_without_transmission(self):
|
||||
"""Test that Redacted provider is NOT registered when Transmission is unavailable."""
|
||||
fetcher = FlacFetchAudioFetcher(redacted_api_key="test_key")
|
||||
def test_get_manager_skips_red_without_transmission(self):
|
||||
"""Test that RED provider is NOT registered when Transmission is unavailable."""
|
||||
fetcher = FlacFetchAudioFetcher(red_api_key="test_key", red_api_url="https://red.url")
|
||||
|
||||
# Mock Transmission as unavailable (the default on Cloud Run)
|
||||
with patch.object(fetcher, '_check_transmission_available', return_value=False):
|
||||
manager = fetcher._get_manager()
|
||||
|
||||
# Verify Redacted provider is NOT registered (can't download from it)
|
||||
# Verify RED provider is NOT registered (can't download from it)
|
||||
provider_names = [p.name for p in manager.providers]
|
||||
assert "Redacted" not in provider_names, \
|
||||
"Redacted provider should NOT be registered when Transmission is unavailable"
|
||||
assert "RED" not in provider_names, \
|
||||
"RED provider should NOT be registered when Transmission is unavailable"
|
||||
|
||||
# YouTube should still be registered
|
||||
assert "YouTube" in provider_names
|
||||
|
||||
def test_get_manager_registers_ops_with_api_key_and_transmission(self):
|
||||
"""Test that OPS provider is registered when API key AND Transmission are available."""
|
||||
fetcher = FlacFetchAudioFetcher(ops_api_key="test_key")
|
||||
def test_get_manager_registers_ops_with_api_key_url_and_transmission(self):
|
||||
"""Test that OPS provider is registered when API key, URL AND Transmission are available."""
|
||||
fetcher = FlacFetchAudioFetcher(ops_api_key="test_key", ops_api_url="https://ops.url")
|
||||
|
||||
# Mock Transmission as available
|
||||
with patch.object(fetcher, '_check_transmission_available', return_value=True):
|
||||
@@ -1074,7 +1092,7 @@ class TestGetManagerIntegration:
|
||||
|
||||
def test_get_manager_skips_ops_without_transmission(self):
|
||||
"""Test that OPS provider is NOT registered when Transmission is unavailable."""
|
||||
fetcher = FlacFetchAudioFetcher(ops_api_key="test_key")
|
||||
fetcher = FlacFetchAudioFetcher(ops_api_key="test_key", ops_api_url="https://ops.url")
|
||||
|
||||
# Mock Transmission as unavailable
|
||||
with patch.object(fetcher, '_check_transmission_available', return_value=False):
|
||||
@@ -1091,8 +1109,10 @@ class TestGetManagerIntegration:
|
||||
def test_get_manager_with_all_providers_and_transmission(self):
|
||||
"""Test manager setup with all providers configured when Transmission is available."""
|
||||
fetcher = FlacFetchAudioFetcher(
|
||||
redacted_api_key="red_key",
|
||||
red_api_key="red_key",
|
||||
red_api_url="https://red.url",
|
||||
ops_api_key="ops_key",
|
||||
ops_api_url="https://ops.url",
|
||||
)
|
||||
|
||||
# Mock Transmission as available
|
||||
@@ -1102,7 +1122,7 @@ class TestGetManagerIntegration:
|
||||
provider_names = [p.name for p in manager.providers]
|
||||
|
||||
# All three providers should be registered when Transmission is available
|
||||
assert "Redacted" in provider_names
|
||||
assert "RED" in provider_names
|
||||
assert "OPS" in provider_names
|
||||
assert "YouTube" in provider_names
|
||||
|
||||
@@ -1112,8 +1132,10 @@ class TestGetManagerIntegration:
|
||||
def test_get_manager_only_youtube_without_transmission(self):
|
||||
"""Test that only YouTube is registered when Transmission is unavailable."""
|
||||
fetcher = FlacFetchAudioFetcher(
|
||||
redacted_api_key="red_key",
|
||||
red_api_key="red_key",
|
||||
red_api_url="https://red.url",
|
||||
ops_api_key="ops_key",
|
||||
ops_api_url="https://ops.url",
|
||||
)
|
||||
|
||||
# Mock Transmission as unavailable (simulates Cloud Run environment)
|
||||
@@ -1123,7 +1145,7 @@ class TestGetManagerIntegration:
|
||||
provider_names = [p.name for p in manager.providers]
|
||||
|
||||
# Only YouTube should be registered
|
||||
assert "Redacted" not in provider_names
|
||||
assert "RED" not in provider_names
|
||||
assert "OPS" not in provider_names
|
||||
assert "YouTube" in provider_names
|
||||
|
||||
@@ -1210,7 +1232,7 @@ class TestFlacFetchReleaseModelCompatibility:
|
||||
title="Test Song",
|
||||
artist="Test Artist",
|
||||
quality=quality,
|
||||
source_name="Redacted",
|
||||
source_name="RED",
|
||||
)
|
||||
|
||||
# Verify the attributes we use in audio_fetcher.py exist
|
||||
@@ -1241,7 +1263,7 @@ class TestFlacFetchReleaseModelCompatibility:
|
||||
title="Real Song",
|
||||
artist="Real Artist",
|
||||
quality=quality,
|
||||
source_name="Redacted",
|
||||
source_name="RED",
|
||||
download_url="https://example.com/download",
|
||||
duration_seconds=240,
|
||||
info_hash="abc123hash",
|
||||
@@ -1263,7 +1285,7 @@ class TestFlacFetchReleaseModelCompatibility:
|
||||
|
||||
assert result.title == "Real Song"
|
||||
assert result.artist == "Real Artist"
|
||||
assert result.provider == "Redacted" # source_name -> provider
|
||||
assert result.provider == "RED" # source_name -> provider
|
||||
assert result.duration == 240 # duration_seconds -> duration
|
||||
assert result.url == "https://example.com/download" # download_url -> url
|
||||
assert result.source_id == "abc123hash" # info_hash -> source_id
|
||||
@@ -1294,7 +1316,7 @@ class TestFlacFetchCLIHandlerCompatibility:
|
||||
title="Test Song",
|
||||
artist="Test Artist",
|
||||
quality=quality,
|
||||
source_name="Redacted",
|
||||
source_name="RED",
|
||||
seeders=25,
|
||||
)
|
||||
|
||||
|
||||
@@ -146,6 +146,23 @@ class TestServerInitialization:
|
||||
|
||||
assert server.with_backing_path == str(with_backing)
|
||||
|
||||
def test_server_initialization_with_original_audio(self, mock_analysis, temp_files):
|
||||
"""Test server initializes with optional original_audio_path."""
|
||||
original_audio = Path(temp_files["output_dir"]) / "original.wav"
|
||||
original_audio.write_bytes(b"fake audio")
|
||||
|
||||
server = InstrumentalReviewServer(
|
||||
output_dir=temp_files["output_dir"],
|
||||
base_name="Artist - Title",
|
||||
analysis=mock_analysis,
|
||||
waveform_path=temp_files["waveform_path"],
|
||||
backing_vocals_path=temp_files["backing_vocals_path"],
|
||||
clean_instrumental_path=temp_files["clean_instrumental_path"],
|
||||
original_audio_path=str(original_audio),
|
||||
)
|
||||
|
||||
assert server.original_audio_path == str(original_audio)
|
||||
|
||||
def test_get_selection_raises_without_selection(self, mock_analysis, temp_files):
|
||||
"""Test get_selection raises when no selection made."""
|
||||
server = InstrumentalReviewServer(
|
||||
@@ -526,6 +543,44 @@ class TestServerAPIEndpoints:
|
||||
assert data["audio_urls"]["backing_vocals"] is not None
|
||||
assert data["audio_urls"]["clean_instrumental"] is not None
|
||||
|
||||
def test_get_analysis_with_original_audio(self, tmp_path, mock_analysis):
|
||||
"""Test analysis endpoint includes has_original flag when original audio is provided."""
|
||||
from fastapi.testclient import TestClient
|
||||
from pydub import AudioSegment
|
||||
from pydub.generators import Sine
|
||||
|
||||
# Create real audio files for testing
|
||||
audio = Sine(440).to_audio_segment(duration=1000) # 1 second of 440Hz sine
|
||||
|
||||
backing = tmp_path / "backing.flac"
|
||||
clean = tmp_path / "clean.flac"
|
||||
original = tmp_path / "original.wav"
|
||||
waveform = tmp_path / "waveform.png"
|
||||
|
||||
audio.export(str(backing), format="flac")
|
||||
audio.export(str(clean), format="flac")
|
||||
audio.export(str(original), format="wav")
|
||||
waveform.write_bytes(b"\x89PNG\r\n\x1a\n") # PNG magic bytes
|
||||
|
||||
# Create server with original audio
|
||||
server = InstrumentalReviewServer(
|
||||
output_dir=str(tmp_path),
|
||||
base_name="Artist - Title",
|
||||
analysis=mock_analysis,
|
||||
waveform_path=str(waveform),
|
||||
backing_vocals_path=str(backing),
|
||||
clean_instrumental_path=str(clean),
|
||||
original_audio_path=str(original),
|
||||
)
|
||||
|
||||
client = TestClient(server._create_app())
|
||||
response = client.get("/api/jobs/local/instrumental-analysis")
|
||||
assert response.status_code == 200
|
||||
|
||||
data = response.json()
|
||||
assert data["has_original"] == True
|
||||
assert data["audio_urls"]["original"] == "/api/audio/original"
|
||||
|
||||
def test_get_waveform_data_returns_amplitudes(self, client):
|
||||
"""Test waveform data endpoint returns amplitudes."""
|
||||
response = client.get("/api/jobs/local/waveform-data?num_points=100")
|
||||
|
||||
@@ -2079,7 +2079,7 @@ class TestJobMonitorDownloadProgress:
|
||||
"""Test that active torrents show progress details."""
|
||||
job_data = {
|
||||
'state_data': {
|
||||
'selected_audio_provider': 'Redacted'
|
||||
'selected_audio_provider': 'RED'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2103,7 +2103,7 @@ class TestJobMonitorDownloadProgress:
|
||||
with caplog.at_level(logging.INFO):
|
||||
monitor._show_download_progress(job_data)
|
||||
|
||||
assert "Downloading from Redacted" in caplog.text
|
||||
assert "Downloading from RED" in caplog.text
|
||||
assert "45.5%" in caplog.text
|
||||
assert "1250.0 KB/s" in caplog.text
|
||||
assert "3 peers" in caplog.text
|
||||
@@ -2145,7 +2145,7 @@ class TestJobMonitorDownloadProgress:
|
||||
"""Test message when no active torrents."""
|
||||
job_data = {
|
||||
'state_data': {
|
||||
'selected_audio_provider': 'Redacted'
|
||||
'selected_audio_provider': 'RED'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2171,7 +2171,7 @@ class TestJobMonitorDownloadProgress:
|
||||
"""Test warning when Transmission not available."""
|
||||
job_data = {
|
||||
'state_data': {
|
||||
'selected_audio_provider': 'Redacted'
|
||||
'selected_audio_provider': 'RED'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2196,7 +2196,7 @@ class TestJobMonitorDownloadProgress:
|
||||
"""Test fallback message on request error."""
|
||||
job_data = {
|
||||
'state_data': {
|
||||
'selected_audio_provider': 'Redacted'
|
||||
'selected_audio_provider': 'RED'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2212,7 +2212,7 @@ class TestJobMonitorDownloadProgress:
|
||||
"""Test fallback on non-200 HTTP response."""
|
||||
job_data = {
|
||||
'state_data': {
|
||||
'selected_audio_provider': 'Redacted'
|
||||
'selected_audio_provider': 'RED'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2223,7 +2223,7 @@ class TestJobMonitorDownloadProgress:
|
||||
with caplog.at_level(logging.INFO):
|
||||
monitor._show_download_progress(job_data)
|
||||
|
||||
assert "Downloading from Redacted" in caplog.text
|
||||
assert "Downloading from RED" in caplog.text
|
||||
|
||||
def test_show_download_progress_missing_provider(self, monitor, caplog):
|
||||
"""Test handling of missing provider in state_data."""
|
||||
|
||||
Reference in new issue
Block a user