Compare commits

...
35 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️ 90d36a63f7 Merge pull request #50 from nomadkaraoke/fix/ctrl-c-graceful-shutdown
fix: improve Ctrl+C handling for graceful shutdown
2025-12-23 17:52:46 -05:00
Andrew Beveridge 84928fed33 Merge remote-tracking branch 'origin/main' into fix/ctrl-c-graceful-shutdown 2025-12-23 17:34:37 -05:00
Andrew Beveridge ☄️ f144797366 Merge pull request #49 from nomadkaraoke/feature/optimize-audioshake-upload
feat: Optimize AudioShake upload by converting WAV to FLAC
2025-12-23 17:33:38 -05:00
Andrew Beveridge a86273adf1 fix: improve Ctrl+C handling for graceful shutdown
- Remove sys.exit(0) from shutdown() which caused unhandled SystemExit exception
- Raise KeyboardInterrupt instead to propagate cleanly up the call stack
- Add asyncio.CancelledError handling in gen_cli.py

Fixes the issue where first Ctrl+C was detected but didn't quit, requiring
a second Ctrl+C that caused ugly threading errors.

Bumps version to 0.75.26
2025-12-23 17:32:27 -05:00
Andrew Beveridge f0b447823b Updated frontend, fixed anchor sequence word IDs calculation on recreation of the same track 2025-12-23 17:26:25 -05:00
Andrew Beveridge e4336c3f99 feat: optimize AudioShake upload by converting WAV to FLAC
- Add AudioUploadOptimizer class to handle intelligent file format selection
- WAV files are converted to FLAC before upload (typically ~50% smaller)
- FLAC and other lossless compressed formats are uploaded directly
- Lossy formats (MP3, AAC, etc.) are uploaded directly to preserve quality
- Temporary files are cleaned up after upload completes or on error
- Add comprehensive unit tests for new optimizer functionality

This optimization reduces upload time and bandwidth usage when transcribing
audio files with AudioShake, especially for WAV files which can be 10x larger
than their FLAC equivalent.
2025-12-23 17:23:20 -05:00
Andrew Beveridge ☄️ d55e8b514a Merge pull request #48 from nomadkaraoke/refactor/remove-private-tracker-references
refactor: update to use RED naming and env var URLs for private trackers
2025-12-23 16:06:40 -05:00
Andrew Beveridge e333fb2ae0 Removed flacfetch submodule 2025-12-23 00:31:51 -05:00
Andrew Beveridge 3dd2ee4a86 Switch back to pypi flacfetch 2025-12-23 00:23:24 -05:00
Andrew Beveridge 70b1410c0e infra: add missing ops-api-url secret
Version: 0.75.23
2025-12-23 00:10:34 -05:00
Andrew Beveridge 067052448f infra: grant flacfetch repo access to Workload Identity and Compute SSH permissions
- Add nomadkaraoke/flacfetch to workload identity user binding
- Grant compute.instanceAdmin.v1 for VM management
- Grant compute.osLogin for SSH access
- Grant iap.tunnelResourceAccessor for secure SSH tunneling

This fixes the 'iam.serviceAccounts.getAccessToken' permission denied error
in flacfetch's deploy-to-gcp CI job.

Version: 0.75.22
2025-12-22 23:54:21 -05:00
Andrew Beveridge a5bca8781a Updated poetry lockfile 2025-12-22 23:48:49 -05:00
Andrew Beveridge 7d1b9ce960 fix: use local flacfetch submodule for builds and CI
- Update pyproject.toml to use path dependency for flacfetch
- Update CI workflow to checkout submodules for package tests
- Bump version to 0.75.21
2025-12-22 23:42:54 -05:00
Andrew Beveridge 311e0a4ad2 refactor: update to use RED naming and env var URLs for private trackers
Updates to align with flacfetch 0.8.0 breaking changes:
- Renamed "Redacted" to "RED" throughout codebase
- Updated REDACTED_API_KEY references to RED_API_KEY
- Updated redacted_api_key parameter to red_api_key
- Added RED_API_URL and OPS_API_URL env var requirements
- Updated infrastructure config for new environment variables
- Updated all tests and documentation

This improves security by requiring private tracker URLs to be
configured via environment variables rather than hardcoded.

Version: 0.75.20
2025-12-22 23:30:19 -05:00
Andrew Beveridge 70977f4807 Bump for deploy 2025-12-22 17:41:31 -05:00
Andrew Beveridge 11c8d8d58e Disable codecov on main 2025-12-22 17:40:42 -05:00
Andrew Beveridge ☄️ c15673b27e Merge pull request #47 from nomadkaraoke/feature/review-auth-tokens
feat: Job-scoped review tokens for lyrics review authentication
2025-12-22 17:29:38 -05:00
Andrew Beveridge 913efcf72a fix: Fix test fixtures and auth headers for backend tests
- Remove mock_auth_service fixture dependency from test_internal_api.py
  and test_upload_api.py (now using autouse mock_auth_dependency from conftest)
- Add upload_auth_headers fixture for file upload tests (no Content-Type header
  to avoid breaking multipart form data)
- Add service._remote_client = None to audio search tests to prevent hitting
  remote flacfetch service
- Add proper skipif decorator for TestRemoteCLIStyleParsing when flacfetch
  module is not properly installed
- Add headers=auth_headers to emulator integration test for annotations endpoint
- Fix headers=upload_auth_headers usage in all file upload tests
2025-12-22 17:19:17 -05:00
Andrew Beveridge ad0a6c3475 feat: Add instrumental review token authentication
- Add instrumental_token and instrumental_token_expires_at to Job model
- Generate instrumental token when entering AWAITING_INSTRUMENTAL_SELECTION
- Create require_instrumental_auth dependency for instrumental endpoints
- Update instrumental endpoints to use require_instrumental_auth:
  - GET /instrumental-options
  - GET /instrumental-analysis
  - GET /audio-stream/{stem_type}
  - POST /create-custom-instrumental
  - GET /waveform-data
  - POST /select-instrumental
- Update remote CLI to build correct instrumental review URL with token
- Modify instrumental review HTML to:
  - Accept baseApiUrl and instrumentalToken from URL params
  - Use cloud API endpoints when in cloud mode
  - Include token in all API requests
- Add CI step to deploy instrumental UI to gen.nomadkaraoke.com/instrumental/
- Add mock for require_instrumental_auth in test fixtures

The instrumental review UI is now accessible at:
gen.nomadkaraoke.com/instrumental/?baseApiUrl=...&instrumentalToken=...
2025-12-22 16:31:48 -05:00
Andrew Beveridge cd15024c42 feat: Add job-scoped review tokens for lyrics review auth
- Add review_token and review_token_expires_at fields to Job model
- Create require_review_auth dependency that accepts either:
  - Full user authentication (admin/user token)
  - Job-specific review token (48-hour expiry)
- Generate review token automatically when job enters AWAITING_REVIEW
- Update all review endpoints to use require_review_auth
- Update remote CLI to include reviewToken in review UI URL
- Update lyrics review frontend to extract and use token from URL
- Add lyrics frontend deployment to gen.nomadkaraoke.com/lyrics/
- Update default review UI URL to gen.nomadkaraoke.com/lyrics
- Fix test auth fixtures and add auth_headers where missing

This enables the lyrics review UI to authenticate without requiring
users to manually enter tokens, while maintaining security through
job-scoped tokens with automatic expiration.
2025-12-22 16:20:10 -05:00
Andrew Beveridge ☄️ 9906d4bb63 Merge pull request #46 from nomadkaraoke/feature/instrumental-review-original-audio-tab
Add Original Audio tab to Instrumental Review UI
2025-12-22 14:56:37 -05:00
Andrew Beveridge 9e28f7bd99 Merge branch 'main' into feature/instrumental-review-original-audio-tab
Resolved conflict in pyproject.toml:
- Updated version to 0.75.16 (after main's 0.75.15)
2025-12-22 14:38:09 -05:00
Andrew Beveridge ☄️ 3ca62aa555 Merge pull request #45 from nomadkaraoke/security/require-auth-all-endpoints
security: Require authentication for all major backend API endpoints
2025-12-22 14:36:12 -05:00
Andrew Beveridge 8b808b0bf0 tests: fix missing auth headers in emulator review endpoint tests
Fixed 2 failing emulator tests that were missing auth_headers:

1. test_review_correction_data_wrong_status
   - GET /api/review/{job_id}/correction-data now includes headers=auth_headers

2. test_review_preview_video_stub
   - POST /api/review/{job_id}/preview-video now includes headers=auth_headers

These tests were getting 401 Unauthorized instead of expected 400 Bad Request
because review endpoints require authentication.

Verified locally: All 27 emulator tests now pass
  poetry run pytest backend/tests/emulator/ -v
  ✅ 27 passed, 341 warnings in 8.79s
2025-12-22 14:23:16 -05:00
Andrew Beveridge 6985ab31b3 tests: fix auth mock to properly skip emulator tests
The mock_auth_dependency fixture was interfering with emulator tests.

Changes:
1. Check for FIRESTORE_EMULATOR_HOST env var to detect emulator environment
2. Skip both 'emulator' and 'integration' in test path
3. This allows emulator tests to use REAL auth with ADMIN_TOKENS

Emulator tests need real auth because they set:
  ADMIN_TOKENS="test-admin-token"

And call endpoints with:
  Authorization: Bearer test-admin-token

The real AuthService should validate this token.
2025-12-22 14:08:14 -05:00
Andrew Beveridge 706e414e36 chore: remove temporary test debugging files 2025-12-22 13:56:52 -05:00
Andrew Beveridge 5ace8b0575 tests: fix auth mocking for all unit tests
Fixed authentication in unit tests after adding require_auth to 33+ endpoints:

1. Added missing imports (Depends, Tuple) to route files:
   - file_upload.py, audio_search.py, review.py

2. Updated conftest.py with proper auth mocking:
   - Use FastAPI's dependency_overrides system
   - Mock require_auth and require_admin to return valid admin credentials
   - Apply automatically to all non-emulator tests

3. Auto-fixed 6 test files to include auth_headers:
   - test_jobs_api.py
   - test_upload_api.py
   - test_api_routes.py
   - test_internal_api.py
   - test_emulator_integration.py (both copies)

4. Fixed test client fixtures:
   - Removed mock_auth_service parameter (replaced by global fixture)
   - Tests now use dependency_overrides instead of patching

Tests verified passing locally for test_jobs_api.py.
Let CI run the full test suite to verify all tests pass.

Related: PR #45
2025-12-22 13:56:23 -05:00
Andrew Beveridge bc7d1a2308 tests: add mock auth service and documentation for test fixes
Added mock_auth_service and auth_headers fixtures to conftest.py to support
testing authenticated endpoints.

The tests are currently failing because they don't include authentication
headers in their requests. This commit:

1. Adds global test fixtures for mock authentication
2. Documents the remaining test fixes needed in TEST-FIXES-NEEDED.md

Remaining work: Update 60+ test methods across multiple test files to:
- Add `auth_headers` parameter to test methods
- Pass `headers=auth_headers` to all client.get/post/etc() calls

See docs/TEST-FIXES-NEEDED.md for detailed instructions and an auto-fix script.

Related: PR #45
2025-12-22 13:31:50 -05:00
Andrew Beveridge 1741470ddb feat: add Original Audio tab to Instrumental Review UI
- Added original audio path detection in gen_cli.py
- Pass original_audio_path to InstrumentalReviewServer
- Updated test-instrumental-review.py script with --original argument
- Added tests for original audio functionality
- Bumped version to 0.75.12

The Instrumental Review UI now shows an 'Original Audio' tab when the
original audio file is available, allowing users to compare the full
song against backing vocals and instrumentals when deciding which
regions to mute.

Closes #[issue_number] (if applicable)
2025-12-22 13:24:34 -05:00
Andrew Beveridge ee9ea7c0c5 security: require authentication for all major backend API endpoints
**Critical Security Fix**

Previously, most backend API endpoints were publicly accessible without any
authentication, allowing anyone to:
- List all jobs
- View job details
- Create new jobs
- Cancel/delete jobs
- Access job outputs

This commit adds `Depends(require_auth)` to 33+ endpoints across the backend.

## Endpoints Secured (33+)

### jobs.py (20 endpoints) ✅
- Job CRUD: create, get, list, delete, bulk_delete
- Review flow: get_review_data, start_review, submit_corrections, complete_review
- Instrumental: get_instrumental_options, get_instrumental_analysis, stream_audio,
  create_custom_instrumental, get_waveform_data, select_instrumental
- Downloads: get_download_urls, download_file
- Management: cancel_job, retry_job, get_worker_logs

### file_upload.py (6 endpoints) ✅
- upload_and_create_job - Direct file upload
- create_job_with_upload_urls - Signed URL flow (step 1)
- mark_uploads_complete - Signed URL flow (step 2)
- create_job_from_url - YouTube/URL submission
- create_finalise_only_job - Prep-only continuation
- mark_finalise_uploads_complete - Finalise uploads validation

### audio_search.py (3 endpoints) ✅
- search_audio - Search by artist/title
- get_audio_search_results - Get search results
- select_audio_source - Select and download audio

### review.py (4/12 endpoints) ⚠️
- get_correction_data - Get lyrics for review
- complete_review - Submit corrected lyrics
- add_lyrics - Add custom lyrics source
- generate_preview_video - Generate preview

## Remaining Work

See `docs/SECURITY-AUTH-TODO.md` for:
- Remaining review.py endpoints (audio streaming, handlers, annotations)
- auth.py endpoints (OAuth credential management - needs admin auth)
- internal.py endpoints (worker triggers - CRITICAL, needs admin auth)
- health.py detailed endpoint

## Frontend Impact

The frontend already has `AuthBanner` component for token input and stores
tokens in localStorage. All API calls in `frontend/lib/api.ts` include the
Authorization header when a token is present.

**Users must now provide a valid authentication token to use the API.**

## Migration Notes

- Health checks (`/health`, `/readiness`) remain unauthenticated for k8s/monitoring
- Internal worker endpoints currently check `X-Admin-Token` but should use formal
  `Depends(require_admin)` - tracked in SECURITY-AUTH-TODO.md
- Review UI audio streaming may need query param token support

Closes: Part of authentication enforcement initiative
2025-12-22 12:01:45 -05:00
Andrew Beveridge 91b2421c37 docs: merge frontend guide documentation 2025-12-22 11:43:11 -05:00
Andrew Beveridge 06748776e3 docs: add comprehensive frontend guide
- Complete overview of frontend architecture and deployment
- Authentication system documentation
- All features explained (job submission, monitoring, interactive elements)
- Component structure and key files
- Local development guide
- Deployment process and CI/CD
- Common issues and troubleshooting
- API integration patterns
- Future enhancement ideas

This provides a complete reference for understanding and working with the frontend.
2025-12-22 11:42:48 -05:00
Andrew Beveridge ☄️ 91f51d6a8c feat: Match frontend styling to instrumental review UI and add authentication
- Updated color scheme to match instrumental review UI (neutral dark theme with blue accents)
- Replaced Geist fonts with system font stack for faster loading
- Fixed API URL from gen.nomadkaraoke.com to api.nomadkaraoke.com
- Added authentication support with token management (localStorage)
- Created AuthBanner component for token input
- All API requests now include Authorization header when authenticated

This resolves frontend API 404 errors and provides consistent styling across all karaoke-gen UIs.
2025-12-22 11:41:25 -05:00
Andrew Beveridge f2e2617e43 fix: update frontend to use correct API URL (api.nomadkaraoke.com) and add authentication support
- Changed API_BASE_URL from gen.nomadkaraoke.com to api.nomadkaraoke.com
- Added token management (localStorage)
- Created AuthBanner component for token input
- All API calls now include Authorization header when token is present
- Fixed 404 errors - gen.nomadkaraoke.com serves frontend, api.nomadkaraoke.com is backend

This resolves the issue where the frontend was trying to call API endpoints on the frontend domain instead of the dedicated backend API domain.
2025-12-22 11:26:43 -05:00
Andrew Beveridge 198ffc2469 feat: match frontend styling to instrumental review UI
- Update color scheme to match instrumental review UI dark theme
- Replace Geist fonts with system font stack (-apple-system, BlinkMacSystemFont, etc.)
- Use #0f0f0f background, #1a1a1a cards, #3b82f6 primary blue
- Maintain Tailwind compatibility with CSS variable mappings
- Remove sidebar color variables (not used in this UI)

This creates a more consistent visual experience across all karaoke-gen UIs.
2025-12-22 10:59:27 -05:00
64 changed files with 2599 additions and 452 deletions

No files matched your search

+37 -4
View File
@@ -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
+3
View File
@@ -73,8 +73,11 @@ dist/
downloads/
eggs/
.eggs/
# Python lib directories (not frontend)
lib/
lib64/
# But allow frontend lib
!frontend/lib/
parts/
sdist/
var/
+2
View File
@@ -183,6 +183,8 @@ karaoke-gen-remote \
| `REVIEW_UI_URL` | Lyrics review UI URL | `https://lyrics.nomadkaraoke.com` |
| `POLL_INTERVAL` | Seconds between status polls | `5` |
**Note:** The `REVIEW_UI_URL` defaults to the hosted lyrics review UI. For local development, set it to `http://localhost:5173` if you're running the frontend dev server.
### Authentication
The backend uses token-based authentication for admin operations (bulk delete, internal worker triggers). For basic job submission and monitoring, authentication is optional.
+194 -2
View File
@@ -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()
+11 -4
View File
@@ -15,9 +15,9 @@ import asyncio
import logging
import os
import tempfile
from typing import Optional, List, Dict, Any
from typing import Optional, List, Dict, Any, Tuple
from fastapi import APIRouter, HTTPException, BackgroundTasks, Request
from fastapi import APIRouter, HTTPException, BackgroundTasks, Request, Depends
from pydantic import BaseModel, Field
from backend.models.job import JobCreate, JobStatus
@@ -34,6 +34,8 @@ from backend.services.audio_search_service import (
)
from backend.config import get_settings
from backend.version import VERSION
from backend.api.dependencies import require_auth
from backend.services.auth_service import UserType
logger = logging.getLogger(__name__)
router = APIRouter(tags=["audio-search"])
@@ -229,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
@@ -330,6 +332,7 @@ async def search_audio(
request: Request,
background_tasks: BackgroundTasks,
body: AudioSearchRequest,
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
):
"""
Search for audio by artist and title, creating a new job.
@@ -548,7 +551,10 @@ async def search_audio(
@router.get("/audio-search/{job_id}/results")
async def get_audio_search_results(job_id: str):
async def get_audio_search_results(
job_id: str,
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
):
"""
Get audio search results for a job.
@@ -582,6 +588,7 @@ async def select_audio_source(
job_id: str,
background_tasks: BackgroundTasks,
body: AudioSelectRequest,
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
):
"""
Select an audio source and start job processing.
+9 -1
View File
@@ -15,7 +15,7 @@ import json
import logging
import tempfile
import os
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Request, Body
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Request, Body, Depends
from pathlib import Path
from typing import Optional, List, Dict, Any, Tuple
@@ -29,6 +29,8 @@ from backend.services.credential_manager import get_credential_manager, Credenti
from backend.config import get_settings
from backend.version import VERSION
from backend.services.metrics import metrics
from backend.api.dependencies import require_auth
from backend.services.auth_service import UserType
logger = logging.getLogger(__name__)
router = APIRouter(tags=["jobs"])
@@ -238,6 +240,7 @@ async def _trigger_workers_parallel(job_id: str) -> None:
async def upload_and_create_job(
request: Request,
background_tasks: BackgroundTasks,
auth_data: Tuple[str, UserType, int] = Depends(require_auth),
# Required fields
file: UploadFile = File(..., description="Audio file to process"),
artist: str = Form(..., description="Artist name"),
@@ -774,6 +777,7 @@ def _get_gcs_path_for_file(job_id: str, file_type: str, filename: str) -> str:
async def create_job_with_upload_urls(
request: Request,
body: CreateJobWithUploadUrlsRequest,
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
):
"""
Create a karaoke generation job and return signed URLs for direct file upload to GCS.
@@ -932,6 +936,7 @@ async def mark_uploads_complete(
job_id: str,
background_tasks: BackgroundTasks,
body: UploadsCompleteRequest,
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
):
"""
Mark file uploads as complete and start job processing.
@@ -1177,6 +1182,7 @@ async def create_job_from_url(
request: Request,
background_tasks: BackgroundTasks,
body: CreateJobFromUrlRequest,
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
):
"""
Create a karaoke generation job from a YouTube or other online video URL.
@@ -1354,6 +1360,7 @@ def _get_gcs_path_for_finalise_file(job_id: str, file_type: str, filename: str)
async def create_finalise_only_job(
request: Request,
body: CreateFinaliseOnlyJobRequest,
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
):
"""
Create a finalise-only job for continuing from a local prep phase.
@@ -1522,6 +1529,7 @@ async def mark_finalise_uploads_complete(
job_id: str,
background_tasks: BackgroundTasks,
body: UploadsCompleteRequest,
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
):
"""
Mark finalise-only file uploads as complete and start video generation.
+79 -19
View File
@@ -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
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
@@ -56,7 +56,8 @@ async def _trigger_workers_parallel(job_id: str) -> None:
@router.post("", response_model=JobResponse)
async def create_job(
request: URLSubmissionRequest,
background_tasks: BackgroundTasks
background_tasks: BackgroundTasks,
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
) -> JobResponse:
"""
Create a new karaoke generation job from a URL.
@@ -106,7 +107,10 @@ async def create_job(
@router.get("/{job_id}", response_model=Job)
async def get_job(job_id: str) -> Job:
async def get_job(
job_id: str,
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
) -> Job:
"""Get job status and details."""
job = job_manager.get_job(job_id)
if not job:
@@ -126,7 +130,8 @@ async def list_jobs(
client_id: Optional[str] = None,
created_after: Optional[str] = None,
created_before: Optional[str] = None,
limit: int = 100
limit: int = 100,
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
) -> List[Job]:
"""
List jobs with optional filters.
@@ -178,7 +183,11 @@ async def list_jobs(
@router.delete("/{job_id}")
async def delete_job(job_id: str, delete_files: bool = True) -> dict:
async def delete_job(
job_id: str,
delete_files: bool = True,
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
) -> dict:
"""Delete a job and optionally its output files."""
try:
job = job_manager.get_job(job_id)
@@ -305,7 +314,10 @@ async def bulk_delete_jobs(
# ============================================================================
@router.get("/{job_id}/review-data")
async def get_review_data(job_id: str) -> Dict[str, Any]:
async def get_review_data(
job_id: str,
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
) -> Dict[str, Any]:
"""
Get data needed for lyrics review interface.
@@ -346,7 +358,11 @@ async def get_review_data(job_id: str) -> Dict[str, Any]:
@router.post("/{job_id}/start-review")
async def start_review(job_id: str, request: StartReviewRequest) -> dict:
async def start_review(
job_id: str,
request: StartReviewRequest,
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
) -> dict:
"""
Mark job as IN_REVIEW (user opened review interface).
@@ -368,7 +384,8 @@ async def start_review(job_id: str, request: StartReviewRequest) -> dict:
async def submit_corrections(
job_id: str,
submission: CorrectionsSubmission,
background_tasks: BackgroundTasks
background_tasks: BackgroundTasks,
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
) -> dict:
"""
Save corrected lyrics during human review.
@@ -426,7 +443,8 @@ async def submit_corrections(
@router.post("/{job_id}/complete-review")
async def complete_review(
job_id: str,
background_tasks: BackgroundTasks
background_tasks: BackgroundTasks,
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
) -> dict:
"""
Complete the human review and trigger video rendering.
@@ -474,13 +492,18 @@ async def complete_review(
@router.get("/{job_id}/instrumental-options")
async def get_instrumental_options(job_id: str) -> Dict[str, Any]:
async def get_instrumental_options(
job_id: str,
auth_info: Tuple[str, str] = Depends(require_instrumental_auth)
) -> Dict[str, Any]:
"""
Get instrumental audio options for user selection.
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:
@@ -529,7 +552,10 @@ async def get_instrumental_options(job_id: str) -> Dict[str, Any]:
@router.get("/{job_id}/instrumental-analysis")
async def get_instrumental_analysis(job_id: str) -> Dict[str, Any]:
async def get_instrumental_analysis(
job_id: str,
auth_info: Tuple[str, str] = Depends(require_instrumental_auth)
) -> Dict[str, Any]:
"""
Get audio analysis data for instrumental selection.
@@ -540,6 +566,8 @@ async def get_instrumental_analysis(job_id: str) -> Dict[str, Any]:
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:
@@ -603,7 +631,11 @@ async def get_instrumental_analysis(job_id: str) -> Dict[str, Any]:
@router.get("/{job_id}/audio-stream/{stem_type}")
async def stream_audio(job_id: str, stem_type: str):
async def stream_audio(
job_id: str,
stem_type: str,
auth_info: Tuple[str, str] = Depends(require_instrumental_auth)
):
"""
Stream an audio file for playback in the browser.
@@ -615,6 +647,8 @@ async def stream_audio(job_id: str, stem_type: str):
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
@@ -691,6 +725,7 @@ async def stream_audio(job_id: str, stem_type: str):
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.
@@ -702,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
@@ -780,7 +817,11 @@ async def create_custom_instrumental(
@router.get("/{job_id}/waveform-data")
async def get_waveform_data(job_id: str, num_points: int = 500) -> Dict[str, Any]:
async def get_waveform_data(
job_id: str,
num_points: int = 500,
auth_info: Tuple[str, str] = Depends(require_instrumental_auth)
) -> Dict[str, Any]:
"""
Get waveform amplitude data for client-side rendering.
@@ -797,6 +838,8 @@ async def get_waveform_data(job_id: str, num_points: int = 500) -> Dict[str, Any
"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
@@ -837,13 +880,16 @@ async def get_waveform_data(job_id: str, num_points: int = 500) -> Dict[str, Any
async def select_instrumental(
job_id: str,
selection: InstrumentalSelection,
background_tasks: BackgroundTasks
background_tasks: BackgroundTasks,
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:
@@ -885,7 +931,10 @@ async def select_instrumental(
@router.get("/{job_id}/download-urls")
async def get_download_urls(job_id: str) -> dict:
async def get_download_urls(
job_id: str,
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
) -> dict:
"""
Get download URLs for all job output files.
@@ -927,7 +976,12 @@ async def get_download_urls(job_id: str) -> dict:
@router.get("/{job_id}/download/{category}/{file_key}")
async def download_file(job_id: str, category: str, file_key: str):
async def download_file(
job_id: str,
category: str,
file_key: str,
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
):
"""
Stream download a specific file from a completed job.
@@ -1014,7 +1068,11 @@ async def download_file(job_id: str, category: str, file_key: str):
@router.post("/{job_id}/cancel")
async def cancel_job(job_id: str, request: CancelJobRequest) -> dict:
async def cancel_job(
job_id: str,
request: CancelJobRequest,
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
) -> dict:
"""
Cancel a job.
@@ -1035,7 +1093,8 @@ async def cancel_job(job_id: str, request: CancelJobRequest) -> dict:
@router.post("/{job_id}/retry")
async def retry_job(
job_id: str,
background_tasks: BackgroundTasks
background_tasks: BackgroundTasks,
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
) -> dict:
"""
Retry a failed job from the last successful checkpoint.
@@ -1189,7 +1248,8 @@ async def retry_job(
async def get_worker_logs(
job_id: str,
since_index: int = 0,
worker: Optional[str] = None
worker: Optional[str] = None,
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
) -> Dict[str, Any]:
"""
Get worker logs for debugging.
+51 -12
View File
@@ -16,9 +16,9 @@ import json
import os
import tempfile
from pathlib import Path
from typing import Dict, Any, Set
from typing import Dict, Any, Set, Tuple
from fastapi import APIRouter, HTTPException, Request
from fastapi import APIRouter, HTTPException, Request, Depends
from fastapi.responses import FileResponse, StreamingResponse
from starlette.background import BackgroundTask
@@ -27,6 +27,8 @@ 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, require_review_auth
from backend.services.auth_service import UserType
# LyricsTranscriber imports for preview generation
from lyrics_transcriber.types import CorrectionResult
@@ -63,7 +65,10 @@ async def ping(job_id: str):
@router.get("/{job_id}/correction-data")
async def get_correction_data(job_id: str):
async def get_correction_data(
job_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
"""
Get correction data for the review interface.
@@ -129,14 +134,21 @@ async def get_correction_data(job_id: str):
@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)
@@ -189,7 +201,11 @@ async def _stream_audio(job_id: str):
@router.post("/{job_id}/complete")
async def complete_review(job_id: str, updated_data: Dict[str, Any]):
async def complete_review(
job_id: str,
updated_data: Dict[str, Any],
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
"""
Complete the review and save corrected lyrics.
@@ -244,7 +260,11 @@ async def complete_review(job_id: str, updated_data: Dict[str, Any]):
@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).
@@ -256,7 +276,11 @@ async def update_handlers(job_id: str, enabled_handlers: list):
@router.post("/{job_id}/add-lyrics")
async def add_lyrics(job_id: str, data: Dict[str, str]):
async def add_lyrics(
job_id: str,
data: Dict[str, str],
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
"""
Add custom lyrics source and rerun correction.
@@ -354,7 +378,11 @@ async def add_lyrics(job_id: str, data: Dict[str, str]):
@router.post("/{job_id}/preview-video")
async def generate_preview_video(job_id: str, updated_data: Dict[str, Any]):
async def generate_preview_video(
job_id: str,
updated_data: Dict[str, Any],
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
"""
Generate a preview video with the current corrections.
@@ -469,7 +497,11 @@ async def generate_preview_video(job_id: str, updated_data: Dict[str, Any]):
@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()
@@ -510,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.
@@ -522,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,
+6
View File
@@ -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
+16 -6
View File
@@ -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)
+1 -1
View File
@@ -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
+32
View File
@@ -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
+57
View File
@@ -34,6 +34,63 @@ if 'FIRESTORE_EMULATOR_HOST' not in os.environ:
from backend.models.job import Job, JobStatus, JobCreate
@pytest.fixture(autouse=True)
def mock_auth_dependency(request):
"""Mock the require_auth dependency for all tests using FastAPI's dependency override system."""
# Skip for emulator tests and integration tests which use real auth
test_path = str(request.fspath)
if 'emulator' in test_path or 'integration' in test_path:
yield
return
# Skip if FIRESTORE_EMULATOR_HOST is set (running in emulator environment)
import os
if os.environ.get('FIRESTORE_EMULATOR_HOST'):
yield
return
from backend.services.auth_service import UserType
from backend.api.dependencies import require_auth, require_admin, require_review_auth, require_instrumental_auth
from backend.main import app
# Create mock auth functions
async def mock_require_auth():
"""Mock require_auth to always return valid admin credentials."""
return ("test-admin-token", UserType.ADMIN, 999)
async def mock_require_admin():
"""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
# Clean up after test
app.dependency_overrides.clear()
@pytest.fixture
def auth_headers():
"""Get authentication headers for test requests."""
return {
"Authorization": "Bearer test-admin-token",
"Content-Type": "application/json"
}
@pytest.fixture
def mock_firestore():
"""Mock Firestore client for unit tests."""
@@ -27,15 +27,15 @@ pytestmark = pytest.mark.skipif(
class TestEmulatorBasics:
"""Basic emulator connectivity tests."""
def test_health_endpoint(self, client):
def test_health_endpoint(self, client, auth_headers):
"""Test health endpoint works."""
response = client.get("/api/health")
response = client.get("/api/health", )
assert response.status_code == 200
assert response.json()["status"] == "healthy"
def test_root_endpoint(self, client):
def test_root_endpoint(self, client, auth_headers):
"""Test root endpoint works."""
response = client.get("/")
response = client.get("/", )
assert response.status_code == 200
assert response.json()["service"] == "karaoke-gen-backend"
@@ -281,13 +281,13 @@ class TestReviewEndpoints:
time.sleep(0.2)
# Should fail - job not in AWAITING_REVIEW status
response = client.get(f"/api/review/{job_id}/correction-data")
response = client.get(f"/api/review/{job_id}/correction-data", headers=auth_headers)
assert response.status_code == 400
assert "not ready for review" in response.json()["detail"].lower()
def test_review_audio_no_job(self, client):
def test_review_audio_no_job(self, client, auth_headers):
"""Test audio endpoint returns 404 for nonexistent job."""
response = client.get("/api/review/nonexistent-job/audio/")
response = client.get("/api/review/nonexistent-job/audio/", headers=auth_headers)
assert response.status_code == 404
def test_review_preview_video_stub(self, client, auth_headers):
@@ -303,6 +303,7 @@ class TestReviewEndpoints:
# Preview video should return error since job not ready
response = client.post(
f"/api/review/{job_id}/preview-video",
headers=auth_headers,
json={"corrections": [], "corrected_segments": []}
)
# Should return 400 (job not in AWAITING_REVIEW state)
@@ -320,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
+6 -6
View File
@@ -28,20 +28,20 @@ class TestHealthRoutes:
from backend.main import app
return TestClient(app)
def test_health_endpoint_returns_200(self, client):
def test_health_endpoint_returns_200(self, client, auth_headers):
"""Test /api/health returns 200 OK."""
response = client.get("/api/health")
response = client.get("/api/health", )
assert response.status_code == 200
def test_health_endpoint_returns_healthy_status(self, client):
def test_health_endpoint_returns_healthy_status(self, client, auth_headers):
"""Test health endpoint returns healthy status."""
response = client.get("/api/health")
response = client.get("/api/health", )
data = response.json()
assert data["status"] == "healthy"
def test_root_endpoint_returns_200(self, client):
def test_root_endpoint_returns_200(self, client, auth_headers):
"""Test root endpoint returns 200."""
response = client.get("/")
response = client.get("/", )
assert response.status_code == 200
+54 -46
View File
@@ -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',
}]
}
+4 -4
View File
@@ -96,15 +96,15 @@ def auth_headers():
class TestEmulatorBasics:
"""Basic emulator connectivity tests."""
def test_health_endpoint(self, client):
def test_health_endpoint(self, client, auth_headers):
"""Test health endpoint works."""
response = client.get("/api/health")
response = client.get("/api/health", )
assert response.status_code == 200
assert response.json()["status"] == "healthy"
def test_root_endpoint(self, client):
def test_root_endpoint(self, client, auth_headers):
"""Test root endpoint works."""
response = client.get("/")
response = client.get("/", )
assert response.status_code == 200
assert response.json()["service"] == "karaoke-gen-backend"
+1 -1
View File
@@ -188,7 +188,7 @@ class TestFlacfetchClientSearch:
{
"title": "Waterloo",
"artist": "ABBA",
"provider": "Redacted",
"provider": "RED",
"quality": "FLAC 16bit CD",
"seeders": 50,
"index": 0,
+5 -5
View File
@@ -98,7 +98,7 @@ class TestAudioWorkerEndpoint:
)
assert response.status_code == 422
def test_audio_worker_requires_auth(self, client):
def test_audio_worker_requires_auth(self, client, auth_headers):
"""Test audio worker requires authentication."""
response = client.post(
"/api/internal/workers/audio",
@@ -128,7 +128,7 @@ class TestLyricsWorkerEndpoint:
)
assert response.status_code == 422
def test_lyrics_worker_requires_auth(self, client):
def test_lyrics_worker_requires_auth(self, client, auth_headers):
"""Test lyrics worker requires authentication."""
response = client.post(
"/api/internal/workers/lyrics",
@@ -158,7 +158,7 @@ class TestScreensWorkerEndpoint:
)
assert response.status_code == 422
def test_screens_worker_requires_auth(self, client):
def test_screens_worker_requires_auth(self, client, auth_headers):
"""Test screens worker requires authentication."""
response = client.post(
"/api/internal/workers/screens",
@@ -188,7 +188,7 @@ class TestVideoWorkerEndpoint:
)
assert response.status_code == 422
def test_video_worker_requires_auth(self, client):
def test_video_worker_requires_auth(self, client, auth_headers):
"""Test video worker requires authentication."""
response = client.post(
"/api/internal/workers/video",
@@ -218,7 +218,7 @@ class TestRenderVideoWorkerEndpoint:
)
assert response.status_code == 422
def test_render_video_worker_requires_auth(self, client):
def test_render_video_worker_requires_auth(self, client, auth_headers):
"""Test render-video worker requires authentication."""
response = client.post(
"/api/internal/workers/render-video",
+38 -32
View File
@@ -68,20 +68,20 @@ def client(mock_job_manager, mock_worker_service):
class TestGetJob:
"""Tests for GET /api/jobs/{job_id}."""
def test_get_job_returns_200(self, client, mock_job_manager, mock_job):
def test_get_job_returns_200(self, client, mock_job_manager, mock_job, auth_headers):
"""Test getting an existing job returns 200."""
response = client.get("/api/jobs/test123")
response = client.get("/api/jobs/test123", headers=auth_headers)
assert response.status_code == 200
def test_get_job_returns_job_data(self, client, mock_job_manager, mock_job):
def test_get_job_returns_job_data(self, client, mock_job_manager, mock_job, auth_headers):
"""Test response contains job data."""
response = client.get("/api/jobs/test123")
response = client.get("/api/jobs/test123", headers=auth_headers)
data = response.json()
assert data["job_id"] == "test123"
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
@@ -95,58 +95,60 @@ class TestGetJob:
patch('google.auth.default', return_value=(mock_creds, 'test-project')):
from backend.main import app
client = TestClient(app)
response = client.get("/api/jobs/nonexistent")
response = client.get("/api/jobs/nonexistent", headers=auth_headers)
assert response.status_code == 404
class TestListJobs:
"""Tests for GET /api/jobs."""
def test_list_jobs_returns_200(self, client):
def test_list_jobs_returns_200(self, client, auth_headers):
"""Test listing jobs returns 200."""
response = client.get("/api/jobs")
response = client.get("/api/jobs", headers=auth_headers)
assert response.status_code == 200
def test_list_jobs_returns_array(self, client, mock_job_manager):
def test_list_jobs_returns_array(self, client, mock_job_manager, auth_headers):
"""Test response is an array of jobs."""
response = client.get("/api/jobs")
response = client.get("/api/jobs", headers=auth_headers)
data = response.json()
assert isinstance(data, list)
assert len(data) == 1
assert data[0]["job_id"] == "test123"
def test_list_jobs_with_status_filter(self, client, mock_job_manager):
def test_list_jobs_with_status_filter(self, client, mock_job_manager, auth_headers):
"""Test listing jobs with status filter."""
response = client.get("/api/jobs?status=pending")
response = client.get("/api/jobs?status=pending", headers=auth_headers)
assert response.status_code == 200
def test_list_jobs_with_limit(self, client, mock_job_manager):
def test_list_jobs_with_limit(self, client, mock_job_manager, auth_headers):
"""Test listing jobs with limit."""
response = client.get("/api/jobs?limit=10")
response = client.get("/api/jobs?limit=10", headers=auth_headers)
assert response.status_code == 200
class TestCreateJob:
"""Tests for POST /api/jobs."""
def test_create_job_with_url_returns_200(self, client, mock_job_manager):
def test_create_job_with_url_returns_200(self, client, mock_job_manager, auth_headers):
"""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
def test_create_job_returns_job_id(self, client, mock_job_manager):
def test_create_job_returns_job_id(self, client, mock_job_manager, auth_headers):
"""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
def test_create_job_with_artist_title(self, client, mock_job_manager):
def test_create_job_with_artist_title(self, client, mock_job_manager, auth_headers):
"""Test creating job with artist and title."""
response = client.post(
"/api/jobs",
@@ -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
@@ -162,12 +165,12 @@ class TestCreateJob:
class TestDeleteJob:
"""Tests for DELETE /api/jobs/{job_id}."""
def test_delete_job_returns_200(self, client, mock_job_manager):
def test_delete_job_returns_200(self, client, mock_job_manager, auth_headers):
"""Test deleting job returns 200."""
response = client.delete("/api/jobs/test123")
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
@@ -181,7 +184,7 @@ class TestDeleteJob:
patch('google.auth.default', return_value=(mock_creds, 'test-project')):
from backend.main import app
client = TestClient(app)
response = client.delete("/api/jobs/nonexistent")
response = client.delete("/api/jobs/nonexistent", headers=auth_headers)
# Either 200 or 404 depending on implementation
assert response.status_code in [200, 404]
@@ -189,12 +192,13 @@ class TestDeleteJob:
class TestCancelJob:
"""Tests for POST /api/jobs/{job_id}/cancel."""
def test_cancel_job_returns_200(self, client, mock_job_manager, mock_job):
def test_cancel_job_returns_200(self, client, mock_job_manager, mock_job, auth_headers):
"""Test cancelling job returns 200."""
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
@@ -202,7 +206,7 @@ class TestCancelJob:
class TestSubmitCorrections:
"""Tests for POST /api/jobs/{job_id}/corrections."""
def test_submit_corrections_returns_200(self, client, mock_job_manager, mock_job):
def test_submit_corrections_returns_200(self, client, mock_job_manager, mock_job, auth_headers):
"""Test submitting corrections returns 200."""
# Job needs to be in AWAITING_REVIEW or IN_REVIEW status
review_job = Job(
@@ -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]
@@ -231,11 +236,12 @@ class TestSubmitCorrections:
class TestSelectInstrumental:
"""Tests for POST /api/jobs/{job_id}/select-instrumental."""
def test_select_instrumental_requires_selection_field(self, client, mock_job_manager, mock_job):
def test_select_instrumental_requires_selection_field(self, client, mock_job_manager, mock_job, auth_headers):
"""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
@@ -244,9 +250,9 @@ class TestSelectInstrumental:
class TestStartReview:
"""Tests for POST /api/jobs/{job_id}/start-review."""
def test_start_review_endpoint_exists(self, client, mock_job_manager, mock_job):
def test_start_review_endpoint_exists(self, client, mock_job_manager, mock_job, auth_headers):
"""Test start review endpoint exists."""
response = client.post("/api/jobs/test123/start-review")
response = client.post("/api/jobs/test123/start-review", headers=auth_headers)
# Should not be 404 or 405
assert response.status_code not in [404, 405]
+9 -2
View File
@@ -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 = {
+42 -17
View File
@@ -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."""
@@ -65,37 +73,41 @@ def client(mock_services):
class TestFileUploadEndpoint:
"""Tests for POST /api/jobs/upload."""
def test_upload_flac_returns_200(self, client, mock_services):
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):
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):
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):
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):
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):
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):
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):
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):
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):
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):
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):
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):
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):
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):
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):
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):
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
View File
@@ -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'
+1
View File
@@ -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,
)
+4 -4
View File
@@ -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 -11
View File
@@ -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
+481
View File
@@ -0,0 +1,481 @@
# Frontend Guide - Karaoke Generator Web UI
## Overview
The karaoke-gen frontend is a Next.js-based static web application deployed to GitHub Pages at **https://gen.nomadkaraoke.com**. It provides a web interface for submitting jobs to the backend API, monitoring job progress, and managing karaoke video generation.
## Architecture
### Deployment Topology
```
┌─────────────────────────────────────────────────────────┐
│ gen.nomadkaraoke.com (GitHub Pages) │
│ - Next.js static export │
│ - Pure client-side React application │
│ - No server-side rendering │
└────────────────┬────────────────────────────────────────┘
│
│ API calls (HTTPS)
▼
┌─────────────────────────────────────────────────────────┐
│ api.nomadkaraoke.com (Cloud Run) │
│ - FastAPI backend │
│ - Requires Bearer token authentication │
│ - Manages jobs, storage, workers │
└─────────────────────────────────────────────────────────┘
```
### Key Components
- **Frontend Domain**: `gen.nomadkaraoke.com` → GitHub Pages (static HTML/CSS/JS)
- **Backend API**: `api.nomadkaraoke.com` → Google Cloud Run
- **Framework**: Next.js 16.0.7 with Turbopack (static export mode)
- **UI Library**: React 19 + shadcn/ui components
- **State Management**: React hooks (useState, useEffect)
- **Storage**: localStorage for auth tokens (client-side only)
## Authentication
### How It Works
The backend API requires **Bearer token authentication** for all requests. The frontend implements client-side token management:
1. **Token Storage**: Tokens are stored in browser localStorage
2. **Token Input**: Users enter tokens via the AuthBanner component
3. **API Requests**: All API calls include `Authorization: Bearer <token>` header
4. **Token Persistence**: Tokens persist across browser sessions until cleared
### Getting a Token
Tokens are managed by administrators. Users need to contact an admin to receive an access token. There is no self-service signup.
**Admin token management**: Admin tokens are stored in Google Cloud Secret Manager (`ADMIN_TOKENS` secret).
### Using Authentication in the UI
```typescript
// Import auth functions
import { setAccessToken, getAccessToken, clearAccessToken } from '@/lib/api';
// Set token (after user input)
setAccessToken('your-token-here');
// Get current token
const token = getAccessToken();
// Clear token (logout)
clearAccessToken();
```
## Features
### 1. Job Submission
Three methods for submitting karaoke generation jobs:
#### File Upload
- Upload audio files directly (FLAC, WAV, MP3, etc.)
- Provide artist and title metadata
- Automatic processing starts immediately
#### YouTube URL
- Submit a YouTube video URL
- Backend downloads audio automatically
- Provide artist and title metadata
#### Audio Search
- Search by artist and title
- Backend finds high-quality audio sources
- Select from multiple results
- Automatic download and processing
### 2. Job Monitoring
Real-time job status tracking with:
- **Status badges**: Visual indicators (Pending, Processing, Awaiting Review, etc.)
- **Progress bars**: Visual progress for active jobs
- **Auto-refresh**: Updates every 10 seconds
- **Manual refresh**: Click refresh button anytime
**Job Statuses**:
- `PENDING` - Job created, waiting to start
- `DOWNLOADING` - Fetching audio
- `PROCESSING_AUDIO` - Separating vocals/instrumental
- `PROCESSING_LYRICS` - Transcribing lyrics
- `AWAITING_REVIEW` - Ready for human review
- `AWAITING_INSTRUMENTAL_SELECTION` - User needs to select instrumental
- `RENDERING_VIDEO` - Creating final video
- `UPLOADING` - Distributing to YouTube/Dropbox
- `COMPLETE` - Finished successfully
- `FAILED` - Error occurred
- `CANCELLED` - User cancelled
### 3. Interactive Elements
#### Lyrics Review
- Launch lyrics correction UI in new tab
- Make timing and text corrections
- Submit corrections to trigger video rendering
#### Instrumental Selection
- Preview multiple instrumental options
- Select best quality instrumental
- Audio player for A/B comparison
#### Job Actions
- **Cancel**: Stop a running job
- **Retry**: Restart a failed job
- **Delete**: Remove job and associated files
- **View Logs**: See detailed processing logs
### 4. Output Access
When jobs complete, access outputs via:
- **YouTube**: Direct link to uploaded video
- **Dropbox**: Link to Dropbox folder with files
- **Direct Downloads**: Download MP4, CDG, TXT files
## Component Structure
### Modular Architecture
```
frontend/
├── app/
│ ├── page.tsx # Main application page
│ ├── layout.tsx # Root layout with metadata
│ └── globals.css # Global styles and CSS variables
│
├── components/
│ ├── auth-banner.tsx # Authentication UI
│ │
│ ├── job/ # Job-related components
│ │ ├── JobCard.tsx # Individual job display
│ │ ├── JobSubmission.tsx # Job creation forms
│ │ ├── JobActions.tsx # Job management buttons
│ │ ├── JobLogs.tsx # Log viewer
│ │ ├── OutputLinks.tsx # Download/distribution links
│ │ └── InstrumentalSelector.tsx # Instrumental picker
│ │
│ ├── audio-search/ # Audio search feature
│ │ └── AudioSearchDialog.tsx
│ │
│ └── ui/ # Reusable UI primitives (shadcn/ui)
│ ├── button.tsx
│ ├── card.tsx
│ ├── dialog.tsx
│ ├── tabs.tsx
│ └── ... (more)
│
└── lib/
├── api.ts # API client (all backend calls)
├── types.ts # TypeScript type definitions
└── utils.ts # Utility functions
```
### Key Files
#### `lib/api.ts` - API Client
The central hub for all backend communication:
```typescript
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'https://api.nomadkaraoke.com';
export const api = {
// Authentication
setAccessToken(token: string): void
getAccessToken(): string | null
clearAccessToken(): void
// Job Management
listJobs(params?: { status?: string; limit?: number }): Promise<Job[]>
getJob(jobId: string): Promise<Job>
uploadJob(file: File, artist: string, title: string): Promise<JobResponse>
createJobFromUrl(body: CreateJobFromUrlRequest): Promise<JobResponse>
cancelJob(jobId: string, reason?: string): Promise<void>
retryJob(jobId: string): Promise<void>
deleteJob(jobId: string): Promise<void>
// Audio Search
searchAudio(request: AudioSearchRequest): Promise<AudioSearchResponse>
getAudioSearchResults(jobId: string): Promise<AudioSearchResult[]>
selectAudioResult(jobId: string, resultIndex: number): Promise<void>
// Lyrics Review
getReviewData(jobId: string): Promise<ReviewData>
completeReview(jobId: string, corrections: any): Promise<void>
// Instrumental Selection
getInstrumentalOptions(jobId: string): Promise<InstrumentalOption[]>
selectInstrumental(jobId: string, sourceIndex: number): Promise<void>
// Outputs
getDownloadUrls(jobId: string): Promise<DownloadUrls>
}
```
#### `components/auth-banner.tsx` - Authentication UI
Prominent banner at top of page for token management:
- Shows "Authentication Required" when no token
- Displays truncated token when authenticated
- Password-masked input field
- Persistent across page reloads
#### `components/job/JobCard.tsx` - Job Display
Main component for displaying individual jobs:
- Collapsible details view
- Status badges and progress bars
- Conditional rendering based on job state
- Integrates all sub-components (actions, logs, outputs, etc.)
## Styling
### Color Scheme
Matches the instrumental review UI for consistency:
```css
/* Background colors */
--bg: #0f0f0f; /* Very dark, neutral */
--card: #1a1a1a; /* Card backgrounds */
/* Text colors */
--text: #e5e5e5; /* Primary text */
--text-muted: #999999; /* Secondary text */
/* UI colors */
--primary: #3b82f6; /* Blue (actions, links) */
--success: #10b981; /* Green (success states) */
--warning: #f59e0b; /* Orange (warnings) */
--error: #ef4444; /* Red (errors) */
--border: #2a2a2a; /* Borders */
```
### Typography
System font stack for fast loading and native feel:
```css
--font-sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
--font-mono: "SF Mono", Monaco, "Cascadia Code", "Courier New", monospace;
```
## Local Development
### Setup
```bash
cd frontend
# Install dependencies
npm ci --legacy-peer-deps
# Start dev server with hot-reload
npm run dev
# → http://localhost:3000
# Build static export
npm run build
# → Output: frontend/out/
# Run tests
npm test
```
### Environment Variables
Create `.env.local` for local development:
```bash
# Optional: Override API URL for local backend testing
NEXT_PUBLIC_API_URL=http://localhost:8080
```
### Testing Against Production API
The default configuration connects to the production API at `api.nomadkaraoke.com`, so you can develop locally while using the real backend.
**Important**: You'll need a valid access token to make API requests.
## Deployment
### Automatic Deployment (CI/CD)
Changes to `main` branch automatically deploy via GitHub Actions:
1. **Trigger**: Push to `main` or merge PR
2. **Build**: `npm ci --legacy-peer-deps && npm run build`
3. **Deploy**: Upload `frontend/out/` to GitHub Pages
4. **Live**: Available at `gen.nomadkaraoke.com` within ~2 minutes
### CI Workflow
`.github/workflows/ci.yml`:
```yaml
deploy-frontend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- name: Install dependencies
working-directory: frontend
run: npm ci --legacy-peer-deps
- name: Build
working-directory: frontend
run: npm run build
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: frontend/out
```
### Manual Deployment
If needed, manually deploy via GitHub Pages settings:
1. Build: `cd frontend && npm run build`
2. Upload `frontend/out/` contents to GitHub Pages
3. Wait for GitHub Pages to rebuild
## Configuration Files
### `next.config.mjs`
```javascript
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'export', // Static export for GitHub Pages
trailingSlash: true, // Ensures paths work on static hosts
typescript: {
ignoreBuildErrors: false // Enforce type safety
}
};
```
### `package.json`
Key dependencies:
- `next@16.0.7` - Framework
- `react@19.0.0` - UI library
- `lucide-react` - Icon library
- `tailwindcss` - Utility-first CSS
- `@testing-library/react` - Testing
## Common Issues
### Issue: API requests return 404
**Cause**: Frontend trying to call `gen.nomadkaraoke.com/api` instead of `api.nomadkaraoke.com/api`
**Solution**: Verify `API_BASE_URL` in `lib/api.ts` is set to `https://api.nomadkaraoke.com`
### Issue: API requests return 401 Unauthorized
**Cause**: No token or invalid token
**Solution**: Enter a valid access token via the AuthBanner
### Issue: Changes not appearing after deployment
**Cause**: GitHub Pages caching or CDN propagation delay
**Solutions**:
- Wait 2-5 minutes for CDN to update
- Hard refresh browser (Cmd/Ctrl + Shift + R)
- Check GitHub Actions for deployment status
### Issue: Build fails in CI with dependency conflicts
**Cause**: React 19 peer dependency mismatch with testing libraries
**Solution**: Use `npm ci --legacy-peer-deps` (already configured in CI)
## Testing
### Running Tests
```bash
cd frontend
# Run all tests
npm test
# Run with coverage
npm run test:coverage
# Run in CI mode (non-interactive)
npm run test:ci
```
### Test Structure
```
frontend/
├── components/__tests__/
│ ├── JobCard.test.tsx
│ └── ...
└── lib/__tests__/
├── api.test.ts
└── ...
```
### Coverage Requirements
Minimum 70% code coverage enforced in CI (though frontend tests are still being expanded).
## API Integration
### Request Flow
1. User action in UI (e.g., click "Create Job")
2. Component calls API function from `lib/api.ts`
3. API function adds auth header if token exists
4. Fetch request to `api.nomadkaraoke.com`
5. Response parsed and returned
6. Component updates UI with response data
### Error Handling
All API errors are wrapped in `ApiError` class:
```typescript
try {
const jobs = await api.listJobs({ limit: 20 });
setJobs(jobs);
} catch (error) {
if (error instanceof ApiError) {
console.error(`API Error ${error.status}: ${error.message}`);
// error.data contains full response body
}
}
```
## Future Enhancements
Potential improvements for future iterations:
1. **OAuth Integration**: Replace manual token entry with OAuth flow
2. **Real-time Updates**: WebSocket connection for live job updates
3. **Admin Dashboard**: User management, token generation, system stats
4. **Job History**: Pagination and filtering for large job lists
5. **Batch Operations**: Select and manage multiple jobs at once
6. **Mobile Optimization**: Responsive design improvements for mobile devices
7. **Offline Support**: Service worker for offline functionality
8. **Enhanced Testing**: Increase test coverage to 90%+
## Related Documentation
- [Backend API Reference](../README.md#backend-api-reference)
- [Cloud Run Deployment](../03-deployment/CLOUD-RUN-DEPLOYMENT.md)
- [Architecture Overview](./ARCHITECTURE.md)
- [GitHub Pages Setup](.github/workflows/ci.yml)
---
**Last Updated**: December 2025
**Frontend Version**: Deployed from `main` branch commit `91f51d6`
@@ -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
+145
View File
@@ -0,0 +1,145 @@
# Backend API Authentication - Remaining Work
## Overview
This document tracks the progress of adding authentication requirements to ALL backend API endpoints. Currently, many endpoints are publicly accessible without any authentication, which is a **major security vulnerability**.
## Completed Endpoints
### ✅ jobs.py (20 endpoints) - DONE
- All job management endpoints now require `Depends(require_auth)`
- Includes: create, get, list, delete, bulk_delete, review endpoints, instrumental selection, download, cancel, retry, logs
### ✅ file_upload.py (6 endpoints) - DONE
- upload_and_create_job
- create_job_with_upload_urls
- mark_uploads_complete
- create_job_from_url
- create_finalise_only_job
- mark_finalise_uploads_complete
### ✅ audio_search.py (3 endpoints) - DONE
- search_audio
- get_audio_search_results
- select_audio_source
### ⚠️ review.py (12 endpoints) - PARTIAL (4/12 done)
**Completed:**
- get_correction_data ✅
- complete_review ✅
- add_lyrics ✅
- generate_preview_video ✅
**Remaining - Need Auth:**
- ❌ ping - Health check (maybe OK without auth?)
- ❌ get_audio_with_hash - Audio streaming for review UI
- ❌ get_audio_no_hash - Audio streaming for review UI
- ❌ update_handlers - Correction handlers config
- ❌ get_preview_video - Preview video streaming
- ❌ submit_annotation - ML training data
- ❌ get_annotation_stats - ML stats
- ❌ (1 more endpoint not yet reviewed)
**Special Considerations:**
- Audio streaming endpoints (`get_audio_*`) are used by the review UI frontend. May need token passed via query param or special handling.
- `ping` endpoint is just a health check - possibly OK without auth
## Remaining Routes
### ❌ auth.py (8 endpoints) - TODO
These are auth-related endpoints themselves, so they have special requirements:
- `/auth/status` - Get OAuth credentials status (probably needs auth)
- `/auth/status/{service}` - Get service credential status (probably needs auth)
- `/auth/validate` - Validate credentials (probably needs auth)
- `/auth/youtube/device` - Start YouTube device auth (admin only)
- `/auth/youtube/device/{device_code}` - Poll YouTube auth (admin only)
- `/auth/gdrive/device` - Start GDrive device auth (admin only)
- `/auth/gdrive/device/{device_code}` - Poll GDrive auth (admin only)
- (1 more endpoint)
**Recommendation:** Most/all of these should require admin auth (`Depends(require_admin)`)
### ❌ health.py (3 endpoints) - TODO
- `/health` - Basic health check (probably OK without auth for k8s/monitoring)
- `/health/detailed` - Detailed health (should require auth)
- `/readiness` - Readiness check for Cloud Run (probably OK without auth)
**Recommendation:**
- Keep `/health` and `/readiness` unauthenticated for infrastructure monitoring
- Require auth for `/health/detailed` as it may expose sensitive info
### ❌ internal.py (6 endpoints) - CRITICAL
**All worker trigger endpoints - MUST have auth!** Currently using `X-Admin-Token` header but needs formal validation:
- `/internal/workers/audio` - Trigger audio worker
- `/internal/workers/lyrics` - Trigger lyrics worker
- `/internal/workers/screens` - Trigger screens worker
- `/internal/workers/video` - Trigger video worker
- `/internal/workers/render-video` - Trigger render worker
- `/internal/health` - Internal health (already has `require_admin`)
**Current State:** These endpoints check for `X-Admin-Token` in the request, but this should use the formal `require_admin` dependency.
**Recommendation:** ALL internal endpoints should use `Depends(require_admin)`
## Implementation Strategy
### Phase 1: Critical Security Fixes (HIGH PRIORITY)
1. ✅ Complete jobs.py, file_upload.py, audio_search.py
2. ❌ **Secure internal.py worker triggers** - These are the most critical as they allow arbitrary job manipulation
3. ❌ **Secure auth.py admin endpoints** - Prevent unauthorized OAuth credential management
### Phase 2: User-Facing Endpoints
1. ❌ Complete review.py endpoints (with special handling for streaming)
2. ❌ health.py detailed endpoint
### Phase 3: Testing & Documentation
1. ❌ Update frontend to always include auth token
2. ❌ Test all endpoints with/without auth
3. ❌ Update API documentation
4. ❌ Add integration tests for auth
## Testing Checklist
After adding auth to all endpoints:
- [ ] Test job creation without token → should return 401
- [ ] Test job listing without token → should return 401
- [ ] Test worker triggers without admin token → should return 401 or 403
- [ ] Test OAuth endpoints without admin token → should return 401 or 403
- [ ] Test health endpoint without token → should work (by design)
- [ ] Test authenticated requests with valid user token → should work
- [ ] Test authenticated requests with valid admin token → should work
- [ ] Update frontend auth flow to handle 401 errors gracefully
## Notes
- The authentication system is already implemented in `backend/api/dependencies.py`
- Functions available: `require_auth()`, `require_admin()`, `optional_auth()`
- Tokens are validated against `ADMIN_TOKENS` env var or Firestore user tokens
- Frontend already has token storage in localStorage via `AuthBanner` component
## Migration Path for Frontend
Once all endpoints require auth:
1. Frontend must obtain a token (either admin token or user token from a signup flow)
2. Token must be included in Authorization header: `Authorization: Bearer <token>`
3. Alternatively, some endpoints support `?token=<token>` query parameter
4. Update frontend API client to always include auth
##Frontend Update Required
Current state: Frontend has AuthBanner that prompts for token, but some endpoints worked without auth (security issue).
New state: ALL endpoints require auth, so users MUST provide a token before using the app.
Update `frontend/lib/api.ts` to:
- Throw user-friendly error if token is missing when calling authenticated endpoints
- Handle 401 responses by prompting user to re-authenticate
- Consider implementing a "logged out" state in the UI
+140
View File
@@ -0,0 +1,140 @@
# Test Fixes Needed for Authentication
## Problem
After adding `Depends(require_auth)` to 33+ backend endpoints, all unit and integration tests are failing because they don't include authentication headers in their requests.
## Solution
All test requests to authenticated endpoints need to include:
```python
headers={"Authorization": "Bearer test-admin-token"}
```
## Files Need Updating
### 1. Global Fixture (DONE)
✅ `backend/tests/conftest.py` - Added mock_auth_service and auth_headers fixtures
### 2. Test Files to Update
Each test file needs:
1. Mock auth service in the client fixture
2. Add `auth_headers` parameter to test methods
3. Pass `headers=auth_headers` to all client requests (get, post, put, delete)
Files:
- `backend/tests/test_jobs_api.py` - ~15 test methods
- `backend/tests/test_upload_api.py` - ~10 test methods
- `backend/tests/test_audio_search.py` - ~5 test methods
- `backend/tests/test_api_routes.py` - ~10 test methods
- `backend/tests/test_instrumental_api.py` - ~5 test methods
- `backend/tests/emulator/test_emulator_integration.py` - ~20 test methods
## Quick Fix Script
Rather than manually updating 60+ test methods, here's a Python script to auto-fix them:
```python
#!/usr/bin/env python3
"""
Auto-fix test files to include authentication headers.
"""
import re
from pathlib import Path
def fix_test_file(filepath):
"""Add auth_headers to client requests in test file."""
with open(filepath, 'r') as f:
content = f.read()
# Pattern: client.METHOD(
# Replace with: client.METHOD(..., headers=auth_headers)
patterns = [
# client.get("/path")
(r'client\.(get|post|put|delete|patch)\((["\'][^"\']+["\'])\)',
r'client.\1(\2, headers=auth_headers)'),
# client.get("/path", json={...})
(r'client\.(get|post|put|delete|patch)\((["\'][^"\']+["\']),\s*json=',
r'client.\1(\2, headers=auth_headers, json='),
# client.post("/path", data={...})
(r'client\.(get|post|put|delete|patch)\((["\'][^"\']+["\']),\s*data=',
r'client.\1(\2, headers=auth_headers, data='),
# client.post("/path", files={...})
(r'client\.(post)\((["\'][^"\']+["\']),\s*files=',
r'client.\1(\2, headers=auth_headers, files='),
]
modified = content
for pattern, replacement in patterns:
modified = re.sub(pattern, replacement, modified)
# Add auth_headers parameter to test methods that don't have it
# def test_something(self, client, mock_job):
# -> def test_something(self, client, mock_job, auth_headers):
modified = re.sub(
r'def (test_\w+)\(self,\s*client([^)]*)\):',
r'def \1(self, client\2, auth_headers):',
modified
)
with open(filepath, 'w') as f:
f.write(modified)
print(f"Fixed: {filepath}")
# Find all test files
test_dir = Path("backend/tests")
for test_file in test_dir.rglob("test_*.py"):
if 'conftest' not in str(test_file):
fix_test_file(test_file)
print("Done!")
```
## Manual Approach
For each test method:
**Before:**
```python
def test_get_job(self, client, mock_job_manager):
response = client.get("/api/jobs/test123")
assert response.status_code == 200
```
**After:**
```python
def test_get_job(self, client, mock_job_manager, auth_headers):
response = client.get("/api/jobs/test123", headers=auth_headers)
assert response.status_code == 200
```
## Emulator Tests
Emulator tests already have `auth_headers` fixture in `backend/tests/emulator/conftest.py`.
Just need to:
1. Add `auth_headers` parameter to test methods
2. Pass `headers=auth_headers` to client requests
## Health Endpoints
Health endpoints (`/api/health`, `/api/readiness`) should remain unauthenticated, so those tests don't need auth headers.
## Internal API Tests
Internal API tests in `test_internal_api.py` already have auth handling via `X-Admin-Token` header. May need updating if we migrate to formal `require_admin`.
## Test Coverage
After fixes, run:
```bash
cd backend
python -m pytest tests/ -v --ignore=tests/integration
```
Should see all tests passing.
Submodule flacfetch deleted from 35ae8994b8.
+36 -48
View File
@@ -4,45 +4,46 @@
@custom-variant dark (&:is(.dark *));
:root {
/* Nomad Karaoke brand colors - matching nomadkaraoke.com */
--background: oklch(0.22 0.04 260); /* Dark slate blue #2b3544 */
--foreground: oklch(0.95 0.01 0); /* White text */
--card: oklch(0.26 0.04 260); /* Slightly lighter slate for cards */
--card-foreground: oklch(0.95 0.01 0);
--popover: oklch(0.26 0.04 260);
--popover-foreground: oklch(0.95 0.01 0);
--primary: oklch(0.68 0.22 340); /* Pink #ff7acc */
--primary-foreground: oklch(0.98 0.01 0);
--secondary: oklch(0.78 0.15 85); /* Gold/yellow #ffc857 */
--secondary-foreground: oklch(0.15 0.01 270);
--muted: oklch(0.3 0.04 260);
--muted-foreground: oklch(0.65 0.01 260);
--accent: oklch(0.68 0.22 340);
--accent-foreground: oklch(0.98 0.01 0);
--destructive: oklch(0.55 0.22 25);
--destructive-foreground: oklch(0.98 0.01 0);
--border: oklch(0.32 0.04 260);
--input: oklch(0.32 0.04 260);
--ring: oklch(0.68 0.22 340);
--chart-1: oklch(0.68 0.22 340);
--chart-2: oklch(0.78 0.15 85);
--chart-3: oklch(0.55 0.2 280);
--chart-4: oklch(0.6 0.18 180);
--chart-5: oklch(0.65 0.2 60);
/* Matching instrumental review UI color scheme */
--bg: #0f0f0f;
--card: #1a1a1a;
--card-border: #2a2a2a;
--waveform-bg: #0d1117;
--text: #e5e5e5;
--text-muted: #888;
--primary: #3b82f6;
--primary-hover: #2563eb;
--secondary: #252525;
--secondary-hover: #333;
--success: #22c55e;
--warning: #f59e0b;
--danger: #ef4444;
--pink: #ec4899;
--blue: #60a5fa;
/* Tailwind compatibility mappings */
--background: var(--bg);
--foreground: var(--text);
--card-foreground: var(--text);
--popover: var(--card);
--popover-foreground: var(--text);
--primary-foreground: #ffffff;
--secondary-foreground: var(--text);
--muted: var(--secondary);
--muted-foreground: var(--text-muted);
--accent: var(--primary);
--accent-foreground: #ffffff;
--destructive: var(--danger);
--destructive-foreground: #ffffff;
--border: var(--card-border);
--input: var(--secondary);
--ring: var(--primary);
--radius: 0.5rem;
--sidebar: oklch(0.26 0.04 260);
--sidebar-foreground: oklch(0.95 0.01 0);
--sidebar-primary: oklch(0.68 0.22 340);
--sidebar-primary-foreground: oklch(0.98 0.01 0);
--sidebar-accent: oklch(0.3 0.04 260);
--sidebar-accent-foreground: oklch(0.95 0.01 0);
--sidebar-border: oklch(0.32 0.04 260);
--sidebar-ring: oklch(0.68 0.22 340);
}
@theme inline {
--font-sans: "Geist", "Geist Fallback";
--font-mono: "Geist Mono", "Geist Mono Fallback";
--font-sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
--font-mono: "SF Mono", Monaco, "Cascadia Code", monospace;
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
@@ -62,23 +63,10 @@
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-5: var(--chart-5);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
}
@layer base {
+1 -1
View File
@@ -27,7 +27,7 @@ export default function RootLayout({
}>) {
return (
<html lang="en" className="dark">
<body className="font-sans antialiased bg-slate-950 text-slate-100">
<body className="font-sans antialiased" style={{ background: 'var(--bg)', color: 'var(--text)' }}>
{children}
</body>
</html>
+5 -1
View File
@@ -7,6 +7,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
import { Music2, RefreshCw, Loader2 } from "lucide-react"
import { JobCard } from "@/components/job"
import { JobSubmission } from "@/components/job/JobSubmission"
import { AuthBanner } from "@/components/auth-banner"
export default function HomePage() {
const [jobs, setJobs] = useState<Job[]>([])
@@ -56,7 +57,10 @@ export default function HomePage() {
</div>
</header>
<main className="container mx-auto px-4 py-8 max-w-5xl">
<main className="container mx-auto px-4 py-8 max-w-5xl space-y-6">
{/* Authentication Banner */}
<AuthBanner />
<div className="grid lg:grid-cols-2 gap-8">
{/* Submit Job Card */}
<Card className="border-slate-800 bg-slate-900/50 backdrop-blur">
+107
View File
@@ -0,0 +1,107 @@
'use client';
import { useState, useEffect } from 'react';
import { X, KeyRound } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { setAccessToken, getAccessToken, clearAccessToken } from '@/lib/api';
export function AuthBanner() {
const [token, setToken] = useState('');
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [showInput, setShowInput] = useState(false);
useEffect(() => {
const storedToken = getAccessToken();
if (storedToken) {
setIsAuthenticated(true);
setToken(storedToken.substring(0, 8) + '...');
} else {
setShowInput(true);
}
}, []);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (token.trim()) {
setAccessToken(token.trim());
setIsAuthenticated(true);
setShowInput(false);
// Reload to fetch jobs with auth
window.location.reload();
}
};
const handleLogout = () => {
clearAccessToken();
setIsAuthenticated(false);
setToken('');
setShowInput(true);
window.location.reload();
};
if (isAuthenticated && !showInput) {
return (
<div className="bg-green-500/10 border border-green-500/20 text-green-400 px-4 py-2 rounded-lg flex items-center justify-between text-sm">
<div className="flex items-center gap-2">
<KeyRound className="h-4 w-4" />
<span>Authenticated</span>
</div>
<Button
variant="ghost"
size="sm"
onClick={handleLogout}
className="h-6 px-2 text-xs text-green-400 hover:text-green-300"
>
Logout
</Button>
</div>
);
}
return (
<div className="bg-yellow-500/10 border border-yellow-500/20 text-yellow-400 px-4 py-3 rounded-lg">
<div className="flex items-start gap-3">
<KeyRound className="h-5 w-5 mt-0.5 flex-shrink-0" />
<div className="flex-1">
<p className="font-medium mb-2">Authentication Required</p>
{showInput ? (
<form onSubmit={handleSubmit} className="flex gap-2">
<Input
type="password"
placeholder="Enter access token"
value={token}
onChange={(e) => setToken(e.target.value)}
className="flex-1 bg-[var(--secondary)] border-[var(--card-border)] text-sm"
/>
<Button type="submit" size="sm" disabled={!token.trim()}>
Authenticate
</Button>
</form>
) : (
<Button
variant="outline"
size="sm"
onClick={() => setShowInput(true)}
className="mt-1"
>
Enter Token
</Button>
)}
<p className="text-xs mt-2 text-[var(--text-muted)]">
Contact an admin to get an access token
</p>
</div>
{showInput && (
<button
onClick={() => setShowInput(false)}
className="text-[var(--text-muted)] hover:text-[var(--text)]"
>
<X className="h-4 w-4" />
</button>
)}
</div>
</div>
);
}
+45 -4
View File
@@ -2,7 +2,40 @@
* API client for karaoke-gen backend
*/
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'https://gen.nomadkaraoke.com';
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'https://api.nomadkaraoke.com';
// Token management - stored in localStorage (client-side only)
let accessToken: string | null = null;
if (typeof window !== 'undefined') {
accessToken = localStorage.getItem('karaoke_access_token');
}
export function setAccessToken(token: string) {
accessToken = token;
if (typeof window !== 'undefined') {
localStorage.setItem('karaoke_access_token', token);
}
}
export function getAccessToken(): string | null {
return accessToken;
}
export function clearAccessToken() {
accessToken = null;
if (typeof window !== 'undefined') {
localStorage.removeItem('karaoke_access_token');
}
}
function getAuthHeaders(): HeadersInit {
const headers: HeadersInit = {};
if (accessToken) {
headers['Authorization'] = `Bearer ${accessToken}`;
}
return headers;
}
export interface Job {
job_id: string;
@@ -125,7 +158,9 @@ export const api = {
if (params?.limit) searchParams.set('limit', String(params.limit));
const url = `${API_BASE_URL}/api/jobs${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
const response = await fetch(url);
const response = await fetch(url, {
headers: getAuthHeaders()
});
return handleResponse<Job[]>(response);
},
@@ -133,7 +168,9 @@ export const api = {
* Get a single job by ID
*/
async getJob(jobId: string): Promise<Job> {
const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}`);
const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}`, {
headers: getAuthHeaders()
});
return handleResponse<Job>(response);
},
@@ -171,6 +208,7 @@ export const api = {
const response = await fetch(`${API_BASE_URL}/api/jobs/upload`, {
method: 'POST',
headers: getAuthHeaders(),
body: formData,
});
@@ -201,7 +239,10 @@ export const api = {
const response = await fetch(`${API_BASE_URL}/api/jobs/create-from-url`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify(body),
});
+7 -3
View File
@@ -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" | \
+62 -9
View File
@@ -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"
+33 -17
View File
@@ -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 })
+10 -12
View File
@@ -901,11 +901,11 @@ class KaraokePrep:
for sig in (signal.SIGINT, signal.SIGTERM):
loop.remove_signal_handler(sig)
async def shutdown(self, signal):
async def shutdown(self, signal_received):
"""Handle shutdown signals gracefully."""
self.logger.info(f"Received exit signal {signal.name}...")
self.logger.info(f"Received exit signal {signal_received.name}...")
# Get all running tasks
# Get all running tasks except the current shutdown task
tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]
if tasks:
@@ -914,17 +914,15 @@ class KaraokePrep:
for task in tasks:
task.cancel()
self.logger.info("Received cancellation request, cleaning up...")
# Wait for all tasks to complete with cancellation
try:
await asyncio.gather(*tasks, return_exceptions=True)
except asyncio.CancelledError:
pass
# Use return_exceptions=True to gather all results without raising
await asyncio.gather(*tasks, return_exceptions=True)
# Force exit after cleanup
self.logger.info("Cleanup complete, exiting...")
sys.exit(0) # Add this line to force exit
self.logger.info("Cleanup complete")
# Raise KeyboardInterrupt to propagate the cancellation up the call stack
# This allows the main event loop to exit cleanly
raise KeyboardInterrupt()
async def process_playlist(self):
if self.artist is None or self.title is None:
+4 -3
View File
@@ -352,9 +352,10 @@ 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', 'local')),
help="Lyrics review UI URL. Use 'local' for bundled frontend (default), "
"'http://localhost:5173' for Vite dev server, or 'https://lyrics.nomadkaraoke.com' for hosted. "
default=os.environ.get('REVIEW_UI_URL', os.environ.get('LYRICS_REVIEW_UI_URL', 'https://gen.nomadkaraoke.com/lyrics')),
help="Lyrics review UI URL. For remote mode: defaults to 'https://gen.nomadkaraoke.com/lyrics'. "
"For local mode: defaults to bundled frontend (from lyrics_transcriber/frontend/). "
"Use 'http://localhost:5173' to develop against Vite dev server. "
"(env: REVIEW_UI_URL or LYRICS_REVIEW_UI_URL)",
)
remote_group.add_argument(
+22 -3
View File
@@ -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
@@ -303,9 +313,18 @@ async def async_main():
args = parser.parse_args()
# Set review UI URL environment variable for the lyrics transcriber review server
# This allows development against a local frontend dev server (e.g., http://localhost:5173)
# Only set this if the user explicitly wants to use a dev server (e.g., http://localhost:5173)
# By default, let the ReviewServer use its bundled local frontend (served from lyrics_transcriber/frontend/)
# This enables local iteration on the frontend without redeploying
if hasattr(args, 'review_ui_url') and args.review_ui_url:
os.environ['LYRICS_REVIEW_UI_URL'] = args.review_ui_url
# Check if user provided a custom value (not the default hosted URL)
default_hosted_urls = [
'https://gen.nomadkaraoke.com/lyrics',
'https://lyrics.nomadkaraoke.com'
]
if args.review_ui_url.rstrip('/') not in [url.rstrip('/') for url in default_hosted_urls]:
# User explicitly wants a specific URL (e.g., Vite dev server)
os.environ['LYRICS_REVIEW_UI_URL'] = args.review_ui_url
# Process style overrides
try:
@@ -736,7 +755,7 @@ async def async_main():
except UserCancelledError:
logger.info("Operation cancelled by user")
return
except KeyboardInterrupt:
except (KeyboardInterrupt, asyncio.CancelledError):
logger.info("Operation cancelled by user (Ctrl+C)")
return
+26 -3
View File
@@ -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)
@@ -2,7 +2,7 @@
"name": "lyrics-transcriber-frontend",
"private": true,
"homepage": "https://nomadkaraoke.github.io/lyrics-transcriber-frontend",
"version": "0.82.0",
"version": "0.83.0",
"type": "module",
"scripts": {
"dev": "vite",
@@ -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}`);
}
@@ -34056,13 +34056,26 @@ function validateCorrectionData(data) {
return CorrectionDataSchema.parse(data);
}
class LiveApiClient {
constructor(baseUrl) {
constructor(baseUrl, reviewToken) {
__publicField(this, "reviewToken");
__publicField(this, "isUpdatingHandlers", false);
this.baseUrl = baseUrl;
this.baseUrl = baseUrl.replace(/\/$/, "");
this.reviewToken = reviewToken;
}
/**
* Build URL with reviewToken query parameter if available
*/
buildUrl(path) {
const url = `${this.baseUrl}${path}`;
if (this.reviewToken) {
const separator = url.includes("?") ? "&" : "?";
return `${url}${separator}review_token=${encodeURIComponent(this.reviewToken)}`;
}
return url;
}
async getCorrectionData() {
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}`);
}
@@ -34079,7 +34092,7 @@ class LiveApiClient {
corrections: data.corrections,
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"
@@ -34091,14 +34104,14 @@ class LiveApiClient {
}
}
getAudioUrl(audioHash) {
return `${this.baseUrl}/audio/${audioHash}`;
return this.buildUrl(`/audio/${audioHash}`);
}
async generatePreviewVideo(data) {
const updatePayload = {
corrections: data.corrections,
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"
@@ -34114,14 +34127,14 @@ class LiveApiClient {
return await response.json();
}
getPreviewVideoUrl(previewHash) {
return `${this.baseUrl}/preview-video/${previewHash}`;
return this.buildUrl(`/preview-video/${previewHash}`);
}
async updateHandlers(enabledHandlers) {
console.log("API: Starting handler update...");
this.isUpdatingHandlers = true;
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"
@@ -34147,7 +34160,7 @@ class LiveApiClient {
source,
lyrics
};
const response = await fetch(`${this.baseUrl}/add-lyrics`, {
const response = await fetch(this.buildUrl("/add-lyrics"), {
method: "POST",
headers: {
"Content-Type": "application/json"
@@ -34165,7 +34178,7 @@ class LiveApiClient {
}
async submitAnnotations(annotations) {
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"
@@ -34178,7 +34191,7 @@ class LiveApiClient {
}
}
async getAnnotationStats() {
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}`);
}
@@ -38943,10 +38956,12 @@ const TimelineCanvas = reactExports.memo(function TimelineCanvas2({
const deltaTime = time - dragStartRef.current.time;
const updates = [];
for (const [wordId, originalTimes] of dragOriginalTimesRef.current) {
const newStartTime = Math.max(0, originalTimes.start + deltaTime);
const newEndTime = Math.max(newStartTime + 0.05, originalTimes.end + deltaTime);
updates.push({
wordId,
newStartTime: Math.max(0, originalTimes.start + deltaTime),
newEndTime: Math.max(0.05, originalTimes.end + deltaTime)
newStartTime,
newEndTime
});
}
if (updates.length > 0) {
@@ -39275,7 +39290,7 @@ const LyricsSynchronizer = reactExports.memo(function LyricsSynchronizer2({
);
const allWords = reactExports.useMemo(() => getAllWords(workingSegments), [workingSegments]);
const audioDuration = reactExports.useMemo(() => {
if (window.getAudioDuration) {
if (typeof window.getAudioDuration === "function") {
const duration2 = window.getAudioDuration();
return duration2 > 0 ? duration2 : 300;
}
@@ -39347,7 +39362,7 @@ const LyricsSynchronizer = reactExports.memo(function LyricsSynchronizer2({
const [isPlaying, setIsPlaying] = reactExports.useState(false);
reactExports.useEffect(() => {
const checkPlaying = () => {
setIsPlaying(window.isAudioPlaying || false);
setIsPlaying(typeof window.isAudioPlaying === "boolean" ? window.isAudioPlaying : false);
};
checkPlaying();
const interval = setInterval(checkPlaying, 100);
@@ -39359,7 +39374,7 @@ const LyricsSynchronizer = reactExports.memo(function LyricsSynchronizer2({
}
}, [onPlaySegment]);
const handleStopAudio = reactExports.useCallback(() => {
if (window.toggleAudioPlayback && window.isAudioPlaying) {
if (typeof window.toggleAudioPlayback === "function" && window.isAudioPlaying) {
window.toggleAudioPlayback();
}
if (isManualSyncing) {
@@ -39616,7 +39631,7 @@ const LyricsSynchronizer = reactExports.memo(function LyricsSynchronizer2({
if (onPlaySegment) {
onPlaySegment(time);
setTimeout(() => {
if (window.toggleAudioPlayback && window.isAudioPlaying) {
if (typeof window.toggleAudioPlayback === "function" && window.isAudioPlaying) {
window.toggleAudioPlayback();
}
}, 50);
@@ -42923,22 +42938,23 @@ 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));
setApiClient(new LiveApiClient(baseApiUrl, reviewTokenParam || void 0));
setIsReadOnly(false);
if (audioHashParam) {
setAudioHash(audioHashParam);
}
fetchData(baseApiUrl);
fetchData(baseApiUrl, reviewTokenParam || void 0);
} else {
setApiClient(new FileOnlyClient());
setIsReadOnly(true);
}
}, []);
const fetchData = async (baseUrl) => {
const fetchData = async (baseUrl, reviewToken) => {
try {
const client2 = new LiveApiClient(baseUrl);
const client2 = new LiveApiClient(baseUrl, reviewToken);
const data2 = await client2.getCorrectionData();
setData(data2);
} catch (err) {
@@ -43258,7 +43274,7 @@ const theme = createTheme({
spacing: (factor) => `${0.6 * factor}rem`
// Further reduced from 0.8 * factor
});
const version = "0.82.0";
const version = "0.83.0";
const packageJson = {
version
};
@@ -43269,4 +43285,4 @@ ReactDOM$1.createRoot(document.getElementById("root")).render(
/* @__PURE__ */ jsxRuntimeExports.jsx(App, {})
] })
);
//# sourceMappingURL=index-COYImAcx.js.map
//# sourceMappingURL=index-BECn1o8Q.js.map
@@ -1 +1 @@
{"version":3,"file":"index-COYImAcx.js","sources":["../../node_modules/react/cjs/react.production.min.js","../../node_modules/react/index.js","../../node_modules/react/cjs/react-jsx-runtime.production.min.js","../../node_modules/react/jsx-runtime.js","../../node_modules/scheduler/cjs/scheduler.production.min.js","../../node_modules/scheduler/index.js","../../node_modules/react-dom/cjs/react-dom.production.min.js","../../node_modules/react-dom/index.js","../../node_modules/react-dom/client.js","../../node_modules/@mui/utils/esm/formatMuiErrorMessage/formatMuiErrorMessage.js","../../node_modules/@mui/material/styles/identifier.js","../../node_modules/@babel/runtime/helpers/esm/extends.js","../../node_modules/@emotion/sheet/dist/emotion-sheet.esm.js","../../node_modules/stylis/src/Enum.js","../../node_modules/stylis/src/Utility.js","../../node_modules/stylis/src/Tokenizer.js","../../node_modules/stylis/src/Parser.js","../../node_modules/stylis/src/Serializer.js","../../node_modules/stylis/src/Middleware.js","../../node_modules/@emotion/memoize/dist/emotion-memoize.esm.js","../../node_modules/@emotion/cache/dist/emotion-cache.browser.esm.js","../../node_modules/react-is/cjs/react-is.production.min.js","../../node_modules/react-is/index.js","../../node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js","../../node_modules/@emotion/utils/dist/emotion-utils.browser.esm.js","../../node_modules/@emotion/hash/dist/emotion-hash.esm.js","../../node_modules/@emotion/unitless/dist/emotion-unitless.esm.js","../../node_modules/@emotion/serialize/dist/emotion-serialize.esm.js","../../node_modules/@emotion/use-insertion-effect-with-fallbacks/dist/emotion-use-insertion-effect-with-fallbacks.browser.esm.js","../../node_modules/@emotion/react/dist/emotion-element-f0de968e.browser.esm.js","../../node_modules/@emotion/react/dist/emotion-react.browser.esm.js","../../node_modules/@emotion/is-prop-valid/dist/emotion-is-prop-valid.esm.js","../../node_modules/@emotion/styled/base/dist/emotion-styled-base.browser.esm.js","../../node_modules/@emotion/styled/dist/emotion-styled.browser.esm.js","../../node_modules/@mui/styled-engine/GlobalStyles/GlobalStyles.js","../../node_modules/@mui/styled-engine/index.js","../../node_modules/@mui/utils/node_modules/react-is/cjs/react-is.production.js","../../node_modules/@mui/utils/node_modules/react-is/index.js","../../node_modules/@mui/utils/esm/deepmerge/deepmerge.js","../../node_modules/@mui/system/esm/createBreakpoints/createBreakpoints.js","../../node_modules/@mui/system/esm/cssContainerQueries/cssContainerQueries.js","../../node_modules/@mui/system/esm/createTheme/shape.js","../../node_modules/@mui/system/esm/merge/merge.js","../../node_modules/@mui/system/esm/breakpoints/breakpoints.js","../../node_modules/@mui/utils/esm/capitalize/capitalize.js","../../node_modules/@mui/system/esm/style/style.js","../../node_modules/@mui/system/esm/memoize/memoize.js","../../node_modules/@mui/system/esm/spacing/spacing.js","../../node_modules/@mui/system/esm/createTheme/createSpacing.js","../../node_modules/@mui/system/esm/compose/compose.js","../../node_modules/@mui/system/esm/borders/borders.js","../../node_modules/@mui/system/esm/cssGrid/cssGrid.js","../../node_modules/@mui/system/esm/palette/palette.js","../../node_modules/@mui/system/esm/sizing/sizing.js","../../node_modules/@mui/system/esm/styleFunctionSx/defaultSxConfig.js","../../node_modules/@mui/system/esm/styleFunctionSx/styleFunctionSx.js","../../node_modules/@mui/system/esm/createTheme/applyStyles.js","../../node_modules/@mui/system/esm/createTheme/createTheme.js","../../node_modules/@mui/system/esm/useThemeWithoutDefault/useThemeWithoutDefault.js","../../node_modules/@mui/system/esm/useTheme/useTheme.js","../../node_modules/@mui/system/esm/GlobalStyles/GlobalStyles.js","../../node_modules/@mui/system/esm/styleFunctionSx/extendSxProp.js","../../node_modules/@mui/utils/esm/ClassNameGenerator/ClassNameGenerator.js","../../node_modules/clsx/dist/clsx.mjs","../../node_modules/@mui/system/esm/createBox/createBox.js","../../node_modules/@mui/utils/esm/generateUtilityClass/generateUtilityClass.js","../../node_modules/@mui/utils/esm/generateUtilityClasses/generateUtilityClasses.js","../../node_modules/@mui/system/esm/preprocessStyles.js","../../node_modules/@mui/system/esm/createStyled/createStyled.js","../../node_modules/@mui/system/esm/styled/styled.js","../../node_modules/@mui/utils/esm/resolveProps/resolveProps.js","../../node_modules/@mui/system/esm/useThemeProps/getThemeProps.js","../../node_modules/@mui/system/esm/useThemeProps/useThemeProps.js","../../node_modules/@mui/utils/esm/useEnhancedEffect/useEnhancedEffect.js","../../node_modules/@mui/system/esm/useMediaQuery/useMediaQuery.js","../../node_modules/@mui/utils/esm/clamp/clamp.js","../../node_modules/@mui/system/esm/colorManipulator/colorManipulator.js","../../node_modules/@mui/utils/esm/createChainedFunction/createChainedFunction.js","../../node_modules/@mui/utils/esm/debLine truncated
{"version":3,"file":"index-BECn1o8Q.js","sources":["../../node_modules/react/cjs/react.production.min.js","../../node_modules/react/index.js","../../node_modules/react/cjs/react-jsx-runtime.production.min.js","../../node_modules/react/jsx-runtime.js","../../node_modules/scheduler/cjs/scheduler.production.min.js","../../node_modules/scheduler/index.js","../../node_modules/react-dom/cjs/react-dom.production.min.js","../../node_modules/react-dom/index.js","../../node_modules/react-dom/client.js","../../node_modules/@mui/utils/esm/formatMuiErrorMessage/formatMuiErrorMessage.js","../../node_modules/@mui/material/styles/identifier.js","../../node_modules/@babel/runtime/helpers/esm/extends.js","../../node_modules/@emotion/sheet/dist/emotion-sheet.esm.js","../../node_modules/stylis/src/Enum.js","../../node_modules/stylis/src/Utility.js","../../node_modules/stylis/src/Tokenizer.js","../../node_modules/stylis/src/Parser.js","../../node_modules/stylis/src/Serializer.js","../../node_modules/stylis/src/Middleware.js","../../node_modules/@emotion/memoize/dist/emotion-memoize.esm.js","../../node_modules/@emotion/cache/dist/emotion-cache.browser.esm.js","../../node_modules/react-is/cjs/react-is.production.min.js","../../node_modules/react-is/index.js","../../node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js","../../node_modules/@emotion/utils/dist/emotion-utils.browser.esm.js","../../node_modules/@emotion/hash/dist/emotion-hash.esm.js","../../node_modules/@emotion/unitless/dist/emotion-unitless.esm.js","../../node_modules/@emotion/serialize/dist/emotion-serialize.esm.js","../../node_modules/@emotion/use-insertion-effect-with-fallbacks/dist/emotion-use-insertion-effect-with-fallbacks.browser.esm.js","../../node_modules/@emotion/react/dist/emotion-element-f0de968e.browser.esm.js","../../node_modules/@emotion/react/dist/emotion-react.browser.esm.js","../../node_modules/@emotion/is-prop-valid/dist/emotion-is-prop-valid.esm.js","../../node_modules/@emotion/styled/base/dist/emotion-styled-base.browser.esm.js","../../node_modules/@emotion/styled/dist/emotion-styled.browser.esm.js","../../node_modules/@mui/styled-engine/GlobalStyles/GlobalStyles.js","../../node_modules/@mui/styled-engine/index.js","../../node_modules/@mui/utils/node_modules/react-is/cjs/react-is.production.js","../../node_modules/@mui/utils/node_modules/react-is/index.js","../../node_modules/@mui/utils/esm/deepmerge/deepmerge.js","../../node_modules/@mui/system/esm/createBreakpoints/createBreakpoints.js","../../node_modules/@mui/system/esm/cssContainerQueries/cssContainerQueries.js","../../node_modules/@mui/system/esm/createTheme/shape.js","../../node_modules/@mui/system/esm/merge/merge.js","../../node_modules/@mui/system/esm/breakpoints/breakpoints.js","../../node_modules/@mui/utils/esm/capitalize/capitalize.js","../../node_modules/@mui/system/esm/style/style.js","../../node_modules/@mui/system/esm/memoize/memoize.js","../../node_modules/@mui/system/esm/spacing/spacing.js","../../node_modules/@mui/system/esm/createTheme/createSpacing.js","../../node_modules/@mui/system/esm/compose/compose.js","../../node_modules/@mui/system/esm/borders/borders.js","../../node_modules/@mui/system/esm/cssGrid/cssGrid.js","../../node_modules/@mui/system/esm/palette/palette.js","../../node_modules/@mui/system/esm/sizing/sizing.js","../../node_modules/@mui/system/esm/styleFunctionSx/defaultSxConfig.js","../../node_modules/@mui/system/esm/styleFunctionSx/styleFunctionSx.js","../../node_modules/@mui/system/esm/createTheme/applyStyles.js","../../node_modules/@mui/system/esm/createTheme/createTheme.js","../../node_modules/@mui/system/esm/useThemeWithoutDefault/useThemeWithoutDefault.js","../../node_modules/@mui/system/esm/useTheme/useTheme.js","../../node_modules/@mui/system/esm/GlobalStyles/GlobalStyles.js","../../node_modules/@mui/system/esm/styleFunctionSx/extendSxProp.js","../../node_modules/@mui/utils/esm/ClassNameGenerator/ClassNameGenerator.js","../../node_modules/clsx/dist/clsx.mjs","../../node_modules/@mui/system/esm/createBox/createBox.js","../../node_modules/@mui/utils/esm/generateUtilityClass/generateUtilityClass.js","../../node_modules/@mui/utils/esm/generateUtilityClasses/generateUtilityClasses.js","../../node_modules/@mui/system/esm/preprocessStyles.js","../../node_modules/@mui/system/esm/createStyled/createStyled.js","../../node_modules/@mui/system/esm/styled/styled.js","../../node_modules/@mui/utils/esm/resolveProps/resolveProps.js","../../node_modules/@mui/system/esm/useThemeProps/getThemeProps.js","../../node_modules/@mui/system/esm/useThemeProps/useThemeProps.js","../../node_modules/@mui/utils/esm/useEnhancedEffect/useEnhancedEffect.js","../../node_modules/@mui/system/esm/useMediaQuery/useMediaQuery.js","../../node_modules/@mui/utils/esm/clamp/clamp.js","../../node_modules/@mui/system/esm/colorManipulator/colorManipulator.js","../../node_modules/@mui/utils/esm/createChainedFunction/createChainedFunction.js","../../node_modules/@mui/utils/esm/debLine truncated
@@ -10,7 +10,7 @@
<link rel="icon" type="image/png" sizes="512x512" href="/android-chrome-512x512.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Nomad Karaoke: Lyrics Review</title>
<script type="module" crossorigin src="/assets/index-COYImAcx.js"></script>
<script type="module" crossorigin src="/assets/index-BECn1o8Q.js"></script>
</head>
<body>
<div id="root"></div>
@@ -2,12 +2,92 @@ from dataclasses import dataclass
import requests
import time
import os
from typing import Dict, Optional, Any, Union
import tempfile
from typing import Dict, Optional, Any, Union, Tuple
from pathlib import Path
from pydub import AudioSegment
from lyrics_transcriber.types import TranscriptionData, LyricsSegment, Word
from lyrics_transcriber.transcribers.base_transcriber import BaseTranscriber, TranscriptionError
from lyrics_transcriber.utils.word_utils import WordUtils
# Lossy formats that should be uploaded directly (transcoding would cause quality loss)
LOSSY_FORMATS = {'.mp3', '.aac', '.ogg', '.m4a', '.wma', '.opus'}
# Lossless formats that are already compressed and can be uploaded directly
LOSSLESS_COMPRESSED_FORMATS = {'.flac', '.alac'}
# Uncompressed formats that should be converted to FLAC for efficient upload
UNCOMPRESSED_FORMATS = {'.wav', '.aiff', '.aif', '.pcm'}
class AudioUploadOptimizer:
"""Optimizes audio files for upload by converting uncompressed formats to FLAC."""
def __init__(self, logger):
self.logger = logger
def prepare_for_upload(self, filepath: str) -> Tuple[str, Optional[str]]:
"""
Prepare audio file for optimal upload.
Returns:
Tuple of (filepath_to_upload, temp_file_to_cleanup)
- If no conversion needed, returns (original_filepath, None)
- If converted, returns (temp_flac_filepath, temp_flac_filepath)
"""
ext = os.path.splitext(filepath)[1].lower()
# Lossy formats: upload directly (transcoding would lose quality)
if ext in LOSSY_FORMATS:
self.logger.info(f"Uploading lossy format ({ext}) directly to preserve quality")
return filepath, None
# Already compressed lossless: upload directly
if ext in LOSSLESS_COMPRESSED_FORMATS:
self.logger.info(f"Uploading lossless compressed format ({ext}) directly")
return filepath, None
# Uncompressed formats: convert to FLAC for smaller upload
if ext in UNCOMPRESSED_FORMATS:
self.logger.info(f"Converting uncompressed format ({ext}) to FLAC for efficient upload")
return self._convert_to_flac(filepath)
# Unknown format: try to upload directly
self.logger.warning(f"Unknown audio format ({ext}), uploading directly")
return filepath, None
def _convert_to_flac(self, filepath: str) -> Tuple[str, str]:
"""Convert audio file to FLAC format."""
ext = os.path.splitext(filepath)[1].lower()
# Load audio based on format
if ext == '.wav':
audio = AudioSegment.from_wav(filepath)
elif ext in {'.aiff', '.aif'}:
audio = AudioSegment.from_file(filepath, format='aiff')
else:
audio = AudioSegment.from_file(filepath)
# Create temp file for FLAC output
with tempfile.NamedTemporaryFile(suffix=".flac", delete=False) as temp_flac:
flac_path = temp_flac.name
audio.export(flac_path, format="flac")
# Log size reduction
original_size = os.path.getsize(filepath)
flac_size = os.path.getsize(flac_path)
reduction_pct = (1 - flac_size / original_size) * 100
self.logger.info(f"Converted to FLAC: {original_size / 1024 / 1024:.1f}MB → {flac_size / 1024 / 1024:.1f}MB ({reduction_pct:.0f}% smaller)")
return flac_path, flac_path
def cleanup(self, temp_filepath: Optional[str]) -> None:
"""Clean up temporary file if it exists."""
if temp_filepath and os.path.exists(temp_filepath):
try:
os.unlink(temp_filepath)
self.logger.debug(f"Cleaned up temporary file: {temp_filepath}")
except OSError as e:
self.logger.warning(f"Failed to clean up temporary file {temp_filepath}: {e}")
@dataclass
class AudioShakeConfig:
@@ -162,11 +242,13 @@ class AudioShakeTranscriber(BaseTranscriber):
config: Optional[AudioShakeConfig] = None,
logger: Optional[Any] = None,
api_client: Optional[AudioShakeAPI] = None,
upload_optimizer: Optional[AudioUploadOptimizer] = None,
):
"""Initialize AudioShake transcriber."""
super().__init__(cache_dir=cache_dir, logger=logger)
self.config = config or AudioShakeConfig(api_token=os.getenv("AUDIOSHAKE_API_TOKEN"))
self.api = api_client or AudioShakeAPI(self.config, self.logger)
self.upload_optimizer = upload_optimizer or AudioUploadOptimizer(self.logger)
def get_name(self) -> str:
return "AudioShake"
@@ -195,14 +277,21 @@ class AudioShakeTranscriber(BaseTranscriber):
"""Starts the transcription task and returns the task ID."""
self.logger.debug(f"Entering start_transcription() for {audio_filepath}")
# Upload file and create task
file_url = self.api.upload_file(audio_filepath)
self.logger.debug(f"File uploaded successfully. File URL: {file_url}")
# Optimize file format for upload (convert WAV to FLAC, etc.)
upload_filepath, temp_filepath = self.upload_optimizer.prepare_for_upload(audio_filepath)
try:
# Upload file and create task
file_url = self.api.upload_file(upload_filepath)
self.logger.debug(f"File uploaded successfully. File URL: {file_url}")
task_id = self.api.create_task(file_url)
self.logger.debug(f"Task created successfully. Task ID: {task_id}")
task_id = self.api.create_task(file_url)
self.logger.debug(f"Task created successfully. Task ID: {task_id}")
return task_id
return task_id
finally:
# Clean up any temporary file created during optimization
self.upload_optimizer.cleanup(temp_filepath)
def get_transcription_result(self, task_id: str) -> Dict[str, Any]:
"""Gets the raw results for a previously started task."""
@@ -363,8 +363,19 @@ class AnchorSequence:
def from_dict(cls, data: Dict[str, Any]) -> "AnchorSequence":
"""Create AnchorSequence from dictionary."""
# Handle both old and new dictionary formats
if "words" in data:
# Old format - convert to new format without setting _words
# Check for new format keys FIRST (they take priority even if old keys also present)
if "transcribed_word_ids" in data:
# New format - use existing IDs
return cls(
id=data.get("id", WordUtils.generate_id()),
transcribed_word_ids=data["transcribed_word_ids"],
transcription_position=data["transcription_position"],
reference_positions=data["reference_positions"],
reference_word_ids=data["reference_word_ids"],
confidence=data["confidence"],
)
elif "words" in data:
# Old format only - convert to new format by generating IDs
# This ensures to_dict() always returns the new format
words = data["words"]
return cls(
@@ -375,18 +386,9 @@ class AnchorSequence:
reference_word_ids={source: [WordUtils.generate_id() for _ in words]
for source in data["reference_positions"].keys()},
confidence=data["confidence"],
# Don't set _words - this ensures we always use the new format
)
else:
# New format
return cls(
id=data.get("id", WordUtils.generate_id()),
transcribed_word_ids=data["transcribed_word_ids"],
transcription_position=data["transcription_position"],
reference_positions=data["reference_positions"],
reference_word_ids=data["reference_word_ids"],
confidence=data["confidence"],
)
raise ValueError("AnchorSequence.from_dict requires either 'transcribed_word_ids' or 'words' key")
@dataclass
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "lyrics-transcriber"
version = "0.82.0"
version = "0.83.0"
description = "Automatically create synchronised lyrics files in ASS and MidiCo LRC formats with word-level timestamps, using Whisper and lyrics from Genius and Spotify"
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"
@@ -67,6 +67,56 @@ def test_anchor_sequence_properties():
assert len(result["reference_word_ids"]["source1"]) == 2
def test_anchor_sequence_from_dict_preserves_ids_with_both_formats():
"""Test that from_dict prioritizes new format keys when both old and new are present.
This is a regression test for a bug where cached anchors with both 'words' (old format)
and 'transcribed_word_ids' (new format) would incorrectly regenerate word IDs.
The fix ensures that 'transcribed_word_ids' takes priority when present.
"""
# Dict with BOTH old format (words) and new format (transcribed_word_ids)
# This is what the cache file looks like after to_dict() is called
data = {
"id": "test123",
"transcribed_word_ids": ["original_id1", "original_id2", "original_id3"],
"transcription_position": 0,
"reference_positions": {"file": 0},
"reference_word_ids": {"file": ["ref_id1", "ref_id2", "ref_id3"]},
"confidence": 1.0,
"words": ["word1", "word2", "word3"], # Old format key also present
"text": "word1 word2 word3",
"length": 3,
}
anchor = AnchorSequence.from_dict(data)
# The fix should preserve the explicit IDs from transcribed_word_ids
assert anchor.transcribed_word_ids == ["original_id1", "original_id2", "original_id3"], \
"transcribed_word_ids should be preserved when both old and new format keys present"
assert anchor.reference_word_ids == {"file": ["ref_id1", "ref_id2", "ref_id3"]}, \
"reference_word_ids should be preserved when both old and new format keys present"
assert anchor.id == "test123", "id should be preserved"
def test_anchor_sequence_from_dict_old_format_only():
"""Test that from_dict generates IDs when only old format is present."""
# Dict with ONLY old format (words), no transcribed_word_ids
data = {
"transcription_position": 0,
"reference_positions": {"file": 0},
"confidence": 1.0,
"words": ["word1", "word2", "word3"],
}
anchor = AnchorSequence.from_dict(data)
# Should generate new IDs
assert len(anchor.transcribed_word_ids) == 3
assert len(anchor.reference_word_ids["file"]) == 3
# IDs should be newly generated (not the literal word text)
assert anchor.transcribed_word_ids != ["word1", "word2", "word3"]
def test_find_ngrams(finder):
words = ["a", "b", "c", "d"]
assert finder._find_ngrams(words, 2) == [(["a", "b"], 0), (["b", "c"], 1), (["c", "d"], 2)]
@@ -1,14 +1,19 @@
import pytest
import requests
from unittest.mock import Mock, patch, mock_open
from unittest.mock import Mock, patch, mock_open, MagicMock
from lyrics_transcriber.types import TranscriptionData
from lyrics_transcriber.transcribers.audioshake import (
AudioShakeConfig,
AudioShakeAPI,
AudioShakeTranscriber,
AudioUploadOptimizer,
LOSSY_FORMATS,
LOSSLESS_COMPRESSED_FORMATS,
UNCOMPRESSED_FORMATS,
)
from lyrics_transcriber.transcribers.base_transcriber import TranscriptionError
import os
import tempfile
@pytest.fixture
@@ -21,6 +26,101 @@ def config():
return AudioShakeConfig(api_token="test_token")
class TestAudioUploadOptimizer:
"""Tests for the AudioUploadOptimizer class."""
@pytest.fixture
def optimizer(self, mock_logger):
return AudioUploadOptimizer(mock_logger)
def test_prepare_for_upload_lossy_mp3(self, optimizer):
"""Test that MP3 files are uploaded directly."""
filepath, temp = optimizer.prepare_for_upload("test.mp3")
assert filepath == "test.mp3"
assert temp is None
optimizer.logger.info.assert_called_with("Uploading lossy format (.mp3) directly to preserve quality")
def test_prepare_for_upload_lossy_formats(self, optimizer):
"""Test that all lossy formats are uploaded directly."""
for ext in LOSSY_FORMATS:
filepath, temp = optimizer.prepare_for_upload(f"test{ext}")
assert filepath == f"test{ext}"
assert temp is None
def test_prepare_for_upload_flac(self, optimizer):
"""Test that FLAC files are uploaded directly."""
filepath, temp = optimizer.prepare_for_upload("test.flac")
assert filepath == "test.flac"
assert temp is None
optimizer.logger.info.assert_called_with("Uploading lossless compressed format (.flac) directly")
def test_prepare_for_upload_lossless_formats(self, optimizer):
"""Test that all lossless compressed formats are uploaded directly."""
for ext in LOSSLESS_COMPRESSED_FORMATS:
filepath, temp = optimizer.prepare_for_upload(f"test{ext}")
assert filepath == f"test{ext}"
assert temp is None
@patch("lyrics_transcriber.transcribers.audioshake.AudioSegment")
@patch("tempfile.NamedTemporaryFile")
@patch("os.path.getsize")
def test_prepare_for_upload_wav_converts_to_flac(self, mock_getsize, mock_tempfile, mock_audio_segment, optimizer):
"""Test that WAV files are converted to FLAC."""
# Setup mocks
mock_audio = MagicMock()
mock_audio_segment.from_wav.return_value = mock_audio
mock_temp = MagicMock()
mock_temp.__enter__ = MagicMock(return_value=mock_temp)
mock_temp.__exit__ = MagicMock(return_value=False)
mock_temp.name = "/tmp/temp123.flac"
mock_tempfile.return_value = mock_temp
mock_getsize.side_effect = [100_000_000, 50_000_000] # Original 100MB, FLAC 50MB
filepath, temp = optimizer.prepare_for_upload("test.wav")
assert filepath == "/tmp/temp123.flac"
assert temp == "/tmp/temp123.flac"
mock_audio_segment.from_wav.assert_called_once_with("test.wav")
mock_audio.export.assert_called_once_with("/tmp/temp123.flac", format="flac")
optimizer.logger.info.assert_any_call("Converting uncompressed format (.wav) to FLAC for efficient upload")
def test_prepare_for_upload_unknown_format(self, optimizer):
"""Test that unknown formats are uploaded directly with a warning."""
filepath, temp = optimizer.prepare_for_upload("test.xyz")
assert filepath == "test.xyz"
assert temp is None
optimizer.logger.warning.assert_called_with("Unknown audio format (.xyz), uploading directly")
@patch("os.path.exists")
@patch("os.unlink")
def test_cleanup_removes_temp_file(self, mock_unlink, mock_exists, optimizer):
"""Test that cleanup removes temporary files."""
mock_exists.return_value = True
optimizer.cleanup("/tmp/temp123.flac")
mock_unlink.assert_called_once_with("/tmp/temp123.flac")
def test_cleanup_does_nothing_for_none(self, optimizer):
"""Test that cleanup does nothing when filepath is None."""
optimizer.cleanup(None)
# Should not raise an exception
@patch("os.path.exists")
def test_cleanup_does_nothing_for_nonexistent_file(self, mock_exists, optimizer):
"""Test that cleanup does nothing when file doesn't exist."""
mock_exists.return_value = False
optimizer.cleanup("/tmp/nonexistent.flac")
# Should not raise an exception
@patch("os.path.exists")
@patch("os.unlink")
def test_cleanup_handles_os_error(self, mock_unlink, mock_exists, optimizer):
"""Test that cleanup handles OS errors gracefully."""
mock_exists.return_value = True
mock_unlink.side_effect = OSError("Permission denied")
optimizer.cleanup("/tmp/temp123.flac")
optimizer.logger.warning.assert_called()
class TestAudioShakeConfig:
def test_default_config(self):
config = AudioShakeConfig()
@@ -208,9 +308,22 @@ class TestAudioShakeTranscriber:
return Mock()
@pytest.fixture
def transcriber(self, mock_logger, mock_api, tmp_path):
def mock_optimizer(self):
optimizer = Mock(spec=AudioUploadOptimizer)
# By default, return the original file path with no temp file
optimizer.prepare_for_upload.return_value = ("test.mp3", None)
return optimizer
@pytest.fixture
def transcriber(self, mock_logger, mock_api, mock_optimizer, tmp_path):
config = AudioShakeConfig(api_token="test_token")
return AudioShakeTranscriber(config=config, logger=mock_logger, api_client=mock_api, cache_dir=tmp_path)
return AudioShakeTranscriber(
config=config,
logger=mock_logger,
api_client=mock_api,
upload_optimizer=mock_optimizer,
cache_dir=tmp_path
)
def test_init_with_token(self, transcriber):
assert transcriber.config.api_token == "test_token"
@@ -232,15 +345,42 @@ class TestAudioShakeTranscriber:
def test_get_name(self, transcriber):
assert transcriber.get_name() == "AudioShake"
def test_start_transcription(self, transcriber, mock_api):
def test_start_transcription(self, transcriber, mock_api, mock_optimizer):
mock_optimizer.prepare_for_upload.return_value = ("test.mp3", None)
mock_api.upload_file.return_value = "https://example.com/file.mp3"
mock_api.create_task.return_value = "task123"
task_id = transcriber.start_transcription("test.mp3")
assert task_id == "task123"
mock_optimizer.prepare_for_upload.assert_called_once_with("test.mp3")
mock_api.upload_file.assert_called_once_with("test.mp3")
mock_api.create_task.assert_called_once_with("https://example.com/file.mp3")
mock_optimizer.cleanup.assert_called_once_with(None)
def test_start_transcription_with_wav_conversion(self, transcriber, mock_api, mock_optimizer):
"""Test that WAV files are converted before upload and temp file is cleaned up."""
mock_optimizer.prepare_for_upload.return_value = ("/tmp/converted.flac", "/tmp/converted.flac")
mock_api.upload_file.return_value = "https://example.com/file.flac"
mock_api.create_task.return_value = "task123"
task_id = transcriber.start_transcription("test.wav")
assert task_id == "task123"
mock_optimizer.prepare_for_upload.assert_called_once_with("test.wav")
mock_api.upload_file.assert_called_once_with("/tmp/converted.flac")
mock_optimizer.cleanup.assert_called_once_with("/tmp/converted.flac")
def test_start_transcription_cleanup_on_error(self, transcriber, mock_api, mock_optimizer):
"""Test that temp files are cleaned up even when upload fails."""
mock_optimizer.prepare_for_upload.return_value = ("/tmp/converted.flac", "/tmp/converted.flac")
mock_api.upload_file.side_effect = Exception("Upload failed")
with pytest.raises(Exception, match="Upload failed"):
transcriber.start_transcription("test.wav")
# Cleanup should still be called
mock_optimizer.cleanup.assert_called_once_with("/tmp/converted.flac")
def test_get_transcription_result(self, transcriber, mock_api):
mock_task_data = {
@@ -289,7 +429,7 @@ class TestAudioShakeTranscriber:
assert result.metadata["language"] == "en"
assert result.metadata["task_id"] == "task123"
def test_transcribe_full_flow(self, transcriber, mock_api, tmp_path):
def test_transcribe_full_flow(self, transcriber, mock_api, mock_optimizer, tmp_path):
# Clear the cache directory first
cache_dir = transcriber.cache_dir
if os.path.exists(cache_dir):
@@ -300,6 +440,9 @@ class TestAudioShakeTranscriber:
test_file = tmp_path / "test.mp3"
test_file.write_text("test content")
# Set up mock optimizer to return the original file
mock_optimizer.prepare_for_upload.return_value = (str(test_file), None)
# Set up mock API responses
mock_api.upload_file.return_value = "https://example.com/file.mp3"
mock_api.create_task.return_value = "task123"
@@ -328,6 +471,7 @@ class TestAudioShakeTranscriber:
assert len(result.segments) == 1
assert result.segments[0].text == "test"
assert result.source == "AudioShake"
mock_optimizer.prepare_for_upload.assert_called_once_with(str(test_file))
mock_api.upload_file.assert_called_once_with(str(test_file))
def test_get_output_filename(self, transcriber):
@@ -368,7 +512,7 @@ class TestAudioShakeTranscriber:
assert result.metadata["language"] == "en"
assert result.metadata["task_id"] == "task123"
def test_transcribe_with_cache(self, transcriber, mock_api, tmp_path):
def test_transcribe_with_cache(self, transcriber, mock_api, mock_optimizer, tmp_path):
# Clear the cache directory first
cache_dir = transcriber.cache_dir
if os.path.exists(cache_dir):
@@ -379,6 +523,9 @@ class TestAudioShakeTranscriber:
test_file = tmp_path / "test.mp3"
test_file.write_text("test content")
# Set up mock optimizer to return the original file
mock_optimizer.prepare_for_upload.return_value = (str(test_file), None)
# Set up mock API responses
mock_api.upload_file.return_value = "https://example.com/file.mp3"
mock_api.create_task.return_value = "task123"
@@ -408,7 +555,8 @@ class TestAudioShakeTranscriber:
result2 = transcriber.transcribe(str(test_file))
assert isinstance(result2, TranscriptionData)
# Verify API was only called once
# Verify API was only called once (second call uses cache)
mock_optimizer.prepare_for_upload.assert_called_once_with(str(test_file))
mock_api.upload_file.assert_called_once_with(str(test_file))
@pytest.fixture(autouse=True)
@@ -420,8 +568,9 @@ class TestAudioShakeTranscriber:
os.remove(os.path.join(cache_dir, file))
yield
def test_perform_transcription_error(self, transcriber, mock_api):
def test_perform_transcription_error(self, transcriber, mock_api, mock_optimizer):
"""Test _perform_transcription with API error"""
mock_optimizer.prepare_for_upload.return_value = ("test.mp3", None)
mock_api.upload_file.side_effect = Exception("API Error")
with pytest.raises(Exception, match="API Error"):
@@ -471,8 +620,9 @@ class TestAudioShakeTranscriber:
assert result.metadata["task_id"] == "task123"
assert result.metadata["duration"] is None
def test_perform_transcription_debug_logging(self, transcriber, mock_api, caplog):
def test_perform_transcription_debug_logging(self, transcriber, mock_api, mock_optimizer, caplog):
"""Test debug logging in _perform_transcription"""
mock_optimizer.prepare_for_upload.return_value = ("test.mp3", None)
mock_api.upload_file.return_value = "https://example.com/file.mp3"
mock_api.create_task.return_value = "task123"
mock_api.wait_for_task_result.return_value = {
Generated
+10 -10
View File
@@ -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
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.75.8"
version = "0.75.26"
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"
+11
View File
@@ -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:
+78 -56
View File
@@ -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,
)
+82
View File
@@ -703,6 +703,88 @@ async def test_style_override_parsing(mock_run_review, mock_kprep_class, mock_ba
assert prep_kwargs["style_overrides"] == expected_overrides
# --- Test review_ui_url environment variable handling ---
@patch("karaoke_gen.utils.gen_cli.run_instrumental_review", return_value="clean")
@patch("karaoke_gen.utils.gen_cli.is_url", return_value=False)
@patch("karaoke_gen.utils.gen_cli.is_file", return_value=False)
@patch("karaoke_gen.utils.gen_cli.KaraokePrep")
async def test_review_ui_url_default_hosted_not_set_env_var(mock_kprep_class, mock_isfile, mock_isurl, mock_run_review, mock_base_args):
"""Test that default hosted review UI URL does NOT set LYRICS_REVIEW_UI_URL env var.
This allows the ReviewServer to use its bundled local frontend by default.
"""
mock_base_args.args = ["Artist", "Title"]
# Simulate the default hosted URL from cli_args
mock_base_args.review_ui_url = "https://gen.nomadkaraoke.com/lyrics"
mock_kprep_instance = MagicMock()
mock_kprep_class.return_value = mock_kprep_instance
mock_kprep_instance.process = AsyncMock(return_value=[MOCK_PREP_TRACK])
# Clear the env var first
env_backup = os.environ.get('LYRICS_REVIEW_UI_URL')
if 'LYRICS_REVIEW_UI_URL' in os.environ:
del os.environ['LYRICS_REVIEW_UI_URL']
try:
with patch("karaoke_gen.utils.gen_cli.argparse.ArgumentParser") as mock_parser, \
patch("karaoke_gen.utils.gen_cli.os.chdir"), \
patch("karaoke_gen.utils.gen_cli.os.path.exists", return_value=True), \
patch("karaoke_gen.utils.gen_cli.KaraokeFinalise"):
mock_parser.return_value.parse_args.return_value = mock_base_args
await gen_cli.async_main()
# Verify the env var was NOT set (so ReviewServer uses local frontend)
assert 'LYRICS_REVIEW_UI_URL' not in os.environ or os.environ.get('LYRICS_REVIEW_UI_URL') != mock_base_args.review_ui_url
finally:
# Restore env var
if env_backup:
os.environ['LYRICS_REVIEW_UI_URL'] = env_backup
elif 'LYRICS_REVIEW_UI_URL' in os.environ:
del os.environ['LYRICS_REVIEW_UI_URL']
@patch("karaoke_gen.utils.gen_cli.run_instrumental_review", return_value="clean")
@patch("karaoke_gen.utils.gen_cli.is_url", return_value=False)
@patch("karaoke_gen.utils.gen_cli.is_file", return_value=False)
@patch("karaoke_gen.utils.gen_cli.KaraokePrep")
async def test_review_ui_url_custom_dev_server_sets_env_var(mock_kprep_class, mock_isfile, mock_isurl, mock_run_review, mock_base_args):
"""Test that custom dev server URL (e.g., localhost:5173) DOES set LYRICS_REVIEW_UI_URL env var.
This allows using a Vite dev server for local frontend development.
"""
mock_base_args.args = ["Artist", "Title"]
# Simulate a custom dev server URL
mock_base_args.review_ui_url = "http://localhost:5173"
mock_kprep_instance = MagicMock()
mock_kprep_class.return_value = mock_kprep_instance
mock_kprep_instance.process = AsyncMock(return_value=[MOCK_PREP_TRACK])
# Clear the env var first
env_backup = os.environ.get('LYRICS_REVIEW_UI_URL')
if 'LYRICS_REVIEW_UI_URL' in os.environ:
del os.environ['LYRICS_REVIEW_UI_URL']
try:
with patch("karaoke_gen.utils.gen_cli.argparse.ArgumentParser") as mock_parser, \
patch("karaoke_gen.utils.gen_cli.os.chdir"), \
patch("karaoke_gen.utils.gen_cli.os.path.exists", return_value=True), \
patch("karaoke_gen.utils.gen_cli.KaraokeFinalise"):
mock_parser.return_value.parse_args.return_value = mock_base_args
await gen_cli.async_main()
# Verify the env var WAS set to the custom URL
assert os.environ.get('LYRICS_REVIEW_UI_URL') == "http://localhost:5173"
finally:
# Restore env var
if env_backup:
os.environ['LYRICS_REVIEW_UI_URL'] = env_backup
elif 'LYRICS_REVIEW_UI_URL' in os.environ:
del os.environ['LYRICS_REVIEW_UI_URL']
# --- Test _resolve_path_for_cwd helper function ---
class TestResolvePathForCwd:
@@ -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")
+7 -7
View File
@@ -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."""