mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-21 05:18:08 +09:00
Compare commits
16
Commits
No files matched your search
@@ -0,0 +1,123 @@
|
||||
# Agent Instructions: Nomad Karaoke E2E Production Testing
|
||||
|
||||
## Context
|
||||
|
||||
You are acting on behalf of Andrew, the creator of Nomad Karaoke, who is building a fully functional end-to-end karaoke video generation platform. The platform has two modes:
|
||||
|
||||
1. **Local CLI** (`karaoke-gen`) - For power users running locally
|
||||
2. **Public Web Service** (`gen.nomadkaraoke.com`) - For paying customers ($5/track via Stripe)
|
||||
|
||||
## Current State
|
||||
|
||||
The platform has been under heavy development with many features implemented, but **end-to-end functionality for real users on gen.nomadkaraoke.com is not fully working yet**. The goal is to make the complete user journey functional in production.
|
||||
|
||||
## Business Model (Planned)
|
||||
|
||||
- **buy.nomadkaraoke.com** - Customer intro/landing page with Stripe payment flow
|
||||
- Payment generates a single-use token
|
||||
- Customer is redirected to **gen.nomadkaraoke.com** with token ready to use
|
||||
- Each track costs $5
|
||||
|
||||
## Your Primary Mission
|
||||
|
||||
**Test and fix the production system until end-to-end karaoke generation works reliably.**
|
||||
|
||||
### The Complete User Journey to Test
|
||||
|
||||
1. **Input** - User enters artist name and song title
|
||||
2. **Audio Selection** - User selects audio source
|
||||
3. **Download & Preparation** - System downloads and prepares audio (wait for completion)
|
||||
4. **Lyrics Review** - User reviews/corrects lyrics in the web UI
|
||||
5. **Preview Video** - Wait for preview video to load
|
||||
6. **Submit Review** - User submits corrected lyrics
|
||||
7. **Render Stage** - Wait for render to complete
|
||||
8. **Instrumental Selection** - User selects instrumental via web UI
|
||||
9. **Final Render & Distribution** - Wait for final render and distribution
|
||||
10. **Verification** - Click to view uploaded YouTube video
|
||||
11. **Verification** - Click Dropbox folder link to view shared folder
|
||||
|
||||
## Your Working Process
|
||||
|
||||
Use Playwright to automate and test this journey against **live production** at `gen.nomadkaraoke.com`.
|
||||
|
||||
### The Fix Loop
|
||||
|
||||
When you encounter something broken:
|
||||
|
||||
1. **Investigate** - Understand the root cause
|
||||
2. **Fix** - Implement the fix
|
||||
3. **Improve Tests** - Add/update tests to cover the issue
|
||||
4. **Refactor** - Clean up if necessary
|
||||
5. **PR** - Create a pull request with clear description
|
||||
6. **CI** - Ensure all checks pass
|
||||
7. **Merge** - Merge the PR
|
||||
8. **Deploy** - Wait for deployment to complete
|
||||
9. **Retest** - Test again in production
|
||||
10. **Repeat** - Continue until everything works
|
||||
|
||||
## Key Rules
|
||||
|
||||
### From CLAUDE.md (Must Follow)
|
||||
|
||||
- **Never commit directly to `main`** - Always use feature branches
|
||||
- **Always run tests before committing** - `make test` for backend, `cd frontend && npm run test:all` for frontend
|
||||
- **Bump version** in `pyproject.toml` for every commit
|
||||
- **Use git worktrees** for non-trivial changes
|
||||
- **Infrastructure changes** must go through Pulumi IaC
|
||||
|
||||
### Testing Commands
|
||||
|
||||
```bash
|
||||
# Backend tests (10 min timeout, limit output)
|
||||
make test 2>&1 | tail -n 500
|
||||
|
||||
# Frontend tests
|
||||
cd frontend && npm run test:all 2>&1 | tail -n 200
|
||||
```
|
||||
|
||||
### Pre-commit Checklist
|
||||
|
||||
- [ ] Tests pass
|
||||
- [ ] Version bumped in `pyproject.toml`
|
||||
- [ ] PR created with clear description
|
||||
- [ ] CI checks pass before merge
|
||||
|
||||
## Permissions
|
||||
|
||||
You have permission to:
|
||||
|
||||
- Run any command necessary
|
||||
- Use Playwright to interact with browsers
|
||||
- Make changes to any part of the codebase
|
||||
- Create PRs and merge them (after CI passes)
|
||||
- Test against live production
|
||||
|
||||
## Success Criteria
|
||||
|
||||
The mission is complete when:
|
||||
|
||||
1. Any artist/title can be entered on gen.nomadkaraoke.com
|
||||
2. The full generation process completes successfully
|
||||
3. A karaoke video is uploaded to YouTube
|
||||
4. Files are distributed to Dropbox
|
||||
5. The entire flow is covered by automated E2E tests
|
||||
|
||||
## Key URLs
|
||||
|
||||
- **Production Frontend**: https://gen.nomadkaraoke.com
|
||||
- **Production API**: https://api.nomadkaraoke.com (inferred from README)
|
||||
- **Lyrics Review UI**: https://gen.nomadkaraoke.com/lyrics/
|
||||
|
||||
## Reference Documentation
|
||||
|
||||
- `/Users/andrew/Projects/karaoke-gen/README.md` - Main project documentation
|
||||
- `/Users/andrew/Projects/karaoke-gen/CLAUDE.md` - AI assistant guidelines
|
||||
- `/Users/andrew/Projects/karaoke-gen/docs/01-reference/` - Reference documentation
|
||||
- `/Users/andrew/Projects/karaoke-gen/docs/00-current-plan/` - Planning documents (may be outdated)
|
||||
|
||||
## Notes
|
||||
|
||||
- Some docs in `docs/00-current-plan/` may be outdated - review, evaluate, and move/delete as appropriate
|
||||
- Focus on making things work, not perfect
|
||||
- Ship iteratively - fix one thing at a time
|
||||
- Document issues you find as you go
|
||||
@@ -2,6 +2,14 @@
|
||||
|
||||
This document contains guidelines and rules for AI assistants working on this codebase.
|
||||
|
||||
## Core Principles
|
||||
|
||||
**Always be testing.** Proactively evaluate, read, run, fix, and improve tests whenever you touch any part of the system—frontend, backend, infrastructure. Every code change should be thoroughly tested. Leave everything better tested than you found it.
|
||||
|
||||
**Always be documenting.** Continuously read, write, improve, update, and organize markdown documentation. Reference existing docs and keep them accurate as the codebase evolves.
|
||||
|
||||
**Build for maintainability.** Keep code SOLID, modular, and clean. Favor simplicity and clarity. Future developers (and AI agents) will thank you.
|
||||
|
||||
## Branching Workflow
|
||||
|
||||
**Never commit directly to `main`.** Always work on a feature branch.
|
||||
|
||||
@@ -81,13 +81,13 @@ class AudioSearchRequest(BaseModel):
|
||||
"""Request to search for audio by artist and title."""
|
||||
artist: str = Field(..., description="Artist name to search for")
|
||||
title: str = Field(..., description="Song title to search for")
|
||||
|
||||
|
||||
# Auto-download mode
|
||||
auto_download: bool = Field(False, description="Automatically select best result and download")
|
||||
|
||||
# Processing options
|
||||
enable_cdg: bool = Field(True, description="Generate CDG+MP3 package")
|
||||
enable_txt: bool = Field(True, description="Generate TXT+MP3 package")
|
||||
|
||||
# Processing options (CDG/TXT require style config, disabled by default)
|
||||
enable_cdg: bool = Field(False, description="Generate CDG+MP3 package (requires style config)")
|
||||
enable_txt: bool = Field(False, description="Generate TXT+MP3 package (requires style config)")
|
||||
|
||||
# Finalisation options
|
||||
brand_prefix: Optional[str] = Field(None, description="Brand code prefix (e.g., NOMAD)")
|
||||
@@ -424,12 +424,17 @@ async def search_audio(
|
||||
effective_dropbox_path = body.dropbox_path or settings.default_dropbox_path
|
||||
effective_gdrive_folder_id = body.gdrive_folder_id or settings.default_gdrive_folder_id
|
||||
effective_discord_webhook_url = body.discord_webhook_url or settings.default_discord_webhook_url
|
||||
|
||||
|
||||
# Apply defaults for YouTube/Dropbox distribution (for web service)
|
||||
effective_enable_youtube_upload = body.enable_youtube_upload or settings.default_enable_youtube_upload
|
||||
effective_brand_prefix = body.brand_prefix or settings.default_brand_prefix
|
||||
effective_youtube_description = body.youtube_description or settings.default_youtube_description
|
||||
|
||||
# Validate credentials if distribution services are requested
|
||||
invalid_services = []
|
||||
credential_manager = get_credential_manager()
|
||||
|
||||
if body.enable_youtube_upload:
|
||||
|
||||
if effective_enable_youtube_upload:
|
||||
result = credential_manager.check_youtube_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"youtube ({result.message})")
|
||||
@@ -463,10 +468,10 @@ async def search_audio(
|
||||
title=body.title,
|
||||
enable_cdg=body.enable_cdg,
|
||||
enable_txt=body.enable_txt,
|
||||
brand_prefix=body.brand_prefix,
|
||||
enable_youtube_upload=body.enable_youtube_upload,
|
||||
youtube_description=body.youtube_description,
|
||||
youtube_description_template=body.youtube_description, # video_worker reads this field
|
||||
brand_prefix=effective_brand_prefix,
|
||||
enable_youtube_upload=effective_enable_youtube_upload,
|
||||
youtube_description=effective_youtube_description,
|
||||
youtube_description_template=effective_youtube_description, # video_worker reads this field
|
||||
discord_webhook_url=effective_discord_webhook_url,
|
||||
dropbox_path=effective_dropbox_path,
|
||||
gdrive_folder_id=effective_gdrive_folder_id,
|
||||
|
||||
@@ -22,10 +22,12 @@ from typing import Optional, List, Dict, Any, Tuple
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from backend.models.job import JobCreate, JobStatus
|
||||
from backend.models.theme import ColorOverrides
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.worker_service import get_worker_service
|
||||
from backend.services.credential_manager import get_credential_manager, CredentialStatus
|
||||
from backend.services.theme_service import get_theme_service
|
||||
from backend.config import get_settings
|
||||
from backend.version import VERSION
|
||||
from backend.services.metrics import metrics
|
||||
@@ -51,15 +53,19 @@ class CreateJobFromUrlRequest(BaseModel):
|
||||
"""Request to create a job from a YouTube/online URL."""
|
||||
# Required fields
|
||||
url: str = Field(..., description="YouTube or other video URL to download audio from")
|
||||
|
||||
|
||||
# Optional fields - will be auto-detected from URL if not provided
|
||||
artist: Optional[str] = Field(None, description="Artist name (auto-detected from URL if not provided)")
|
||||
title: Optional[str] = Field(None, description="Song title (auto-detected from URL if not provided)")
|
||||
|
||||
# Processing options
|
||||
enable_cdg: bool = Field(True, description="Generate CDG+MP3 package")
|
||||
enable_txt: bool = Field(True, description="Generate TXT+MP3 package")
|
||||
|
||||
|
||||
# Theme configuration (use pre-made theme from GCS)
|
||||
theme_id: Optional[str] = Field(None, description="Theme ID to use (e.g., 'nomad', 'default'). If set, CDG/TXT are enabled by default.")
|
||||
color_overrides: Optional[Dict[str, str]] = Field(None, description="Color overrides: artist_color, title_color, sung_lyrics_color, unsung_lyrics_color (hex #RRGGBB)")
|
||||
|
||||
# Processing options (CDG/TXT require style config or theme, disabled by default unless theme is set)
|
||||
enable_cdg: Optional[bool] = Field(None, description="Generate CDG+MP3 package. Default: True if theme_id set, False otherwise")
|
||||
enable_txt: Optional[bool] = Field(None, description="Generate TXT+MP3 package. Default: True if theme_id set, False otherwise")
|
||||
|
||||
# Finalisation options
|
||||
brand_prefix: Optional[str] = Field(None, description="Brand code prefix (e.g., NOMAD)")
|
||||
enable_youtube_upload: bool = Field(False, description="Upload to YouTube")
|
||||
@@ -67,19 +73,19 @@ class CreateJobFromUrlRequest(BaseModel):
|
||||
discord_webhook_url: Optional[str] = Field(None, description="Discord webhook URL for notifications")
|
||||
webhook_url: Optional[str] = Field(None, description="Generic webhook URL")
|
||||
user_email: Optional[str] = Field(None, description="User email for notifications")
|
||||
|
||||
|
||||
# Distribution options (native API - preferred for remote CLI)
|
||||
dropbox_path: Optional[str] = Field(None, description="Dropbox folder path for organized output")
|
||||
gdrive_folder_id: Optional[str] = Field(None, description="Google Drive folder ID for public share uploads")
|
||||
|
||||
|
||||
# Legacy distribution options (rclone - deprecated)
|
||||
organised_dir_rclone_root: Optional[str] = Field(None, description="[Deprecated] rclone remote path")
|
||||
|
||||
|
||||
# Lyrics configuration
|
||||
lyrics_artist: Optional[str] = Field(None, description="Override artist name for lyrics search")
|
||||
lyrics_title: Optional[str] = Field(None, description="Override title for lyrics search")
|
||||
subtitle_offset_ms: int = Field(0, description="Subtitle timing offset in milliseconds")
|
||||
|
||||
|
||||
# Audio separation model configuration
|
||||
clean_instrumental_model: Optional[str] = Field(None, description="Model for clean instrumental separation")
|
||||
backing_vocals_models: Optional[List[str]] = Field(None, description="Models for backing vocals separation")
|
||||
@@ -102,10 +108,14 @@ class CreateJobWithUploadUrlsRequest(BaseModel):
|
||||
artist: str = Field(..., description="Artist name")
|
||||
title: str = Field(..., description="Song title")
|
||||
files: List[FileUploadRequest] = Field(..., description="List of files to upload")
|
||||
|
||||
# Processing options
|
||||
enable_cdg: bool = Field(True, description="Generate CDG+MP3 package")
|
||||
enable_txt: bool = Field(True, description="Generate TXT+MP3 package")
|
||||
|
||||
# Theme configuration (use pre-made theme from GCS)
|
||||
theme_id: Optional[str] = Field(None, description="Theme ID to use (e.g., 'nomad', 'default'). If set, CDG/TXT are enabled by default.")
|
||||
color_overrides: Optional[Dict[str, str]] = Field(None, description="Color overrides: artist_color, title_color, sung_lyrics_color, unsung_lyrics_color (hex #RRGGBB)")
|
||||
|
||||
# Processing options (CDG/TXT require style config or theme, disabled by default unless theme is set)
|
||||
enable_cdg: Optional[bool] = Field(None, description="Generate CDG+MP3 package. Default: True if theme_id set, False otherwise")
|
||||
enable_txt: Optional[bool] = Field(None, description="Generate TXT+MP3 package. Default: True if theme_id set, False otherwise")
|
||||
|
||||
# Finalisation options
|
||||
brand_prefix: Optional[str] = Field(None, description="Brand code prefix (e.g., NOMAD)")
|
||||
@@ -226,7 +236,7 @@ ALLOWED_FONT_EXTENSIONS = {'.ttf', '.otf', '.woff', '.woff2'}
|
||||
async def _trigger_workers_parallel(job_id: str) -> None:
|
||||
"""
|
||||
Trigger both audio and lyrics workers in parallel.
|
||||
|
||||
|
||||
FastAPI's BackgroundTasks runs async tasks sequentially, so we use
|
||||
asyncio.gather to ensure both workers start at the same time.
|
||||
"""
|
||||
@@ -236,6 +246,83 @@ async def _trigger_workers_parallel(job_id: str) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _resolve_cdg_txt_defaults(
|
||||
theme_id: Optional[str],
|
||||
enable_cdg: Optional[bool],
|
||||
enable_txt: Optional[bool]
|
||||
) -> Tuple[bool, bool]:
|
||||
"""
|
||||
Resolve CDG/TXT settings based on theme and explicit settings.
|
||||
|
||||
When a theme is selected, CDG and TXT are enabled by default.
|
||||
Explicit True/False values always override the default.
|
||||
|
||||
Args:
|
||||
theme_id: Theme identifier (if any)
|
||||
enable_cdg: Explicit CDG setting (None means use default)
|
||||
enable_txt: Explicit TXT setting (None means use default)
|
||||
|
||||
Returns:
|
||||
Tuple of (resolved_enable_cdg, resolved_enable_txt)
|
||||
"""
|
||||
# Default based on whether theme is set
|
||||
default_enabled = theme_id is not None
|
||||
|
||||
# Resolve with explicit override taking precedence
|
||||
resolved_cdg = enable_cdg if enable_cdg is not None else default_enabled
|
||||
resolved_txt = enable_txt if enable_txt is not None else default_enabled
|
||||
|
||||
return resolved_cdg, resolved_txt
|
||||
|
||||
|
||||
def _prepare_theme_for_job(
|
||||
job_id: str,
|
||||
theme_id: str,
|
||||
color_overrides: Optional[Dict[str, str]] = None
|
||||
) -> Tuple[str, Dict[str, str], Optional[str]]:
|
||||
"""
|
||||
Prepare theme style files for a job.
|
||||
|
||||
Args:
|
||||
job_id: The job ID
|
||||
theme_id: Theme identifier
|
||||
color_overrides: Optional color override dict
|
||||
|
||||
Returns:
|
||||
Tuple of (style_params_gcs_path, style_assets, youtube_description)
|
||||
|
||||
Raises:
|
||||
HTTPException: If theme not found
|
||||
"""
|
||||
theme_service = get_theme_service()
|
||||
|
||||
# Verify theme exists
|
||||
if not theme_service.theme_exists(theme_id):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Theme not found: {theme_id}. Use GET /api/themes to list available themes."
|
||||
)
|
||||
|
||||
# Convert dict to ColorOverrides model if provided
|
||||
color_overrides_model = None
|
||||
if color_overrides:
|
||||
color_overrides_model = ColorOverrides(**color_overrides)
|
||||
|
||||
# Prepare job style from theme
|
||||
style_params_path, style_assets = theme_service.prepare_job_style(
|
||||
job_id=job_id,
|
||||
theme_id=theme_id,
|
||||
color_overrides=color_overrides_model
|
||||
)
|
||||
|
||||
# Get YouTube description template if available
|
||||
youtube_desc = theme_service.get_youtube_description(theme_id)
|
||||
|
||||
logger.info(f"Prepared theme '{theme_id}' for job {job_id}")
|
||||
|
||||
return style_params_path, style_assets, youtube_desc
|
||||
|
||||
|
||||
@router.post("/jobs/upload")
|
||||
async def upload_and_create_job(
|
||||
request: Request,
|
||||
@@ -254,9 +341,9 @@ async def upload_and_create_job(
|
||||
style_cdg_instrumental_background: Optional[UploadFile] = File(None, description="CDG instrumental background"),
|
||||
style_cdg_title_background: Optional[UploadFile] = File(None, description="CDG title screen background"),
|
||||
style_cdg_outro_background: Optional[UploadFile] = File(None, description="CDG outro screen background"),
|
||||
# Processing options
|
||||
enable_cdg: bool = Form(True, description="Generate CDG+MP3 package"),
|
||||
enable_txt: bool = Form(True, description="Generate TXT+MP3 package"),
|
||||
# Processing options (CDG/TXT require style config, disabled by default)
|
||||
enable_cdg: bool = Form(False, description="Generate CDG+MP3 package (requires style config)"),
|
||||
enable_txt: bool = Form(False, description="Generate TXT+MP3 package (requires style config)"),
|
||||
# Finalisation options
|
||||
brand_prefix: Optional[str] = Form(None, description="Brand code prefix (e.g., NOMAD)"),
|
||||
enable_youtube_upload: bool = Form(False, description="Upload to YouTube"),
|
||||
@@ -681,10 +768,14 @@ class CreateFinaliseOnlyJobRequest(BaseModel):
|
||||
artist: str = Field(..., description="Artist name")
|
||||
title: str = Field(..., description="Song title")
|
||||
files: List[FinaliseOnlyFileRequest] = Field(..., description="List of prep output files to upload")
|
||||
|
||||
# Processing options
|
||||
enable_cdg: bool = Field(True, description="Generate CDG+MP3 package")
|
||||
enable_txt: bool = Field(True, description="Generate TXT+MP3 package")
|
||||
|
||||
# Theme configuration (use pre-made theme from GCS)
|
||||
theme_id: Optional[str] = Field(None, description="Theme ID to use (e.g., 'nomad', 'default'). If set, CDG/TXT are enabled by default.")
|
||||
color_overrides: Optional[Dict[str, str]] = Field(None, description="Color overrides: artist_color, title_color, sung_lyrics_color, unsung_lyrics_color (hex #RRGGBB)")
|
||||
|
||||
# Processing options (CDG/TXT require style config or theme, disabled by default unless theme is set)
|
||||
enable_cdg: Optional[bool] = Field(None, description="Generate CDG+MP3 package. Default: True if theme_id set, False otherwise")
|
||||
enable_txt: Optional[bool] = Field(None, description="Generate TXT+MP3 package. Default: True if theme_id set, False otherwise")
|
||||
|
||||
# Finalisation options
|
||||
brand_prefix: Optional[str] = Field(None, description="Brand code prefix (e.g., NOMAD)")
|
||||
@@ -859,17 +950,27 @@ async def create_job_with_upload_urls(
|
||||
|
||||
# Extract request metadata for tracking
|
||||
request_metadata = extract_request_metadata(request, created_from="signed_url_upload")
|
||||
|
||||
|
||||
# Get original audio filename
|
||||
audio_file = audio_files[0]
|
||||
|
||||
|
||||
# Resolve CDG/TXT defaults based on theme
|
||||
resolved_cdg, resolved_txt = _resolve_cdg_txt_defaults(
|
||||
body.theme_id, body.enable_cdg, body.enable_txt
|
||||
)
|
||||
|
||||
# Check if style_params is being uploaded (overrides theme)
|
||||
has_style_params_upload = any(f.file_type == 'style_params' for f in body.files)
|
||||
|
||||
# Create job
|
||||
job_create = JobCreate(
|
||||
artist=body.artist,
|
||||
title=body.title,
|
||||
filename=audio_file.filename,
|
||||
enable_cdg=body.enable_cdg,
|
||||
enable_txt=body.enable_txt,
|
||||
theme_id=body.theme_id,
|
||||
color_overrides=body.color_overrides or {},
|
||||
enable_cdg=resolved_cdg,
|
||||
enable_txt=resolved_txt,
|
||||
brand_prefix=body.brand_prefix,
|
||||
enable_youtube_upload=body.enable_youtube_upload,
|
||||
youtube_description=body.youtube_description,
|
||||
@@ -889,11 +990,26 @@ async def create_job_with_upload_urls(
|
||||
)
|
||||
job = job_manager.create_job(job_create)
|
||||
job_id = job.job_id
|
||||
|
||||
|
||||
# Record job creation metric
|
||||
metrics.record_job_created(job_id, source="upload")
|
||||
|
||||
|
||||
logger.info(f"Created job {job_id} for {body.artist} - {body.title} (signed URL upload flow)")
|
||||
|
||||
# If theme is set and no style_params uploaded, prepare theme style now
|
||||
if body.theme_id and not has_style_params_upload:
|
||||
style_params_path, style_assets, youtube_desc = _prepare_theme_for_job(
|
||||
job_id, body.theme_id, body.color_overrides
|
||||
)
|
||||
# Update job with theme style data
|
||||
update_data = {
|
||||
'style_params_gcs_path': style_params_path,
|
||||
'style_assets': style_assets,
|
||||
}
|
||||
if youtube_desc and not body.youtube_description:
|
||||
update_data['youtube_description_template'] = youtube_desc
|
||||
job_manager.update_job(job_id, update_data)
|
||||
logger.info(f"Applied theme '{body.theme_id}' to job {job_id}")
|
||||
|
||||
# Generate signed upload URLs for each file
|
||||
upload_urls = []
|
||||
@@ -1245,19 +1361,26 @@ async def create_job_from_url(
|
||||
|
||||
# Extract request metadata for tracking
|
||||
request_metadata = extract_request_metadata(request, created_from="url")
|
||||
|
||||
|
||||
# Use provided artist/title or leave as None (will be auto-detected by audio worker)
|
||||
artist = body.artist
|
||||
title = body.title
|
||||
|
||||
|
||||
# Resolve CDG/TXT defaults based on theme
|
||||
resolved_cdg, resolved_txt = _resolve_cdg_txt_defaults(
|
||||
body.theme_id, body.enable_cdg, body.enable_txt
|
||||
)
|
||||
|
||||
# Create job with URL
|
||||
job_create = JobCreate(
|
||||
url=body.url,
|
||||
artist=artist,
|
||||
title=title,
|
||||
filename=None, # No file uploaded
|
||||
enable_cdg=body.enable_cdg,
|
||||
enable_txt=body.enable_txt,
|
||||
theme_id=body.theme_id,
|
||||
color_overrides=body.color_overrides or {},
|
||||
enable_cdg=resolved_cdg,
|
||||
enable_txt=resolved_txt,
|
||||
brand_prefix=body.brand_prefix,
|
||||
enable_youtube_upload=body.enable_youtube_upload,
|
||||
youtube_description=body.youtube_description,
|
||||
@@ -1277,9 +1400,24 @@ async def create_job_from_url(
|
||||
)
|
||||
job = job_manager.create_job(job_create)
|
||||
job_id = job.job_id
|
||||
|
||||
|
||||
# Record job creation metric
|
||||
metrics.record_job_created(job_id, source="url")
|
||||
|
||||
# If theme is set, prepare theme style now
|
||||
if body.theme_id:
|
||||
style_params_path, style_assets, youtube_desc = _prepare_theme_for_job(
|
||||
job_id, body.theme_id, body.color_overrides
|
||||
)
|
||||
# Update job with theme style data
|
||||
update_data = {
|
||||
'style_params_gcs_path': style_params_path,
|
||||
'style_assets': style_assets,
|
||||
}
|
||||
if youtube_desc and not body.youtube_description:
|
||||
update_data['youtube_description_template'] = youtube_desc
|
||||
job_manager.update_job(job_id, update_data)
|
||||
logger.info(f"Applied theme '{body.theme_id}' to job {job_id}")
|
||||
|
||||
logger.info(f"Created URL-based job {job_id} for URL: {body.url}")
|
||||
if artist:
|
||||
@@ -1462,14 +1600,24 @@ async def create_finalise_only_job(
|
||||
|
||||
# Extract request metadata
|
||||
request_metadata = extract_request_metadata(request, created_from="finalise_only_upload")
|
||||
|
||||
|
||||
# Resolve CDG/TXT defaults based on theme
|
||||
resolved_cdg, resolved_txt = _resolve_cdg_txt_defaults(
|
||||
body.theme_id, body.enable_cdg, body.enable_txt
|
||||
)
|
||||
|
||||
# Check if style_params is being uploaded (overrides theme)
|
||||
has_style_params_upload = any(f.file_type == 'style_params' for f in body.files)
|
||||
|
||||
# Create job with finalise_only=True
|
||||
job_create = JobCreate(
|
||||
artist=body.artist,
|
||||
title=body.title,
|
||||
filename="finalise_only", # No single audio file - using prep outputs
|
||||
enable_cdg=body.enable_cdg,
|
||||
enable_txt=body.enable_txt,
|
||||
theme_id=body.theme_id,
|
||||
color_overrides=body.color_overrides or {},
|
||||
enable_cdg=resolved_cdg,
|
||||
enable_txt=resolved_txt,
|
||||
brand_prefix=body.brand_prefix,
|
||||
enable_youtube_upload=body.enable_youtube_upload,
|
||||
youtube_description=body.youtube_description,
|
||||
@@ -1482,11 +1630,26 @@ async def create_finalise_only_job(
|
||||
)
|
||||
job = job_manager.create_job(job_create)
|
||||
job_id = job.job_id
|
||||
|
||||
|
||||
# Record job creation metric
|
||||
metrics.record_job_created(job_id, source="finalise")
|
||||
|
||||
|
||||
logger.info(f"Created finalise-only job {job_id} for {body.artist} - {body.title}")
|
||||
|
||||
# If theme is set and no style_params uploaded, prepare theme style now
|
||||
if body.theme_id and not has_style_params_upload:
|
||||
style_params_path, style_assets, youtube_desc = _prepare_theme_for_job(
|
||||
job_id, body.theme_id, body.color_overrides
|
||||
)
|
||||
# Update job with theme style data
|
||||
update_data = {
|
||||
'style_params_gcs_path': style_params_path,
|
||||
'style_assets': style_assets,
|
||||
}
|
||||
if youtube_desc and not body.youtube_description:
|
||||
update_data['youtube_description_template'] = youtube_desc
|
||||
job_manager.update_job(job_id, update_data)
|
||||
logger.info(f"Applied theme '{body.theme_id}' to job {job_id}")
|
||||
|
||||
# Generate signed upload URLs for each file
|
||||
upload_urls = []
|
||||
|
||||
+67
-15
@@ -336,12 +336,27 @@ async def get_review_data(
|
||||
|
||||
# Get URLs from file_urls
|
||||
corrections_url = job.file_urls.get('lyrics', {}).get('corrections')
|
||||
audio_url = job.file_urls.get('lyrics', {}).get('audio')
|
||||
|
||||
if not corrections_url or not audio_url:
|
||||
|
||||
# For audio, try multiple sources in order of preference:
|
||||
# 1. Explicit lyrics audio (if worker uploaded it)
|
||||
# 2. Lead vocals stem (best for reviewing lyrics sync)
|
||||
# 3. Input media (original audio)
|
||||
audio_url = (
|
||||
job.file_urls.get('lyrics', {}).get('audio') or
|
||||
job.file_urls.get('stems', {}).get('lead_vocals') or
|
||||
job.input_media_gcs_path
|
||||
)
|
||||
|
||||
if not corrections_url:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Review data not available"
|
||||
detail="Corrections data not available"
|
||||
)
|
||||
|
||||
if not audio_url:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Audio not available for review"
|
||||
)
|
||||
|
||||
# Generate signed URLs for direct access
|
||||
@@ -1097,32 +1112,34 @@ async def retry_job(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
) -> dict:
|
||||
"""
|
||||
Retry a failed job from the last successful checkpoint.
|
||||
|
||||
This endpoint allows resuming jobs that failed during:
|
||||
Retry a failed or cancelled job from the last successful checkpoint.
|
||||
|
||||
This endpoint allows resuming jobs that failed or were cancelled during:
|
||||
- Audio processing (re-runs from beginning if input audio exists)
|
||||
- Video generation (re-runs video worker)
|
||||
- Encoding (re-runs video worker)
|
||||
- Packaging (re-runs video worker)
|
||||
|
||||
|
||||
The retry logic determines the appropriate stage to resume from
|
||||
based on what files/state already exist.
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
if job.status != JobStatus.FAILED:
|
||||
|
||||
if job.status not in [JobStatus.FAILED, JobStatus.CANCELLED]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Only failed jobs can be retried (current status: {job.status})"
|
||||
detail=f"Only failed or cancelled jobs can be retried (current status: {job.status})"
|
||||
)
|
||||
|
||||
try:
|
||||
# Determine retry point based on what's already complete
|
||||
error_details = job.error_details or {}
|
||||
error_stage = error_details.get('stage', 'unknown')
|
||||
|
||||
logger.info(f"Job {job_id}: Retrying from failed stage '{error_stage}'")
|
||||
original_status = job.status
|
||||
|
||||
logger.info(f"Job {job_id}: Retrying from {original_status} state (error stage: '{error_stage}')")
|
||||
|
||||
# Check what state exists to determine retry point
|
||||
file_urls = job.file_urls or {}
|
||||
@@ -1230,11 +1247,46 @@ async def retry_job(
|
||||
"retry_stage": "screens_generation"
|
||||
}
|
||||
|
||||
# If we have input audio (uploaded or from URL), restart from beginning
|
||||
elif job.input_media_gcs_path or job.url:
|
||||
logger.info(f"Job {job_id}: Has input audio, restarting from beginning")
|
||||
|
||||
# Clear error state and any partial progress
|
||||
job_manager.update_job(job_id, {
|
||||
'error_message': None,
|
||||
'error_details': None,
|
||||
'state_data': {}, # Clear parallel worker progress
|
||||
})
|
||||
|
||||
# Reset to DOWNLOADING and trigger audio worker
|
||||
if not job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING,
|
||||
progress=5,
|
||||
message=f"Restarting job from {original_status} state"
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to transition job status for retry"
|
||||
)
|
||||
|
||||
# Trigger audio worker (which kicks off parallel audio + lyrics processing)
|
||||
background_tasks.add_task(worker_service.trigger_audio_worker, job_id)
|
||||
background_tasks.add_task(worker_service.trigger_lyrics_worker, job_id)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"job_id": job_id,
|
||||
"job_status": "downloading",
|
||||
"message": f"Job restarted from {original_status} state",
|
||||
"retry_stage": "from_beginning"
|
||||
}
|
||||
|
||||
else:
|
||||
# Can't determine a safe retry point, need to restart from beginning
|
||||
# No input audio available - job needs to be resubmitted
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Cannot determine safe retry point. Job may need to be resubmitted."
|
||||
detail="Cannot retry: no input audio available. Job must be resubmitted."
|
||||
)
|
||||
|
||||
except HTTPException:
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
"""
|
||||
Theme API routes for listing and retrieving theme information.
|
||||
|
||||
Themes are pre-created style configurations that users can select when creating jobs.
|
||||
These endpoints are public (no authentication required) to allow theme selection
|
||||
before job creation.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from backend.models.theme import ThemeDetailResponse, ThemesListResponse
|
||||
from backend.services.theme_service import get_theme_service
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/themes", tags=["themes"])
|
||||
|
||||
|
||||
@router.get("", response_model=ThemesListResponse)
|
||||
async def list_themes() -> ThemesListResponse:
|
||||
"""
|
||||
List all available themes.
|
||||
|
||||
Returns a list of themes with their metadata and preview image URLs.
|
||||
Preview URLs are signed and valid for 60 minutes.
|
||||
|
||||
This endpoint is public and does not require authentication.
|
||||
"""
|
||||
try:
|
||||
theme_service = get_theme_service()
|
||||
themes = theme_service.list_themes()
|
||||
return ThemesListResponse(themes=themes)
|
||||
except Exception as e:
|
||||
logger.error(f"Error listing themes: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to load themes"
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{theme_id}", response_model=ThemeDetailResponse)
|
||||
async def get_theme(theme_id: str) -> ThemeDetailResponse:
|
||||
"""
|
||||
Get detailed information about a specific theme.
|
||||
|
||||
Returns the full theme details including style parameters.
|
||||
This can be used to preview theme settings or inspect configuration.
|
||||
|
||||
Args:
|
||||
theme_id: The unique identifier of the theme
|
||||
|
||||
Returns:
|
||||
ThemeDetailResponse with full theme details
|
||||
|
||||
Raises:
|
||||
404: Theme not found
|
||||
"""
|
||||
try:
|
||||
theme_service = get_theme_service()
|
||||
theme = theme_service.get_theme(theme_id)
|
||||
|
||||
if theme is None:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Theme not found: {theme_id}"
|
||||
)
|
||||
|
||||
return ThemeDetailResponse(theme=theme)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting theme {theme_id}: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to load theme"
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{theme_id}/preview")
|
||||
async def get_theme_preview(theme_id: str) -> dict:
|
||||
"""
|
||||
Get a signed URL for the theme's preview image.
|
||||
|
||||
This endpoint is useful when you need just the preview URL
|
||||
without loading the full theme details.
|
||||
|
||||
Args:
|
||||
theme_id: The unique identifier of the theme
|
||||
|
||||
Returns:
|
||||
Object with preview_url field
|
||||
|
||||
Raises:
|
||||
404: Theme not found or no preview available
|
||||
"""
|
||||
try:
|
||||
theme_service = get_theme_service()
|
||||
|
||||
if not theme_service.theme_exists(theme_id):
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Theme not found: {theme_id}"
|
||||
)
|
||||
|
||||
theme = theme_service.get_theme(theme_id)
|
||||
if theme is None or theme.preview_url is None:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"No preview available for theme: {theme_id}"
|
||||
)
|
||||
|
||||
return {"preview_url": theme.preview_url}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting preview for theme {theme_id}: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to load theme preview"
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{theme_id}/youtube-description")
|
||||
async def get_theme_youtube_description(theme_id: str) -> dict:
|
||||
"""
|
||||
Get the YouTube description template for a theme.
|
||||
|
||||
Some themes include a default YouTube video description template
|
||||
that can be used when uploading videos.
|
||||
|
||||
Args:
|
||||
theme_id: The unique identifier of the theme
|
||||
|
||||
Returns:
|
||||
Object with description field containing the template text,
|
||||
or null if no template is available
|
||||
|
||||
Raises:
|
||||
404: Theme not found
|
||||
"""
|
||||
try:
|
||||
theme_service = get_theme_service()
|
||||
|
||||
if not theme_service.theme_exists(theme_id):
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Theme not found: {theme_id}"
|
||||
)
|
||||
|
||||
description = theme_service.get_youtube_description(theme_id)
|
||||
return {"description": description}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting YouTube description for theme {theme_id}: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to load YouTube description"
|
||||
)
|
||||
@@ -69,6 +69,16 @@ class Settings(BaseSettings):
|
||||
default_discord_webhook_url: Optional[str] = (
|
||||
os.getenv("DEFAULT_DISCORD_WEBHOOK_URL", "").strip() or None
|
||||
)
|
||||
|
||||
# Default values for web service jobs (YouTube/Dropbox distribution)
|
||||
default_enable_youtube_upload: bool = os.getenv("DEFAULT_ENABLE_YOUTUBE_UPLOAD", "false").lower() in ("true", "1", "yes")
|
||||
default_brand_prefix: Optional[str] = os.getenv("DEFAULT_BRAND_PREFIX")
|
||||
default_youtube_description: str = os.getenv(
|
||||
"DEFAULT_YOUTUBE_DESCRIPTION",
|
||||
"Karaoke video created with Nomad Karaoke (https://nomadkaraoke.com)\n\n"
|
||||
"AI-powered vocal separation and synchronized lyrics.\n\n"
|
||||
"#karaoke #music #singing #instrumental #lyrics"
|
||||
)
|
||||
|
||||
# Secret Manager cache
|
||||
_secret_cache: Dict[str, str] = {}
|
||||
|
||||
+2
-1
@@ -7,7 +7,7 @@ from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from backend.config import settings
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes
|
||||
from backend.services.tracing import setup_tracing, instrument_app, get_current_trace_id
|
||||
from backend.services.structured_logging import setup_structured_logging
|
||||
|
||||
@@ -108,6 +108,7 @@ app.include_router(internal.router, prefix="/api") # Internal worker endpoints
|
||||
app.include_router(review.router, prefix="/api") # Review UI compatibility endpoints
|
||||
app.include_router(auth.router, prefix="/api") # OAuth credential management
|
||||
app.include_router(audio_search.router, prefix="/api") # Audio search (artist+title mode)
|
||||
app.include_router(themes.router, prefix="/api") # Theme selection for styles
|
||||
|
||||
|
||||
@app.get("/")
|
||||
|
||||
+38
-10
@@ -134,17 +134,23 @@ STATE_TRANSITIONS = {
|
||||
JobStatus.UPLOADING: [JobStatus.NOTIFYING, JobStatus.COMPLETE, JobStatus.FAILED],
|
||||
JobStatus.NOTIFYING: [JobStatus.COMPLETE, JobStatus.FAILED],
|
||||
|
||||
# Terminal states - COMPLETE, PREP_COMPLETE, and CANCELLED have no transitions
|
||||
# FAILED allows retry transitions to resume from checkpoints
|
||||
# Terminal states - COMPLETE, PREP_COMPLETE have no transitions
|
||||
# FAILED and CANCELLED allow retry transitions to resume from checkpoints
|
||||
# PREP_COMPLETE allows finalise-only continuation
|
||||
JobStatus.COMPLETE: [],
|
||||
JobStatus.PREP_COMPLETE: [JobStatus.AWAITING_INSTRUMENTAL_SELECTION, JobStatus.FAILED], # Finalise-only continues from here
|
||||
JobStatus.FAILED: [
|
||||
JobStatus.DOWNLOADING, # Retry from beginning (if input audio exists)
|
||||
JobStatus.INSTRUMENTAL_SELECTED, # Retry from video generation
|
||||
JobStatus.REVIEW_COMPLETE, # Retry from render stage
|
||||
JobStatus.LYRICS_COMPLETE, # Retry from screens generation
|
||||
],
|
||||
JobStatus.CANCELLED: [
|
||||
JobStatus.DOWNLOADING, # Retry from beginning (if input audio exists)
|
||||
JobStatus.INSTRUMENTAL_SELECTED, # Retry from video generation
|
||||
JobStatus.REVIEW_COMPLETE, # Retry from render stage
|
||||
JobStatus.LYRICS_COMPLETE, # Retry from screens generation
|
||||
],
|
||||
JobStatus.CANCELLED: [],
|
||||
|
||||
# Legacy states (for backward compatibility)
|
||||
JobStatus.QUEUED: [JobStatus.PENDING],
|
||||
@@ -192,14 +198,25 @@ class Job(BaseModel):
|
||||
input_media_gcs_path: Optional[str] = None # GCS path to uploaded file
|
||||
|
||||
# User preferences
|
||||
enable_cdg: bool = True # Generate CDG+MP3 package
|
||||
enable_txt: bool = True # Generate TXT+MP3 package
|
||||
enable_cdg: bool = False # Generate CDG+MP3 package (requires style config)
|
||||
enable_txt: bool = False # Generate TXT+MP3 package (requires style config)
|
||||
enable_youtube_upload: bool = False # Upload to YouTube
|
||||
youtube_description: Optional[str] = None # YouTube video description
|
||||
webhook_url: Optional[str] = None # Webhook for notifications
|
||||
user_email: Optional[str] = None # Email for notifications
|
||||
|
||||
# Style configuration (uploaded files)
|
||||
# Theme configuration (pre-made themes from GCS)
|
||||
theme_id: Optional[str] = None # Theme identifier (e.g., "nomad", "default")
|
||||
color_overrides: Dict[str, str] = Field(default_factory=dict)
|
||||
"""
|
||||
User color overrides applied on top of theme. Keys:
|
||||
- artist_color: Hex color for artist name (#RRGGBB)
|
||||
- title_color: Hex color for song title
|
||||
- sung_lyrics_color: Hex color for highlighted lyrics
|
||||
- unsung_lyrics_color: Hex color for unhighlighted lyrics
|
||||
"""
|
||||
|
||||
# Style configuration (uploaded files - used when theme_id is not set)
|
||||
style_params_gcs_path: Optional[str] = None # GCS path to style_params.json
|
||||
style_assets: Dict[str, str] = Field(default_factory=dict)
|
||||
"""
|
||||
@@ -394,16 +411,27 @@ class JobCreate(BaseModel):
|
||||
artist: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
filename: Optional[str] = None # Original uploaded filename
|
||||
|
||||
|
||||
# Optional preferences
|
||||
enable_cdg: bool = True
|
||||
enable_txt: bool = True
|
||||
enable_cdg: bool = False # Requires style config
|
||||
enable_txt: bool = False # Requires style config
|
||||
enable_youtube_upload: bool = False
|
||||
youtube_description: Optional[str] = None
|
||||
webhook_url: Optional[str] = None
|
||||
user_email: Optional[str] = None
|
||||
|
||||
# Style configuration (will be populated after file upload)
|
||||
# Theme configuration (pre-made themes from GCS)
|
||||
theme_id: Optional[str] = None # Theme identifier (e.g., "nomad", "default")
|
||||
color_overrides: Dict[str, str] = Field(default_factory=dict)
|
||||
"""
|
||||
User color overrides applied on top of theme. Keys:
|
||||
- artist_color: Hex color for artist name (#RRGGBB)
|
||||
- title_color: Hex color for song title
|
||||
- sung_lyrics_color: Hex color for highlighted lyrics
|
||||
- unsung_lyrics_color: Hex color for unhighlighted lyrics
|
||||
"""
|
||||
|
||||
# Style configuration (will be populated after file upload, or from theme)
|
||||
style_params_gcs_path: Optional[str] = None
|
||||
style_assets: Dict[str, str] = Field(default_factory=dict)
|
||||
|
||||
|
||||
@@ -12,8 +12,8 @@ class URLSubmissionRequest(BaseModel):
|
||||
title: Optional[str] = None # Auto-detected if not provided
|
||||
|
||||
# Optional preferences
|
||||
enable_cdg: bool = True
|
||||
enable_txt: bool = True
|
||||
enable_cdg: bool = False # Requires style config
|
||||
enable_txt: bool = False # Requires style config
|
||||
enable_youtube_upload: bool = False
|
||||
youtube_description: Optional[str] = None
|
||||
webhook_url: Optional[str] = None
|
||||
@@ -24,10 +24,10 @@ class UploadSubmissionRequest(BaseModel):
|
||||
"""Request to submit a job from an uploaded file."""
|
||||
artist: str
|
||||
title: str
|
||||
|
||||
|
||||
# Optional preferences
|
||||
enable_cdg: bool = True
|
||||
enable_txt: bool = True
|
||||
enable_cdg: bool = False # Requires style config
|
||||
enable_txt: bool = False # Requires style config
|
||||
enable_youtube_upload: bool = False
|
||||
youtube_description: Optional[str] = None
|
||||
webhook_url: Optional[str] = None
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
"""
|
||||
Theme data models for karaoke-gen.
|
||||
|
||||
Themes are pre-created style configurations stored in GCS that users can select
|
||||
when creating karaoke jobs. Each theme includes:
|
||||
- Style parameters (fonts, colors, backgrounds, layouts)
|
||||
- Asset files (images, fonts)
|
||||
- Preview images
|
||||
- Optional YouTube description template
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class ThemeSummary(BaseModel):
|
||||
"""Summary of a theme for listing purposes."""
|
||||
|
||||
id: str = Field(..., description="Unique theme identifier (e.g., 'nomad', 'default')")
|
||||
name: str = Field(..., description="Human-readable theme name")
|
||||
description: str = Field(..., description="Brief description of the theme style")
|
||||
preview_url: Optional[str] = Field(None, description="Signed URL for preview image")
|
||||
thumbnail_url: Optional[str] = Field(None, description="Signed URL for smaller thumbnail")
|
||||
is_default: bool = Field(False, description="Whether this is the default theme")
|
||||
|
||||
|
||||
class ThemeMetadata(BaseModel):
|
||||
"""Metadata for a single theme in the registry."""
|
||||
|
||||
id: str
|
||||
name: str
|
||||
description: str
|
||||
is_default: bool = False
|
||||
created_at: Optional[datetime] = None
|
||||
|
||||
|
||||
class ThemeRegistry(BaseModel):
|
||||
"""Registry of all available themes, stored as _metadata.json in GCS."""
|
||||
|
||||
version: int = 1
|
||||
themes: List[ThemeMetadata] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ThemeDetail(BaseModel):
|
||||
"""Full theme details including style parameters."""
|
||||
|
||||
id: str
|
||||
name: str
|
||||
description: str
|
||||
preview_url: Optional[str] = None
|
||||
is_default: bool = False
|
||||
style_params: Dict[str, Any] = Field(default_factory=dict)
|
||||
has_youtube_description: bool = False
|
||||
|
||||
|
||||
class ColorOverrides(BaseModel):
|
||||
"""
|
||||
User-customizable color overrides that can be applied on top of a theme.
|
||||
|
||||
All colors are hex format (#RRGGBB). When applied:
|
||||
- artist_color: Applied to intro.artist_color, end.artist_color, cdg.artist_color
|
||||
- title_color: Applied to intro.title_color, end.title_color, cdg.title_color
|
||||
- sung_lyrics_color: Applied to karaoke.primary_color (converted to RGBA), cdg.active_fill
|
||||
- unsung_lyrics_color: Applied to karaoke.secondary_color (converted to RGBA), cdg.inactive_fill
|
||||
"""
|
||||
|
||||
artist_color: Optional[str] = Field(
|
||||
None,
|
||||
pattern=r"^#[0-9A-Fa-f]{6}$",
|
||||
description="Hex color for artist name on intro/end screens",
|
||||
)
|
||||
title_color: Optional[str] = Field(
|
||||
None,
|
||||
pattern=r"^#[0-9A-Fa-f]{6}$",
|
||||
description="Hex color for song title on intro/end screens",
|
||||
)
|
||||
sung_lyrics_color: Optional[str] = Field(
|
||||
None,
|
||||
pattern=r"^#[0-9A-Fa-f]{6}$",
|
||||
description="Hex color for lyrics being sung (highlighted)",
|
||||
)
|
||||
unsung_lyrics_color: Optional[str] = Field(
|
||||
None,
|
||||
pattern=r"^#[0-9A-Fa-f]{6}$",
|
||||
description="Hex color for lyrics not yet sung",
|
||||
)
|
||||
|
||||
def has_overrides(self) -> bool:
|
||||
"""Check if any color overrides are set."""
|
||||
return any(
|
||||
[
|
||||
self.artist_color,
|
||||
self.title_color,
|
||||
self.sung_lyrics_color,
|
||||
self.unsung_lyrics_color,
|
||||
]
|
||||
)
|
||||
|
||||
def to_dict(self) -> Dict[str, str]:
|
||||
"""Convert to dict, excluding None values."""
|
||||
return {k: v for k, v in self.model_dump().items() if v is not None}
|
||||
|
||||
|
||||
class ThemesListResponse(BaseModel):
|
||||
"""Response from GET /api/themes endpoint."""
|
||||
|
||||
themes: List[ThemeSummary]
|
||||
|
||||
|
||||
class ThemeDetailResponse(BaseModel):
|
||||
"""Response from GET /api/themes/{theme_id} endpoint."""
|
||||
|
||||
theme: ThemeDetail
|
||||
|
||||
|
||||
# Utility functions for color conversion
|
||||
|
||||
|
||||
def hex_to_rgba(hex_color: str, alpha: int = 255) -> str:
|
||||
"""
|
||||
Convert hex color (#RRGGBB) to RGBA format for ASS subtitles.
|
||||
|
||||
ASS subtitle format uses "R, G, B, A" string format.
|
||||
|
||||
Args:
|
||||
hex_color: Hex color string like "#7070F7"
|
||||
alpha: Alpha value 0-255 (default 255 = opaque)
|
||||
|
||||
Returns:
|
||||
RGBA string like "112, 112, 247, 255"
|
||||
"""
|
||||
hex_color = hex_color.lstrip("#")
|
||||
r = int(hex_color[0:2], 16)
|
||||
g = int(hex_color[2:4], 16)
|
||||
b = int(hex_color[4:6], 16)
|
||||
return f"{r}, {g}, {b}, {alpha}"
|
||||
|
||||
|
||||
def rgba_to_hex(rgba_str: str) -> str:
|
||||
"""
|
||||
Convert RGBA format to hex color.
|
||||
|
||||
Args:
|
||||
rgba_str: RGBA string like "112, 112, 247, 255"
|
||||
|
||||
Returns:
|
||||
Hex color string like "#7070F7"
|
||||
"""
|
||||
parts = [int(x.strip()) for x in rgba_str.split(",")]
|
||||
r, g, b = parts[0], parts[1], parts[2]
|
||||
return f"#{r:02x}{g:02x}{b:02x}"
|
||||
@@ -0,0 +1,469 @@
|
||||
"""
|
||||
Theme service for managing pre-created style themes.
|
||||
|
||||
Themes are stored in GCS at themes/{theme_id}/ with:
|
||||
- style_params.json: Complete style configuration
|
||||
- preview.png: Preview image for theme selection UI
|
||||
- youtube_description.txt: Optional YouTube description template
|
||||
- assets/: Fonts, backgrounds, and other assets
|
||||
|
||||
The service provides:
|
||||
- Theme listing with signed preview URLs
|
||||
- Theme detail retrieval
|
||||
- Color override application
|
||||
- Job style preparation (copying theme to job folder)
|
||||
"""
|
||||
|
||||
import copy
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
import threading
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from backend.models.theme import (
|
||||
ColorOverrides,
|
||||
ThemeDetail,
|
||||
ThemeMetadata,
|
||||
ThemeRegistry,
|
||||
ThemeSummary,
|
||||
hex_to_rgba,
|
||||
)
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# GCS paths for themes
|
||||
THEMES_PREFIX = "themes"
|
||||
METADATA_FILE = f"{THEMES_PREFIX}/_metadata.json"
|
||||
|
||||
|
||||
class ThemeService:
|
||||
"""Service for managing themes from GCS."""
|
||||
|
||||
def __init__(self, storage: Optional[StorageService] = None):
|
||||
"""
|
||||
Initialize the theme service.
|
||||
|
||||
Args:
|
||||
storage: StorageService instance (creates new one if not provided)
|
||||
"""
|
||||
self.storage = storage or StorageService()
|
||||
self._metadata_cache: Optional[ThemeRegistry] = None
|
||||
self._cache_time: Optional[datetime] = None
|
||||
self.CACHE_TTL_SECONDS = 300 # 5 minute cache for theme metadata
|
||||
|
||||
def _get_theme_path(self, theme_id: str, filename: str = "") -> str:
|
||||
"""Get the GCS path for a theme file."""
|
||||
if filename:
|
||||
return f"{THEMES_PREFIX}/{theme_id}/{filename}"
|
||||
return f"{THEMES_PREFIX}/{theme_id}"
|
||||
|
||||
def _is_cache_valid(self) -> bool:
|
||||
"""Check if the metadata cache is still valid."""
|
||||
if self._metadata_cache is None or self._cache_time is None:
|
||||
return False
|
||||
age = datetime.now() - self._cache_time
|
||||
return age.total_seconds() < self.CACHE_TTL_SECONDS
|
||||
|
||||
def _load_metadata(self, force_refresh: bool = False) -> ThemeRegistry:
|
||||
"""
|
||||
Load theme metadata from GCS with caching.
|
||||
|
||||
Args:
|
||||
force_refresh: Force reload from GCS even if cache is valid
|
||||
|
||||
Returns:
|
||||
ThemeRegistry containing all theme metadata
|
||||
"""
|
||||
if not force_refresh and self._is_cache_valid():
|
||||
return self._metadata_cache # type: ignore
|
||||
|
||||
try:
|
||||
data = self.storage.download_json(METADATA_FILE)
|
||||
self._metadata_cache = ThemeRegistry(**data)
|
||||
self._cache_time = datetime.now()
|
||||
logger.info(f"Loaded theme metadata: {len(self._metadata_cache.themes)} themes")
|
||||
return self._metadata_cache
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to load theme metadata: {e}")
|
||||
# Return empty registry on error
|
||||
return ThemeRegistry(version=1, themes=[])
|
||||
|
||||
def list_themes(self) -> List[ThemeSummary]:
|
||||
"""
|
||||
List all available themes with signed preview URLs.
|
||||
|
||||
Returns:
|
||||
List of ThemeSummary objects with preview URLs
|
||||
"""
|
||||
metadata = self._load_metadata()
|
||||
summaries = []
|
||||
|
||||
for theme in metadata.themes:
|
||||
try:
|
||||
# Generate signed URLs for preview images
|
||||
preview_path = self._get_theme_path(theme.id, "preview.png")
|
||||
thumbnail_path = self._get_theme_path(theme.id, "preview_thumbnail.png")
|
||||
|
||||
preview_url = None
|
||||
thumbnail_url = None
|
||||
|
||||
if self.storage.file_exists(preview_path):
|
||||
preview_url = self.storage.generate_signed_url(preview_path, expiration_minutes=60)
|
||||
|
||||
# Try thumbnail, fall back to main preview
|
||||
if self.storage.file_exists(thumbnail_path):
|
||||
thumbnail_url = self.storage.generate_signed_url(thumbnail_path, expiration_minutes=60)
|
||||
elif preview_url:
|
||||
thumbnail_url = preview_url
|
||||
|
||||
summaries.append(
|
||||
ThemeSummary(
|
||||
id=theme.id,
|
||||
name=theme.name,
|
||||
description=theme.description,
|
||||
preview_url=preview_url,
|
||||
thumbnail_url=thumbnail_url,
|
||||
is_default=theme.is_default,
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"Error processing theme {theme.id}: {e}")
|
||||
# Still include theme but without preview URLs
|
||||
summaries.append(
|
||||
ThemeSummary(
|
||||
id=theme.id,
|
||||
name=theme.name,
|
||||
description=theme.description,
|
||||
is_default=theme.is_default,
|
||||
)
|
||||
)
|
||||
|
||||
return summaries
|
||||
|
||||
def get_theme(self, theme_id: str) -> Optional[ThemeDetail]:
|
||||
"""
|
||||
Get full theme details including style parameters.
|
||||
|
||||
Args:
|
||||
theme_id: The theme identifier
|
||||
|
||||
Returns:
|
||||
ThemeDetail if found, None otherwise
|
||||
"""
|
||||
metadata = self._load_metadata()
|
||||
|
||||
# Find theme in metadata
|
||||
theme_meta = next((t for t in metadata.themes if t.id == theme_id), None)
|
||||
if not theme_meta:
|
||||
logger.warning(f"Theme not found: {theme_id}")
|
||||
return None
|
||||
|
||||
try:
|
||||
# Load style_params.json
|
||||
style_params_path = self._get_theme_path(theme_id, "style_params.json")
|
||||
style_params = self.storage.download_json(style_params_path)
|
||||
|
||||
# Check for YouTube description
|
||||
youtube_desc_path = self._get_theme_path(theme_id, "youtube_description.txt")
|
||||
has_youtube_desc = self.storage.file_exists(youtube_desc_path)
|
||||
|
||||
# Generate preview URL
|
||||
preview_path = self._get_theme_path(theme_id, "preview.png")
|
||||
preview_url = None
|
||||
if self.storage.file_exists(preview_path):
|
||||
preview_url = self.storage.generate_signed_url(preview_path, expiration_minutes=60)
|
||||
|
||||
return ThemeDetail(
|
||||
id=theme_id,
|
||||
name=theme_meta.name,
|
||||
description=theme_meta.description,
|
||||
preview_url=preview_url,
|
||||
is_default=theme_meta.is_default,
|
||||
style_params=style_params,
|
||||
has_youtube_description=has_youtube_desc,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Error loading theme {theme_id}: {e}")
|
||||
return None
|
||||
|
||||
def get_theme_style_params(self, theme_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
Get just the style_params.json for a theme.
|
||||
|
||||
Args:
|
||||
theme_id: The theme identifier
|
||||
|
||||
Returns:
|
||||
Style parameters dict if found, None otherwise
|
||||
"""
|
||||
try:
|
||||
style_params_path = self._get_theme_path(theme_id, "style_params.json")
|
||||
return self.storage.download_json(style_params_path)
|
||||
except Exception as e:
|
||||
logger.error(f"Error loading style params for theme {theme_id}: {e}")
|
||||
return None
|
||||
|
||||
def get_youtube_description(self, theme_id: str) -> Optional[str]:
|
||||
"""
|
||||
Get the YouTube description template for a theme.
|
||||
|
||||
Args:
|
||||
theme_id: The theme identifier
|
||||
|
||||
Returns:
|
||||
YouTube description text if found, None otherwise
|
||||
"""
|
||||
try:
|
||||
youtube_desc_path = self._get_theme_path(theme_id, "youtube_description.txt")
|
||||
if not self.storage.file_exists(youtube_desc_path):
|
||||
return None
|
||||
|
||||
# Download to temp file and read
|
||||
with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".txt") as tmp:
|
||||
tmp_path = tmp.name
|
||||
|
||||
try:
|
||||
self.storage.download_file(youtube_desc_path, tmp_path)
|
||||
with open(tmp_path, "r") as f:
|
||||
return f.read()
|
||||
finally:
|
||||
if os.path.exists(tmp_path):
|
||||
os.remove(tmp_path)
|
||||
except Exception as e:
|
||||
logger.error(f"Error loading YouTube description for theme {theme_id}: {e}")
|
||||
return None
|
||||
|
||||
def apply_color_overrides(
|
||||
self, style_params: Dict[str, Any], overrides: ColorOverrides
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Apply user color overrides to theme style parameters.
|
||||
|
||||
Args:
|
||||
style_params: Base style parameters from theme
|
||||
overrides: User color overrides
|
||||
|
||||
Returns:
|
||||
Modified style parameters with overrides applied
|
||||
"""
|
||||
if not overrides.has_overrides():
|
||||
return style_params
|
||||
|
||||
# Deep copy to avoid modifying original
|
||||
result = copy.deepcopy(style_params)
|
||||
|
||||
# Apply artist_color to intro, end, and CDG sections
|
||||
if overrides.artist_color:
|
||||
if "intro" in result:
|
||||
result["intro"]["artist_color"] = overrides.artist_color
|
||||
if "end" in result:
|
||||
result["end"]["artist_color"] = overrides.artist_color
|
||||
if "cdg" in result:
|
||||
result["cdg"]["artist_color"] = overrides.artist_color
|
||||
|
||||
# Apply title_color to intro, end, and CDG sections
|
||||
if overrides.title_color:
|
||||
if "intro" in result:
|
||||
result["intro"]["title_color"] = overrides.title_color
|
||||
if "end" in result:
|
||||
result["end"]["title_color"] = overrides.title_color
|
||||
if "cdg" in result:
|
||||
result["cdg"]["title_color"] = overrides.title_color
|
||||
|
||||
# Apply sung_lyrics_color (karaoke uses RGBA, CDG uses hex)
|
||||
if overrides.sung_lyrics_color:
|
||||
if "karaoke" in result:
|
||||
result["karaoke"]["primary_color"] = hex_to_rgba(overrides.sung_lyrics_color)
|
||||
if "cdg" in result:
|
||||
result["cdg"]["active_fill"] = overrides.sung_lyrics_color
|
||||
|
||||
# Apply unsung_lyrics_color (karaoke uses RGBA, CDG uses hex)
|
||||
if overrides.unsung_lyrics_color:
|
||||
if "karaoke" in result:
|
||||
result["karaoke"]["secondary_color"] = hex_to_rgba(overrides.unsung_lyrics_color)
|
||||
if "cdg" in result:
|
||||
result["cdg"]["inactive_fill"] = overrides.unsung_lyrics_color
|
||||
|
||||
return result
|
||||
|
||||
def prepare_job_style(
|
||||
self,
|
||||
job_id: str,
|
||||
theme_id: str,
|
||||
color_overrides: Optional[ColorOverrides] = None,
|
||||
) -> Tuple[str, Dict[str, str]]:
|
||||
"""
|
||||
Prepare style files for a job by copying theme to job folder.
|
||||
|
||||
This method:
|
||||
1. Loads the theme's style_params.json
|
||||
2. Applies any color overrides
|
||||
3. Updates asset paths to point to theme assets (shared, not copied)
|
||||
4. Uploads modified style_params.json to job folder
|
||||
5. Returns the GCS path and style_assets mapping
|
||||
|
||||
Args:
|
||||
job_id: The job ID
|
||||
theme_id: The theme to use
|
||||
color_overrides: Optional color overrides
|
||||
|
||||
Returns:
|
||||
Tuple of (style_params_gcs_path, style_assets dict)
|
||||
|
||||
Raises:
|
||||
ValueError: If theme not found
|
||||
"""
|
||||
# Load theme style params
|
||||
style_params = self.get_theme_style_params(theme_id)
|
||||
if style_params is None:
|
||||
raise ValueError(f"Theme not found: {theme_id}")
|
||||
|
||||
# Apply color overrides if provided
|
||||
if color_overrides:
|
||||
style_params = self.apply_color_overrides(style_params, color_overrides)
|
||||
|
||||
# Update asset paths to point to theme's shared assets
|
||||
# Theme assets stay in themes/{theme_id}/assets/ - they're shared
|
||||
style_assets = self._build_style_assets_mapping(theme_id, style_params)
|
||||
|
||||
# Update style_params to use theme asset paths (not job-specific)
|
||||
style_params = self._update_asset_paths_in_style(theme_id, style_params)
|
||||
|
||||
# Upload modified style_params.json to job's style folder
|
||||
job_style_path = f"uploads/{job_id}/style/style_params.json"
|
||||
self.storage.upload_json(job_style_path, style_params)
|
||||
|
||||
logger.info(f"Prepared job {job_id} style from theme {theme_id}")
|
||||
|
||||
return job_style_path, style_assets
|
||||
|
||||
def _build_style_assets_mapping(
|
||||
self, theme_id: str, style_params: Dict[str, Any]
|
||||
) -> Dict[str, str]:
|
||||
"""
|
||||
Build the style_assets mapping for a theme.
|
||||
|
||||
Maps asset keys to their GCS paths in the theme folder.
|
||||
"""
|
||||
style_assets = {}
|
||||
theme_assets_prefix = f"{THEMES_PREFIX}/{theme_id}/assets"
|
||||
|
||||
# Check each potential asset type
|
||||
asset_checks = [
|
||||
("intro_background", "intro", "background_image"),
|
||||
("karaoke_background", "karaoke", "background_image"),
|
||||
("end_background", "end", "background_image"),
|
||||
("font", "intro", "font"), # Font is typically shared across sections
|
||||
("cdg_instrumental_background", "cdg", "instrumental_background"),
|
||||
("cdg_title_background", "cdg", "title_screen_background"),
|
||||
("cdg_outro_background", "cdg", "outro_background"),
|
||||
]
|
||||
|
||||
for asset_key, section, field in asset_checks:
|
||||
if section in style_params and field in style_params[section]:
|
||||
value = style_params[section][field]
|
||||
if value and isinstance(value, str):
|
||||
# Check if it's a theme asset path or already has the full path
|
||||
if value.startswith(f"{THEMES_PREFIX}/"):
|
||||
# Already a full theme path
|
||||
style_assets[asset_key] = value
|
||||
elif not value.startswith("/") and not value.startswith("gs://"):
|
||||
# Relative path - prepend theme assets prefix
|
||||
asset_path = f"{theme_assets_prefix}/{os.path.basename(value)}"
|
||||
if self.storage.file_exists(asset_path):
|
||||
style_assets[asset_key] = asset_path
|
||||
|
||||
return style_assets
|
||||
|
||||
def _update_asset_paths_in_style(
|
||||
self, theme_id: str, style_params: Dict[str, Any]
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Update asset paths in style_params to use full GCS theme paths.
|
||||
|
||||
This ensures the style_loader can find assets when processing.
|
||||
"""
|
||||
result = copy.deepcopy(style_params)
|
||||
theme_assets_prefix = f"{THEMES_PREFIX}/{theme_id}/assets"
|
||||
|
||||
# Fields that contain asset paths
|
||||
path_fields = {
|
||||
"intro": ["background_image", "font"],
|
||||
"end": ["background_image", "font"],
|
||||
"karaoke": ["background_image", "font_path"],
|
||||
"cdg": [
|
||||
"font_path",
|
||||
"instrumental_background",
|
||||
"title_screen_background",
|
||||
"outro_background",
|
||||
],
|
||||
}
|
||||
|
||||
for section, fields in path_fields.items():
|
||||
if section not in result:
|
||||
continue
|
||||
for field in fields:
|
||||
if field not in result[section]:
|
||||
continue
|
||||
value = result[section][field]
|
||||
if value and isinstance(value, str):
|
||||
# Skip if already a full path or URL
|
||||
if value.startswith(f"{THEMES_PREFIX}/") or value.startswith("gs://"):
|
||||
continue
|
||||
# Skip absolute local paths (shouldn't happen but be safe)
|
||||
if value.startswith("/"):
|
||||
continue
|
||||
# Update to full theme asset path
|
||||
result[section][field] = f"{theme_assets_prefix}/{os.path.basename(value)}"
|
||||
|
||||
return result
|
||||
|
||||
def theme_exists(self, theme_id: str) -> bool:
|
||||
"""
|
||||
Check if a theme exists.
|
||||
|
||||
Args:
|
||||
theme_id: The theme identifier
|
||||
|
||||
Returns:
|
||||
True if theme exists, False otherwise
|
||||
"""
|
||||
metadata = self._load_metadata()
|
||||
return any(t.id == theme_id for t in metadata.themes)
|
||||
|
||||
def get_default_theme_id(self) -> Optional[str]:
|
||||
"""
|
||||
Get the ID of the default theme.
|
||||
|
||||
Returns:
|
||||
Default theme ID if one exists, None otherwise
|
||||
"""
|
||||
metadata = self._load_metadata()
|
||||
default_theme = next((t for t in metadata.themes if t.is_default), None)
|
||||
return default_theme.id if default_theme else None
|
||||
|
||||
def invalidate_cache(self) -> None:
|
||||
"""Force invalidation of the metadata cache."""
|
||||
self._metadata_cache = None
|
||||
self._cache_time = None
|
||||
logger.info("Theme metadata cache invalidated")
|
||||
|
||||
|
||||
# Singleton instance with thread-safe initialization
|
||||
_theme_service: Optional[ThemeService] = None
|
||||
_theme_service_lock = threading.Lock()
|
||||
|
||||
|
||||
def get_theme_service() -> ThemeService:
|
||||
"""Get or create the singleton ThemeService instance (thread-safe)."""
|
||||
global _theme_service
|
||||
if _theme_service is None:
|
||||
with _theme_service_lock:
|
||||
# Double-check after acquiring lock
|
||||
if _theme_service is None:
|
||||
_theme_service = ThemeService()
|
||||
return _theme_service
|
||||
@@ -1122,9 +1122,10 @@ class TestFinaliseOnlyModels:
|
||||
FinaliseOnlyFileRequest(filename="with_vocals.mkv", content_type="video/mkv", file_type="with_vocals"),
|
||||
]
|
||||
)
|
||||
|
||||
assert request.enable_cdg is True
|
||||
assert request.enable_txt is True
|
||||
|
||||
# CDG/TXT default to None (server resolves based on theme_id)
|
||||
assert request.enable_cdg is None
|
||||
assert request.enable_txt is None
|
||||
assert request.brand_prefix is None
|
||||
assert request.keep_brand_code is None
|
||||
assert request.enable_youtube_upload is False
|
||||
@@ -1270,13 +1271,14 @@ class TestCreateJobFromUrlRequest:
|
||||
request = CreateJobFromUrlRequest(
|
||||
url="https://www.youtube.com/watch?v=dQw4w9WgXcQ"
|
||||
)
|
||||
|
||||
|
||||
assert request.url == "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
|
||||
assert request.artist is None
|
||||
assert request.title is None
|
||||
assert request.enable_cdg is True
|
||||
assert request.enable_txt is True
|
||||
|
||||
# CDG/TXT default to None (server resolves based on theme_id)
|
||||
assert request.enable_cdg is None
|
||||
assert request.enable_txt is None
|
||||
|
||||
def test_create_with_artist_and_title(self):
|
||||
"""Test creating request with URL, artist, and title."""
|
||||
from backend.api.routes.file_upload import CreateJobFromUrlRequest
|
||||
|
||||
@@ -146,8 +146,9 @@ class TestUploadSubmissionRequest:
|
||||
def test_default_options(self):
|
||||
"""Test default option values."""
|
||||
request = UploadSubmissionRequest(artist="Test", title="Test")
|
||||
assert request.enable_cdg is True
|
||||
assert request.enable_txt is True
|
||||
# CDG/TXT disabled by default (requires style config)
|
||||
assert request.enable_cdg is False
|
||||
assert request.enable_txt is False
|
||||
assert request.enable_youtube_upload is False
|
||||
|
||||
|
||||
|
||||
@@ -67,12 +67,31 @@ class TestJobStatusTransitions:
|
||||
"""Test FAILED status can transition to retry checkpoint states."""
|
||||
from backend.models.job import STATE_TRANSITIONS
|
||||
valid_transitions = STATE_TRANSITIONS.get(JobStatus.FAILED, [])
|
||||
|
||||
|
||||
# FAILED should allow retry transitions
|
||||
assert JobStatus.INSTRUMENTAL_SELECTED in valid_transitions, "FAILED should allow retry to INSTRUMENTAL_SELECTED"
|
||||
assert JobStatus.REVIEW_COMPLETE in valid_transitions, "FAILED should allow retry to REVIEW_COMPLETE"
|
||||
assert JobStatus.LYRICS_COMPLETE in valid_transitions, "FAILED should allow retry to LYRICS_COMPLETE"
|
||||
|
||||
def test_cancelled_can_transition_for_retry(self):
|
||||
"""Test CANCELLED status can transition to retry checkpoint states."""
|
||||
from backend.models.job import STATE_TRANSITIONS
|
||||
valid_transitions = STATE_TRANSITIONS.get(JobStatus.CANCELLED, [])
|
||||
|
||||
# CANCELLED should allow same retry transitions as FAILED
|
||||
assert JobStatus.INSTRUMENTAL_SELECTED in valid_transitions, "CANCELLED should allow retry to INSTRUMENTAL_SELECTED"
|
||||
assert JobStatus.REVIEW_COMPLETE in valid_transitions, "CANCELLED should allow retry to REVIEW_COMPLETE"
|
||||
assert JobStatus.LYRICS_COMPLETE in valid_transitions, "CANCELLED should allow retry to LYRICS_COMPLETE"
|
||||
assert JobStatus.DOWNLOADING in valid_transitions, "CANCELLED should allow retry to DOWNLOADING (restart)"
|
||||
|
||||
def test_failed_can_restart_from_beginning(self):
|
||||
"""Test FAILED status can transition to DOWNLOADING for restart from beginning."""
|
||||
from backend.models.job import STATE_TRANSITIONS
|
||||
valid_transitions = STATE_TRANSITIONS.get(JobStatus.FAILED, [])
|
||||
|
||||
# FAILED should allow restart from beginning
|
||||
assert JobStatus.DOWNLOADING in valid_transitions, "FAILED should allow restart to DOWNLOADING"
|
||||
|
||||
|
||||
class TestJobModelSerialization:
|
||||
"""Tests for Job model serialization to/from API."""
|
||||
@@ -119,3 +138,145 @@ class TestJobModelSerialization:
|
||||
assert job.url is None
|
||||
assert job.file_urls == {}
|
||||
|
||||
|
||||
class TestRetryEndpoint:
|
||||
"""Tests for the retry job endpoint."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job_manager(self):
|
||||
"""Create mock job manager."""
|
||||
return MagicMock()
|
||||
|
||||
@pytest.fixture
|
||||
def mock_worker_service(self):
|
||||
"""Create mock worker service."""
|
||||
return MagicMock()
|
||||
|
||||
def test_retry_rejects_pending_job(self, mock_job_manager):
|
||||
"""Test retry endpoint rejects jobs that are not failed or cancelled."""
|
||||
# Create a pending job
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song"
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job
|
||||
|
||||
# The endpoint should reject this with a 400 error
|
||||
# (status check happens before any logic)
|
||||
assert job.status not in [JobStatus.FAILED, JobStatus.CANCELLED]
|
||||
|
||||
def test_retry_accepts_failed_job(self, mock_job_manager):
|
||||
"""Test retry endpoint accepts failed jobs."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.FAILED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
input_media_gcs_path="jobs/test123/input/audio.flac"
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job
|
||||
|
||||
# Status should be accepted
|
||||
assert job.status in [JobStatus.FAILED, JobStatus.CANCELLED]
|
||||
|
||||
def test_retry_accepts_cancelled_job(self, mock_job_manager):
|
||||
"""Test retry endpoint accepts cancelled jobs."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.CANCELLED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
input_media_gcs_path="jobs/test123/input/audio.flac"
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job
|
||||
|
||||
# Status should be accepted
|
||||
assert job.status in [JobStatus.FAILED, JobStatus.CANCELLED]
|
||||
|
||||
def test_retry_checkpoint_detection_video_generation(self):
|
||||
"""Test retry detects video generation checkpoint."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.FAILED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
file_urls={
|
||||
'videos': {'with_vocals': 'gs://bucket/path/video.mkv'}
|
||||
},
|
||||
state_data={
|
||||
'instrumental_selection': 'clean'
|
||||
}
|
||||
)
|
||||
|
||||
# This job has video and instrumental selection - should retry from video generation
|
||||
has_video = job.file_urls.get('videos', {}).get('with_vocals')
|
||||
has_instrumental_selection = (job.state_data or {}).get('instrumental_selection')
|
||||
assert has_video and has_instrumental_selection
|
||||
|
||||
def test_retry_checkpoint_detection_render_stage(self):
|
||||
"""Test retry detects render stage checkpoint."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.FAILED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
file_urls={
|
||||
'lyrics': {'corrections': 'gs://bucket/path/corrections.json'},
|
||||
'screens': {'title': 'gs://bucket/path/title.mov'}
|
||||
}
|
||||
)
|
||||
|
||||
# This job has corrections and screens - should retry from render
|
||||
has_corrections = job.file_urls.get('lyrics', {}).get('corrections')
|
||||
has_screens = job.file_urls.get('screens', {}).get('title')
|
||||
has_video = job.file_urls.get('videos', {}).get('with_vocals')
|
||||
assert has_corrections and has_screens and not has_video
|
||||
|
||||
def test_retry_checkpoint_detection_from_beginning(self):
|
||||
"""Test retry detects need to restart from beginning."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.CANCELLED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
input_media_gcs_path="jobs/test123/input/audio.flac",
|
||||
file_urls={} # No progress yet
|
||||
)
|
||||
|
||||
# This job has input audio but no other files - should restart from beginning
|
||||
has_input = job.input_media_gcs_path
|
||||
has_stems = job.file_urls.get('stems', {}).get('instrumental_clean')
|
||||
has_corrections = job.file_urls.get('lyrics', {}).get('corrections')
|
||||
assert has_input and not has_stems and not has_corrections
|
||||
|
||||
def test_retry_no_input_audio(self):
|
||||
"""Test retry fails when no input audio available."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.CANCELLED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
# No input_media_gcs_path and no url
|
||||
file_urls={}
|
||||
)
|
||||
|
||||
# This job has no input audio - should not be retryable
|
||||
has_input = job.input_media_gcs_path or job.url
|
||||
assert not has_input
|
||||
|
||||
@@ -0,0 +1,516 @@
|
||||
"""
|
||||
Tests for the theme service and API endpoints.
|
||||
|
||||
Tests theme listing, retrieval, color override application, and job style preparation.
|
||||
"""
|
||||
import json
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch, Mock
|
||||
from datetime import datetime
|
||||
|
||||
from backend.models.theme import (
|
||||
ThemeSummary,
|
||||
ThemeDetail,
|
||||
ThemeMetadata,
|
||||
ThemeRegistry,
|
||||
ColorOverrides,
|
||||
hex_to_rgba,
|
||||
rgba_to_hex,
|
||||
)
|
||||
from backend.services.theme_service import ThemeService, get_theme_service
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Color Conversion Tests
|
||||
# =============================================================================
|
||||
|
||||
class TestColorConversion:
|
||||
"""Tests for hex/rgba color conversion utilities."""
|
||||
|
||||
def test_hex_to_rgba_basic(self):
|
||||
"""Test basic hex to RGBA conversion."""
|
||||
result = hex_to_rgba("#7070F7")
|
||||
assert result == "112, 112, 247, 255"
|
||||
|
||||
def test_hex_to_rgba_with_custom_alpha(self):
|
||||
"""Test hex to RGBA with custom alpha."""
|
||||
result = hex_to_rgba("#FF0000", alpha=128)
|
||||
assert result == "255, 0, 0, 128"
|
||||
|
||||
def test_hex_to_rgba_lowercase(self):
|
||||
"""Test hex with lowercase letters."""
|
||||
result = hex_to_rgba("#abcdef")
|
||||
assert result == "171, 205, 239, 255"
|
||||
|
||||
def test_hex_to_rgba_without_hash(self):
|
||||
"""Test hex without leading hash."""
|
||||
result = hex_to_rgba("FFFFFF")
|
||||
assert result == "255, 255, 255, 255"
|
||||
|
||||
def test_rgba_to_hex_basic(self):
|
||||
"""Test basic RGBA to hex conversion."""
|
||||
result = rgba_to_hex("112, 112, 247, 255")
|
||||
assert result == "#7070f7"
|
||||
|
||||
def test_rgba_to_hex_ignores_alpha(self):
|
||||
"""Test that alpha is ignored in conversion."""
|
||||
result = rgba_to_hex("255, 0, 0, 128")
|
||||
assert result == "#ff0000"
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# ColorOverrides Model Tests
|
||||
# =============================================================================
|
||||
|
||||
class TestColorOverrides:
|
||||
"""Tests for ColorOverrides model."""
|
||||
|
||||
def test_has_overrides_empty(self):
|
||||
"""Test has_overrides with no overrides set."""
|
||||
overrides = ColorOverrides()
|
||||
assert overrides.has_overrides() is False
|
||||
|
||||
def test_has_overrides_with_artist_color(self):
|
||||
"""Test has_overrides with artist_color set."""
|
||||
overrides = ColorOverrides(artist_color="#FF0000")
|
||||
assert overrides.has_overrides() is True
|
||||
|
||||
def test_has_overrides_with_all_colors(self):
|
||||
"""Test has_overrides with all colors set."""
|
||||
overrides = ColorOverrides(
|
||||
artist_color="#FF0000",
|
||||
title_color="#00FF00",
|
||||
sung_lyrics_color="#0000FF",
|
||||
unsung_lyrics_color="#FFFF00",
|
||||
)
|
||||
assert overrides.has_overrides() is True
|
||||
|
||||
def test_to_dict_excludes_none(self):
|
||||
"""Test to_dict excludes None values."""
|
||||
overrides = ColorOverrides(artist_color="#FF0000")
|
||||
result = overrides.to_dict()
|
||||
assert result == {"artist_color": "#FF0000"}
|
||||
assert "title_color" not in result
|
||||
|
||||
def test_color_validation_valid(self):
|
||||
"""Test color validation accepts valid hex colors."""
|
||||
overrides = ColorOverrides(artist_color="#AbCdEf")
|
||||
assert overrides.artist_color == "#AbCdEf"
|
||||
|
||||
def test_color_validation_invalid(self):
|
||||
"""Test color validation rejects invalid colors."""
|
||||
with pytest.raises(ValueError):
|
||||
ColorOverrides(artist_color="red")
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
ColorOverrides(artist_color="#GGG")
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# ThemeService Tests
|
||||
# =============================================================================
|
||||
|
||||
class TestThemeService:
|
||||
"""Tests for ThemeService."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_storage(self):
|
||||
"""Create a mock storage service."""
|
||||
storage = MagicMock()
|
||||
return storage
|
||||
|
||||
@pytest.fixture
|
||||
def sample_metadata(self):
|
||||
"""Sample theme metadata for testing."""
|
||||
return {
|
||||
"version": 1,
|
||||
"themes": [
|
||||
{
|
||||
"id": "nomad",
|
||||
"name": "Nomad Karaoke",
|
||||
"description": "Golden artist text, professional look",
|
||||
"is_default": True,
|
||||
},
|
||||
{
|
||||
"id": "default",
|
||||
"name": "Default",
|
||||
"description": "Clean white text on black background",
|
||||
"is_default": False,
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
@pytest.fixture
|
||||
def sample_style_params(self):
|
||||
"""Sample style params for testing."""
|
||||
return {
|
||||
"intro": {
|
||||
"artist_color": "#ffdf6b",
|
||||
"title_color": "#ffffff",
|
||||
"background_image": "intro_bg.png",
|
||||
"font": "Montserrat-Bold.ttf",
|
||||
},
|
||||
"end": {
|
||||
"artist_color": "#ffdf6b",
|
||||
"title_color": "#ffffff",
|
||||
"background_image": "end_bg.png",
|
||||
"font": "Montserrat-Bold.ttf",
|
||||
},
|
||||
"karaoke": {
|
||||
"primary_color": "112, 112, 247, 255",
|
||||
"secondary_color": "255, 255, 255, 255",
|
||||
"background_image": "karaoke_bg.png",
|
||||
"font_path": "Montserrat-Bold.ttf",
|
||||
},
|
||||
"cdg": {
|
||||
"active_fill": "#7070F7",
|
||||
"inactive_fill": "#FFFFFF",
|
||||
"font_path": "Montserrat-Bold.ttf",
|
||||
},
|
||||
}
|
||||
|
||||
def test_list_themes_returns_summaries(self, mock_storage, sample_metadata):
|
||||
"""Test list_themes returns ThemeSummary objects."""
|
||||
mock_storage.download_json.return_value = sample_metadata
|
||||
mock_storage.file_exists.return_value = True
|
||||
mock_storage.generate_signed_url.return_value = "https://signed-url.com/preview.png"
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
themes = service.list_themes()
|
||||
|
||||
assert len(themes) == 2
|
||||
assert themes[0].id == "nomad"
|
||||
assert themes[0].name == "Nomad Karaoke"
|
||||
assert themes[0].is_default is True
|
||||
assert themes[0].preview_url is not None
|
||||
|
||||
def test_list_themes_handles_missing_preview(self, mock_storage, sample_metadata):
|
||||
"""Test list_themes handles missing preview images gracefully."""
|
||||
mock_storage.download_json.return_value = sample_metadata
|
||||
mock_storage.file_exists.return_value = False
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
themes = service.list_themes()
|
||||
|
||||
assert len(themes) == 2
|
||||
assert themes[0].preview_url is None
|
||||
|
||||
def test_get_theme_returns_detail(self, mock_storage, sample_metadata, sample_style_params):
|
||||
"""Test get_theme returns ThemeDetail with style params."""
|
||||
mock_storage.download_json.side_effect = [sample_metadata, sample_style_params]
|
||||
mock_storage.file_exists.return_value = True
|
||||
mock_storage.generate_signed_url.return_value = "https://signed-url.com/preview.png"
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
theme = service.get_theme("nomad")
|
||||
|
||||
assert theme is not None
|
||||
assert theme.id == "nomad"
|
||||
assert theme.name == "Nomad Karaoke"
|
||||
assert "intro" in theme.style_params
|
||||
assert theme.style_params["intro"]["artist_color"] == "#ffdf6b"
|
||||
|
||||
def test_get_theme_returns_none_for_unknown(self, mock_storage, sample_metadata):
|
||||
"""Test get_theme returns None for unknown theme ID."""
|
||||
mock_storage.download_json.return_value = sample_metadata
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
theme = service.get_theme("unknown-theme")
|
||||
|
||||
assert theme is None
|
||||
|
||||
def test_theme_exists_true(self, mock_storage, sample_metadata):
|
||||
"""Test theme_exists returns True for existing theme."""
|
||||
mock_storage.download_json.return_value = sample_metadata
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
assert service.theme_exists("nomad") is True
|
||||
|
||||
def test_theme_exists_false(self, mock_storage, sample_metadata):
|
||||
"""Test theme_exists returns False for unknown theme."""
|
||||
mock_storage.download_json.return_value = sample_metadata
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
assert service.theme_exists("unknown") is False
|
||||
|
||||
def test_get_default_theme_id(self, mock_storage, sample_metadata):
|
||||
"""Test get_default_theme_id returns the default theme."""
|
||||
mock_storage.download_json.return_value = sample_metadata
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
assert service.get_default_theme_id() == "nomad"
|
||||
|
||||
def test_get_default_theme_id_no_default(self, mock_storage):
|
||||
"""Test get_default_theme_id returns None when no default."""
|
||||
mock_storage.download_json.return_value = {
|
||||
"version": 1,
|
||||
"themes": [{"id": "test", "name": "Test", "description": "Test", "is_default": False}],
|
||||
}
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
assert service.get_default_theme_id() is None
|
||||
|
||||
def test_apply_color_overrides_no_changes(self, sample_style_params):
|
||||
"""Test apply_color_overrides with empty overrides."""
|
||||
service = ThemeService()
|
||||
overrides = ColorOverrides()
|
||||
|
||||
result = service.apply_color_overrides(sample_style_params, overrides)
|
||||
|
||||
# Should return original (no deep copy needed when no changes)
|
||||
assert result == sample_style_params
|
||||
|
||||
def test_apply_color_overrides_artist_color(self, sample_style_params):
|
||||
"""Test apply_color_overrides applies artist_color."""
|
||||
service = ThemeService()
|
||||
overrides = ColorOverrides(artist_color="#FF0000")
|
||||
|
||||
result = service.apply_color_overrides(sample_style_params, overrides)
|
||||
|
||||
assert result["intro"]["artist_color"] == "#FF0000"
|
||||
assert result["end"]["artist_color"] == "#FF0000"
|
||||
assert result["cdg"]["artist_color"] == "#FF0000"
|
||||
# Original should be unchanged
|
||||
assert sample_style_params["intro"]["artist_color"] == "#ffdf6b"
|
||||
|
||||
def test_apply_color_overrides_sung_lyrics_color(self, sample_style_params):
|
||||
"""Test apply_color_overrides applies sung_lyrics_color with conversion."""
|
||||
service = ThemeService()
|
||||
overrides = ColorOverrides(sung_lyrics_color="#FF0000")
|
||||
|
||||
result = service.apply_color_overrides(sample_style_params, overrides)
|
||||
|
||||
# Karaoke uses RGBA format
|
||||
assert result["karaoke"]["primary_color"] == "255, 0, 0, 255"
|
||||
# CDG uses hex
|
||||
assert result["cdg"]["active_fill"] == "#FF0000"
|
||||
|
||||
def test_apply_color_overrides_unsung_lyrics_color(self, sample_style_params):
|
||||
"""Test apply_color_overrides applies unsung_lyrics_color."""
|
||||
service = ThemeService()
|
||||
overrides = ColorOverrides(unsung_lyrics_color="#00FF00")
|
||||
|
||||
result = service.apply_color_overrides(sample_style_params, overrides)
|
||||
|
||||
assert result["karaoke"]["secondary_color"] == "0, 255, 0, 255"
|
||||
assert result["cdg"]["inactive_fill"] == "#00FF00"
|
||||
|
||||
def test_metadata_cache(self, mock_storage, sample_metadata):
|
||||
"""Test metadata caching works."""
|
||||
mock_storage.download_json.return_value = sample_metadata
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
|
||||
# First call loads from GCS
|
||||
service.list_themes()
|
||||
assert mock_storage.download_json.call_count == 1
|
||||
|
||||
# Second call uses cache
|
||||
service.list_themes()
|
||||
assert mock_storage.download_json.call_count == 1
|
||||
|
||||
def test_invalidate_cache(self, mock_storage, sample_metadata):
|
||||
"""Test cache invalidation."""
|
||||
mock_storage.download_json.return_value = sample_metadata
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
|
||||
# Load metadata
|
||||
service.list_themes()
|
||||
assert mock_storage.download_json.call_count == 1
|
||||
|
||||
# Invalidate cache
|
||||
service.invalidate_cache()
|
||||
|
||||
# Next call should reload
|
||||
service.list_themes()
|
||||
assert mock_storage.download_json.call_count == 2
|
||||
|
||||
def test_prepare_job_style(self, mock_storage, sample_metadata, sample_style_params):
|
||||
"""Test prepare_job_style creates job style from theme."""
|
||||
mock_storage.download_json.side_effect = [sample_metadata, sample_style_params]
|
||||
mock_storage.file_exists.return_value = True
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
style_path, style_assets = service.prepare_job_style("job123", "nomad")
|
||||
|
||||
# Should upload modified style_params.json
|
||||
mock_storage.upload_json.assert_called_once()
|
||||
assert style_path == "uploads/job123/style/style_params.json"
|
||||
|
||||
def test_prepare_job_style_with_overrides(self, mock_storage, sample_metadata, sample_style_params):
|
||||
"""Test prepare_job_style applies color overrides."""
|
||||
# prepare_job_style calls get_theme_style_params which directly downloads style_params.json
|
||||
# No metadata lookup happens unless we've cached it previously
|
||||
mock_storage.download_json.return_value = sample_style_params
|
||||
mock_storage.file_exists.return_value = True
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
overrides = ColorOverrides(artist_color="#FF0000")
|
||||
|
||||
style_path, style_assets = service.prepare_job_style("job123", "nomad", overrides)
|
||||
|
||||
# Check that upload_json was called with modified style params
|
||||
call_args = mock_storage.upload_json.call_args
|
||||
uploaded_path = call_args[0][0] # First positional arg is the path
|
||||
uploaded_style = call_args[0][1] # Second positional arg is the data
|
||||
|
||||
assert uploaded_path == "uploads/job123/style/style_params.json"
|
||||
# Check that artist_color override was applied
|
||||
assert uploaded_style["intro"]["artist_color"] == "#FF0000"
|
||||
assert uploaded_style["end"]["artist_color"] == "#FF0000"
|
||||
|
||||
def test_prepare_job_style_unknown_theme_raises(self, mock_storage, sample_metadata):
|
||||
"""Test prepare_job_style raises for unknown theme."""
|
||||
# First download_json returns metadata (no unknown theme)
|
||||
# Second download_json for style_params.json should fail
|
||||
def download_json_side_effect(path):
|
||||
if "_metadata.json" in path:
|
||||
return sample_metadata
|
||||
# Unknown theme path - raise exception
|
||||
raise Exception(f"File not found: {path}")
|
||||
|
||||
mock_storage.download_json.side_effect = download_json_side_effect
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
|
||||
with pytest.raises(ValueError, match="Theme not found"):
|
||||
service.prepare_job_style("job123", "unknown-theme")
|
||||
|
||||
def test_get_youtube_description(self, mock_storage, sample_metadata):
|
||||
"""Test get_youtube_description returns template text."""
|
||||
mock_storage.download_json.return_value = sample_metadata
|
||||
mock_storage.file_exists.return_value = True
|
||||
|
||||
# Mock the download_file to write content to temp file
|
||||
def mock_download(gcs_path, local_path):
|
||||
with open(local_path, "w") as f:
|
||||
f.write("Thank you for watching!")
|
||||
|
||||
mock_storage.download_file.side_effect = mock_download
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
desc = service.get_youtube_description("nomad")
|
||||
|
||||
assert desc == "Thank you for watching!"
|
||||
|
||||
def test_get_youtube_description_not_found(self, mock_storage, sample_metadata):
|
||||
"""Test get_youtube_description returns None when no template."""
|
||||
mock_storage.download_json.return_value = sample_metadata
|
||||
mock_storage.file_exists.return_value = False
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
desc = service.get_youtube_description("nomad")
|
||||
|
||||
assert desc is None
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# API Endpoint Tests
|
||||
# =============================================================================
|
||||
|
||||
class TestThemeAPI:
|
||||
"""Tests for theme API endpoints."""
|
||||
|
||||
@pytest.fixture
|
||||
def sample_metadata(self):
|
||||
"""Sample theme metadata."""
|
||||
return {
|
||||
"version": 1,
|
||||
"themes": [
|
||||
{
|
||||
"id": "nomad",
|
||||
"name": "Nomad Karaoke",
|
||||
"description": "Golden artist text",
|
||||
"is_default": True,
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
def test_list_themes_endpoint(self, test_client, sample_metadata):
|
||||
"""Test GET /api/themes returns theme list."""
|
||||
with patch("backend.api.routes.themes.get_theme_service") as mock_get_service:
|
||||
mock_service = MagicMock()
|
||||
mock_service.list_themes.return_value = [
|
||||
ThemeSummary(
|
||||
id="nomad",
|
||||
name="Nomad Karaoke",
|
||||
description="Golden artist text",
|
||||
preview_url="https://example.com/preview.png",
|
||||
is_default=True,
|
||||
)
|
||||
]
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
response = test_client.get("/api/themes")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert len(data["themes"]) == 1
|
||||
assert data["themes"][0]["id"] == "nomad"
|
||||
assert data["themes"][0]["is_default"] is True
|
||||
|
||||
def test_get_theme_endpoint(self, test_client):
|
||||
"""Test GET /api/themes/{theme_id} returns theme detail."""
|
||||
with patch("backend.api.routes.themes.get_theme_service") as mock_get_service:
|
||||
mock_service = MagicMock()
|
||||
mock_service.get_theme.return_value = ThemeDetail(
|
||||
id="nomad",
|
||||
name="Nomad Karaoke",
|
||||
description="Golden artist text",
|
||||
is_default=True,
|
||||
style_params={"intro": {"artist_color": "#ffdf6b"}},
|
||||
)
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
response = test_client.get("/api/themes/nomad")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["theme"]["id"] == "nomad"
|
||||
assert "style_params" in data["theme"]
|
||||
|
||||
def test_get_theme_not_found(self, test_client):
|
||||
"""Test GET /api/themes/{theme_id} returns 404 for unknown theme."""
|
||||
with patch("backend.api.routes.themes.get_theme_service") as mock_get_service:
|
||||
mock_service = MagicMock()
|
||||
mock_service.get_theme.return_value = None
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
response = test_client.get("/api/themes/unknown")
|
||||
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_get_theme_preview_endpoint(self, test_client):
|
||||
"""Test GET /api/themes/{theme_id}/preview returns preview URL."""
|
||||
with patch("backend.api.routes.themes.get_theme_service") as mock_get_service:
|
||||
mock_service = MagicMock()
|
||||
mock_service.theme_exists.return_value = True
|
||||
mock_service.get_theme.return_value = ThemeDetail(
|
||||
id="nomad",
|
||||
name="Nomad Karaoke",
|
||||
description="Golden artist text",
|
||||
preview_url="https://example.com/preview.png",
|
||||
is_default=True,
|
||||
)
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
response = test_client.get("/api/themes/nomad/preview")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "preview_url" in data
|
||||
|
||||
def test_get_youtube_description_endpoint(self, test_client):
|
||||
"""Test GET /api/themes/{theme_id}/youtube-description returns description."""
|
||||
with patch("backend.api.routes.themes.get_theme_service") as mock_get_service:
|
||||
mock_service = MagicMock()
|
||||
mock_service.theme_exists.return_value = True
|
||||
mock_service.get_youtube_description.return_value = "Thank you for watching!"
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
response = test_client.get("/api/themes/nomad/youtube-description")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["description"] == "Thank you for watching!"
|
||||
+1
-1
@@ -75,7 +75,7 @@ steps:
|
||||
--concurrency 1 \
|
||||
--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-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,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD" \
|
||||
--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:
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
playwright-report-prod/
|
||||
@@ -0,0 +1,237 @@
|
||||
/**
|
||||
* Tests for JobActions component
|
||||
*/
|
||||
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { JobActions } from '../job/JobActions'
|
||||
import { Job } from '@/lib/api'
|
||||
|
||||
// Mock the API module
|
||||
jest.mock('@/lib/api', () => ({
|
||||
api: {
|
||||
retryJob: jest.fn(),
|
||||
cancelJob: jest.fn(),
|
||||
deleteJob: jest.fn(),
|
||||
}
|
||||
}))
|
||||
|
||||
describe('JobActions', () => {
|
||||
const mockOnRefresh = jest.fn()
|
||||
const mockOnToggleLogs = jest.fn()
|
||||
|
||||
const baseJob: Partial<Job> = {
|
||||
job_id: '123',
|
||||
created_at: '2025-01-01T00:00:00Z',
|
||||
updated_at: '2025-01-01T00:00:00Z',
|
||||
artist: 'Test Artist',
|
||||
title: 'Test Song',
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('Retry button visibility', () => {
|
||||
it('shows retry button for failed jobs', () => {
|
||||
const failedJob = { ...baseJob, status: 'failed' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={failedJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Retry')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows retry button for cancelled jobs', () => {
|
||||
const cancelledJob = { ...baseJob, status: 'cancelled' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={cancelledJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Retry')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show retry button for pending jobs', () => {
|
||||
const pendingJob = { ...baseJob, status: 'pending' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={pendingJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.queryByText('Retry')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show retry button for processing jobs', () => {
|
||||
const processingJob = { ...baseJob, status: 'processing' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={processingJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.queryByText('Retry')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show retry button for complete jobs', () => {
|
||||
const completeJob = { ...baseJob, status: 'complete' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={completeJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.queryByText('Retry')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Cancel button visibility', () => {
|
||||
it('shows cancel button for pending jobs', () => {
|
||||
const pendingJob = { ...baseJob, status: 'pending' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={pendingJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Cancel')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show cancel button for failed jobs', () => {
|
||||
const failedJob = { ...baseJob, status: 'failed' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={failedJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.queryByText('Cancel')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show cancel button for cancelled jobs', () => {
|
||||
const cancelledJob = { ...baseJob, status: 'cancelled' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={cancelledJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.queryByText('Cancel')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Delete button visibility', () => {
|
||||
it('shows delete button for complete jobs', () => {
|
||||
const completeJob = { ...baseJob, status: 'complete' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={completeJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Delete')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows delete button for failed jobs', () => {
|
||||
const failedJob = { ...baseJob, status: 'failed' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={failedJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Delete')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows delete button for cancelled jobs', () => {
|
||||
const cancelledJob = { ...baseJob, status: 'cancelled' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={cancelledJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Delete')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show delete button for pending jobs', () => {
|
||||
const pendingJob = { ...baseJob, status: 'pending' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={pendingJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.queryByText('Delete')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Show Logs button', () => {
|
||||
it('always shows Show Logs button', () => {
|
||||
const pendingJob = { ...baseJob, status: 'pending' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={pendingJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={false}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Show Logs')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows Hide Logs when logs are visible', () => {
|
||||
const pendingJob = { ...baseJob, status: 'pending' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={pendingJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
showLogs={true}
|
||||
onToggleLogs={mockOnToggleLogs}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Hide Logs')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,190 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import type { ColorOverrides } from "@/lib/video-themes"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from "@/components/ui/collapsible"
|
||||
import { ChevronDown, ChevronUp, Paintbrush, RotateCcw } from "lucide-react"
|
||||
|
||||
interface ColorOverridesProps {
|
||||
value: ColorOverrides
|
||||
onChange: (overrides: ColorOverrides) => void
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
interface ColorFieldProps {
|
||||
id: string
|
||||
label: string
|
||||
description: string
|
||||
value?: string
|
||||
onChange: (value: string | undefined) => void
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
function ColorField({ id, label, description, value, onChange, disabled }: ColorFieldProps) {
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label htmlFor={id} className="text-sm text-slate-300">
|
||||
{label}
|
||||
</Label>
|
||||
{value && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange(undefined)}
|
||||
className="text-xs text-slate-500 hover:text-slate-300"
|
||||
disabled={disabled}
|
||||
>
|
||||
Reset
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className="w-8 h-8 rounded border border-slate-600 flex-shrink-0"
|
||||
style={{ backgroundColor: value || "#333333" }}
|
||||
/>
|
||||
<Input
|
||||
id={id}
|
||||
type="text"
|
||||
placeholder="#RRGGBB"
|
||||
value={value || ""}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value.trim()
|
||||
if (val === "") {
|
||||
onChange(undefined)
|
||||
} else if (/^#[0-9A-Fa-f]{0,6}$/.test(val)) {
|
||||
onChange(val)
|
||||
}
|
||||
}}
|
||||
disabled={disabled}
|
||||
className="bg-slate-800 border-slate-700 text-white placeholder:text-slate-500 font-mono text-sm"
|
||||
/>
|
||||
<Input
|
||||
type="color"
|
||||
value={value || "#333333"}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
disabled={disabled}
|
||||
className="w-10 h-8 p-0 border-0 bg-transparent cursor-pointer"
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-slate-500">{description}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function ColorOverridesPanel({ value, onChange, disabled }: ColorOverridesProps) {
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
|
||||
const hasAnyOverrides = !!(
|
||||
value.artist_color ||
|
||||
value.title_color ||
|
||||
value.sung_lyrics_color ||
|
||||
value.unsung_lyrics_color
|
||||
)
|
||||
|
||||
function handleResetAll() {
|
||||
onChange({})
|
||||
}
|
||||
|
||||
function updateField(field: keyof ColorOverrides, newValue: string | undefined) {
|
||||
onChange({
|
||||
...value,
|
||||
[field]: newValue,
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<Collapsible open={isOpen} onOpenChange={setIsOpen}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
type="button"
|
||||
className="w-full justify-between px-3 py-2 h-auto text-slate-300 hover:text-white hover:bg-slate-700/50"
|
||||
>
|
||||
<span className="flex items-center gap-2">
|
||||
<Paintbrush className="w-4 h-4" />
|
||||
Customize Colors
|
||||
{hasAnyOverrides && (
|
||||
<span className="text-xs bg-amber-500/20 text-amber-400 px-1.5 py-0.5 rounded">
|
||||
Modified
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{isOpen ? (
|
||||
<ChevronUp className="w-4 h-4" />
|
||||
) : (
|
||||
<ChevronDown className="w-4 h-4" />
|
||||
)}
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
|
||||
<CollapsibleContent className="mt-2">
|
||||
<div className="space-y-4 p-4 rounded-lg border border-slate-700 bg-slate-800/50">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-sm text-slate-400">
|
||||
Override theme colors (optional)
|
||||
</p>
|
||||
{hasAnyOverrides && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleResetAll}
|
||||
disabled={disabled}
|
||||
className="text-slate-400 hover:text-white"
|
||||
>
|
||||
<RotateCcw className="w-3 h-3 mr-1" />
|
||||
Reset All
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<ColorField
|
||||
id="artist-color"
|
||||
label="Artist Color"
|
||||
description="Color for artist name on title/end screens"
|
||||
value={value.artist_color}
|
||||
onChange={(v) => updateField("artist_color", v)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
|
||||
<ColorField
|
||||
id="title-color"
|
||||
label="Title Color"
|
||||
description="Color for song title on title/end screens"
|
||||
value={value.title_color}
|
||||
onChange={(v) => updateField("title_color", v)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
|
||||
<ColorField
|
||||
id="sung-lyrics-color"
|
||||
label="Sung Lyrics Color"
|
||||
description="Color for lyrics being sung (highlighted)"
|
||||
value={value.sung_lyrics_color}
|
||||
onChange={(v) => updateField("sung_lyrics_color", v)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
|
||||
<ColorField
|
||||
id="unsung-lyrics-color"
|
||||
label="Unsung Lyrics Color"
|
||||
description="Color for lyrics not yet sung"
|
||||
value={value.unsung_lyrics_color}
|
||||
onChange={(v) => updateField("unsung_lyrics_color", v)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
)
|
||||
}
|
||||
@@ -19,7 +19,7 @@ export function JobActions({ job, onRefresh, showLogs, onToggleLogs }: JobAction
|
||||
const [isCancelling, setIsCancelling] = useState(false)
|
||||
const [isDeleting, setIsDeleting] = useState(false)
|
||||
|
||||
const canRetry = job.status === "failed"
|
||||
const canRetry = job.status === "failed" || job.status === "cancelled"
|
||||
const canCancel = !["complete", "failed", "cancelled"].includes(job.status)
|
||||
const canDelete = ["complete", "failed", "cancelled"].includes(job.status)
|
||||
|
||||
|
||||
@@ -2,10 +2,14 @@
|
||||
|
||||
import { useState } from "react"
|
||||
import { api, ApiError } from "@/lib/api"
|
||||
import type { ColorOverrides } from "@/lib/video-themes"
|
||||
import { cleanColorOverrides } from "@/lib/video-themes"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import { ThemeSelector } from "./ThemeSelector"
|
||||
import { ColorOverridesPanel } from "./ColorOverrides"
|
||||
import { Upload, Youtube, Music, Loader2 } from "lucide-react"
|
||||
|
||||
interface JobSubmissionProps {
|
||||
@@ -31,6 +35,10 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
const [searchArtist, setSearchArtist] = useState("")
|
||||
const [searchTitle, setSearchTitle] = useState("")
|
||||
|
||||
// Theme selection (shared across all tabs)
|
||||
const [selectedTheme, setSelectedTheme] = useState<string | undefined>()
|
||||
const [colorOverrides, setColorOverrides] = useState<ColorOverrides>({})
|
||||
|
||||
async function handleUploadSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
setError("")
|
||||
@@ -46,7 +54,10 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
await api.uploadJob(uploadFile, uploadArtist.trim(), uploadTitle.trim())
|
||||
await api.uploadJob(uploadFile, uploadArtist.trim(), uploadTitle.trim(), {
|
||||
theme_id: selectedTheme,
|
||||
color_overrides: cleanColorOverrides(colorOverrides),
|
||||
})
|
||||
setUploadFile(null)
|
||||
setUploadArtist("")
|
||||
setUploadTitle("")
|
||||
@@ -76,7 +87,11 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
await api.createJobFromUrl(
|
||||
youtubeUrl.trim(),
|
||||
youtubeArtist.trim() || undefined,
|
||||
youtubeTitle.trim() || undefined
|
||||
youtubeTitle.trim() || undefined,
|
||||
{
|
||||
theme_id: selectedTheme,
|
||||
color_overrides: cleanColorOverrides(colorOverrides),
|
||||
}
|
||||
)
|
||||
setYoutubeUrl("")
|
||||
setYoutubeArtist("")
|
||||
@@ -104,7 +119,10 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
await api.searchAudio(searchArtist.trim(), searchTitle.trim())
|
||||
await api.searchAudio(searchArtist.trim(), searchTitle.trim(), false, {
|
||||
theme_id: selectedTheme,
|
||||
color_overrides: cleanColorOverrides(colorOverrides),
|
||||
})
|
||||
setSearchArtist("")
|
||||
setSearchTitle("")
|
||||
onJobCreated()
|
||||
@@ -200,6 +218,20 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Theme Selection */}
|
||||
<div className="space-y-4 pt-4 border-t border-slate-700">
|
||||
<ThemeSelector
|
||||
value={selectedTheme}
|
||||
onChange={setSelectedTheme}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
<ColorOverridesPanel
|
||||
value={colorOverrides}
|
||||
onChange={setColorOverrides}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && activeTab === "upload" && (
|
||||
<p className="text-sm text-red-400 bg-red-500/10 rounded p-2">{error}</p>
|
||||
)}
|
||||
@@ -264,6 +296,20 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Theme Selection */}
|
||||
<div className="space-y-4 pt-4 border-t border-slate-700">
|
||||
<ThemeSelector
|
||||
value={selectedTheme}
|
||||
onChange={setSelectedTheme}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
<ColorOverridesPanel
|
||||
value={colorOverrides}
|
||||
onChange={setColorOverrides}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && activeTab === "url" && (
|
||||
<p className="text-sm text-red-400 bg-red-500/10 rounded p-2">{error}</p>
|
||||
)}
|
||||
@@ -312,6 +358,20 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Theme Selection */}
|
||||
<div className="space-y-4 pt-4 border-t border-slate-700">
|
||||
<ThemeSelector
|
||||
value={selectedTheme}
|
||||
onChange={setSelectedTheme}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
<ColorOverridesPanel
|
||||
value={colorOverrides}
|
||||
onChange={setColorOverrides}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && activeTab === "search" && (
|
||||
<p className="text-sm text-red-400 bg-red-500/10 rounded p-2">{error}</p>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { api } from "@/lib/api"
|
||||
import type { VideoThemeSummary } from "@/lib/video-themes"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import { Palette, AlertCircle } from "lucide-react"
|
||||
|
||||
interface ThemeSelectorProps {
|
||||
value?: string
|
||||
onChange: (themeId: string | undefined) => void
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
export function ThemeSelector({ value, onChange, disabled }: ThemeSelectorProps) {
|
||||
const [themes, setThemes] = useState<VideoThemeSummary[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
async function loadThemes() {
|
||||
try {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
const themeList = await api.listThemes()
|
||||
setThemes(themeList)
|
||||
|
||||
// If no value is set and there's a default theme, select it
|
||||
if (!value && themeList.length > 0) {
|
||||
const defaultTheme = themeList.find(t => t.is_default)
|
||||
if (defaultTheme) {
|
||||
onChange(defaultTheme.id)
|
||||
} else {
|
||||
onChange(themeList[0].id)
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to load themes:", err)
|
||||
setError("Failed to load themes")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
loadThemes()
|
||||
}, []) // Only run once on mount
|
||||
|
||||
const selectedTheme = themes.find(t => t.id === value)
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-slate-200 flex items-center gap-2">
|
||||
<Palette className="w-4 h-4" />
|
||||
Video Theme
|
||||
</Label>
|
||||
<Skeleton className="h-10 w-full bg-slate-700" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error || themes.length === 0) {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-slate-200 flex items-center gap-2">
|
||||
<Palette className="w-4 h-4" />
|
||||
Video Theme
|
||||
</Label>
|
||||
<div className="flex items-center gap-2 text-sm text-amber-400 bg-amber-500/10 rounded p-2">
|
||||
<AlertCircle className="w-4 h-4" />
|
||||
{error || "No themes available"}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="theme-select" className="text-slate-200 flex items-center gap-2">
|
||||
<Palette className="w-4 h-4" />
|
||||
Video Theme
|
||||
</Label>
|
||||
|
||||
<Select
|
||||
value={value || ""}
|
||||
onValueChange={(val) => onChange(val || undefined)}
|
||||
disabled={disabled}
|
||||
>
|
||||
<SelectTrigger
|
||||
id="theme-select"
|
||||
className="bg-slate-800 border-slate-700 text-white"
|
||||
>
|
||||
<SelectValue placeholder="Select a theme..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="bg-slate-800 border-slate-700">
|
||||
{themes.map((theme) => (
|
||||
<SelectItem
|
||||
key={theme.id}
|
||||
value={theme.id}
|
||||
className="text-white hover:bg-slate-700 focus:bg-slate-700"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<span>{theme.name}</span>
|
||||
{theme.is_default && (
|
||||
<span className="text-xs text-amber-400">(Default)</span>
|
||||
)}
|
||||
</div>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* Theme description and preview */}
|
||||
{selectedTheme && (
|
||||
<div className="mt-2 space-y-2">
|
||||
<p className="text-sm text-slate-400">{selectedTheme.description}</p>
|
||||
|
||||
{selectedTheme.thumbnail_url && (
|
||||
<div className="relative w-full aspect-video max-w-xs rounded-lg overflow-hidden border border-slate-700">
|
||||
<img
|
||||
src={selectedTheme.thumbnail_url}
|
||||
alt={`${selectedTheme.name} preview`}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,874 @@
|
||||
import { test, expect, Page, ConsoleMessage, Request, Response } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* Production E2E tests for the complete karaoke generation journey.
|
||||
*
|
||||
* These tests run directly against gen.nomadkaraoke.com (production).
|
||||
*
|
||||
* IMPORTANT: Set KARAOKE_ACCESS_TOKEN environment variable:
|
||||
* KARAOKE_ACCESS_TOKEN=your-token npx playwright test --config=playwright.production.config.ts
|
||||
*
|
||||
* The complete user journey:
|
||||
* 1. Enter artist name and song title
|
||||
* 2. Select audio source from search results
|
||||
* 3. Wait for audio download and preparation
|
||||
* 4. Review/correct lyrics in the review UI
|
||||
* 5. Submit the review
|
||||
* 6. Wait for render stage
|
||||
* 7. Select instrumental (clean or with backing vocals)
|
||||
* 8. Wait for final render and distribution
|
||||
* 9. Verify YouTube upload and Dropbox folder links
|
||||
*/
|
||||
|
||||
const ACCESS_TOKEN = process.env.KARAOKE_ACCESS_TOKEN;
|
||||
const PROD_URL = 'https://gen.nomadkaraoke.com';
|
||||
const API_URL = 'https://api.nomadkaraoke.com';
|
||||
|
||||
// Test song - using something short and reliable
|
||||
const TEST_ARTIST = 'LCMDF';
|
||||
const TEST_TITLE = 'Take Me To The Mountains';
|
||||
|
||||
// Helper to authenticate the page by setting localStorage token
|
||||
async function authenticatePage(page: Page) {
|
||||
if (!ACCESS_TOKEN) {
|
||||
throw new Error('KARAOKE_ACCESS_TOKEN environment variable is required for production tests');
|
||||
}
|
||||
|
||||
// Set the token in localStorage before navigating
|
||||
await page.addInitScript((token) => {
|
||||
localStorage.setItem('karaoke_access_token', token);
|
||||
}, ACCESS_TOKEN);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Network and console logging for debugging
|
||||
function setupLogging(page: Page) {
|
||||
const logs: { type: string; url?: string; status?: number; text?: string; body?: any }[] = [];
|
||||
|
||||
page.on('request', (request: Request) => {
|
||||
if (request.url().includes('/api/')) {
|
||||
console.log(`>> ${request.method()} ${request.url()}`);
|
||||
logs.push({ type: 'request', url: request.url() });
|
||||
}
|
||||
});
|
||||
|
||||
page.on('response', async (response: Response) => {
|
||||
if (response.url().includes('/api/')) {
|
||||
console.log(`<< ${response.status()} ${response.url()}`);
|
||||
logs.push({ type: 'response', url: response.url(), status: response.status() });
|
||||
if (response.status() >= 400) {
|
||||
try {
|
||||
const body = await response.json();
|
||||
console.log(' Error:', JSON.stringify(body));
|
||||
logs.push({ type: 'error', body });
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
page.on('console', (msg: ConsoleMessage) => {
|
||||
if (msg.type() === 'error') {
|
||||
console.log(`[Console Error] ${msg.text()}`);
|
||||
logs.push({ type: 'console-error', text: msg.text() });
|
||||
}
|
||||
});
|
||||
|
||||
return logs;
|
||||
}
|
||||
|
||||
// Wait for a job to reach a specific status with progress logging
|
||||
async function waitForJobStatus(
|
||||
page: Page,
|
||||
targetStatuses: string[],
|
||||
timeoutMs: number = 600000, // 10 minutes default
|
||||
pollIntervalMs: number = 5000
|
||||
): Promise<{ status: string; jobId?: string }> {
|
||||
const startTime = Date.now();
|
||||
let lastStatus = '';
|
||||
|
||||
while (Date.now() - startTime < timeoutMs) {
|
||||
// Find job cards with status badges
|
||||
const badges = await page.locator('[class*="rounded-lg"][class*="border"]').locator('span, [class*="Badge"]').allTextContents();
|
||||
const allText = badges.join(' ').toLowerCase();
|
||||
|
||||
// Check for target statuses
|
||||
for (const status of targetStatuses) {
|
||||
if (allText.includes(status.toLowerCase())) {
|
||||
console.log(`Found target status: ${status}`);
|
||||
return { status };
|
||||
}
|
||||
}
|
||||
|
||||
// Check for failure states
|
||||
if (allText.includes('failed')) {
|
||||
// Get error details
|
||||
const errorDetails = await page.locator('[class*="text-red"]').allTextContents();
|
||||
throw new Error(`Job failed: ${errorDetails.join(', ')}`);
|
||||
}
|
||||
if (allText.includes('cancelled')) {
|
||||
throw new Error('Job was cancelled');
|
||||
}
|
||||
|
||||
// Log progress updates
|
||||
const currentBadges = badges.filter(b => b.trim()).join(', ');
|
||||
if (currentBadges !== lastStatus) {
|
||||
console.log(`Current status: ${currentBadges}`);
|
||||
lastStatus = currentBadges;
|
||||
}
|
||||
|
||||
// Click refresh and wait
|
||||
const refreshBtn = page.getByRole('button', { name: /refresh/i });
|
||||
if (await refreshBtn.isVisible()) {
|
||||
await refreshBtn.click();
|
||||
}
|
||||
await page.waitForTimeout(pollIntervalMs);
|
||||
}
|
||||
|
||||
throw new Error(`Timeout waiting for status: ${targetStatuses.join(' or ')}`);
|
||||
}
|
||||
|
||||
test.describe('Production Full Karaoke Generation Journey', () => {
|
||||
test.beforeEach(async ({ page }, testInfo) => {
|
||||
// Ensure we have authentication
|
||||
await authenticatePage(page);
|
||||
setupLogging(page);
|
||||
});
|
||||
|
||||
test('Step 1: Homepage loads and shows interface', async ({ page }) => {
|
||||
await page.goto(PROD_URL);
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Screenshot for visual verification
|
||||
await page.screenshot({ path: 'test-results/prod-01-homepage.png', fullPage: true });
|
||||
|
||||
// Verify main elements
|
||||
await expect(page.locator('h1')).toContainText('Karaoke Generator');
|
||||
await expect(page.getByRole('tab', { name: /search/i })).toBeVisible();
|
||||
await expect(page.locator('text=Recent Jobs')).toBeVisible();
|
||||
|
||||
console.log('Homepage loaded successfully');
|
||||
});
|
||||
|
||||
test('Step 2: Can search for audio and see results', async ({ page }) => {
|
||||
test.setTimeout(180000); // 3 minutes - search can be slow
|
||||
|
||||
await page.goto(PROD_URL);
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Click Search tab
|
||||
await page.getByRole('tab', { name: /search/i }).click();
|
||||
await page.waitForTimeout(500);
|
||||
|
||||
// Fill in artist and title
|
||||
await page.getByLabel('Artist').fill(TEST_ARTIST);
|
||||
await page.getByLabel('Title').fill(TEST_TITLE);
|
||||
|
||||
await page.screenshot({ path: 'test-results/prod-02-search-form.png' });
|
||||
|
||||
// Submit search
|
||||
console.log(`Searching for: ${TEST_ARTIST} - ${TEST_TITLE}`);
|
||||
const searchButton = page.getByRole('button', { name: /search.*create/i });
|
||||
await searchButton.click();
|
||||
|
||||
// Wait for response - could be quick or take a while
|
||||
await page.waitForTimeout(5000);
|
||||
|
||||
// Check for loading state or error
|
||||
const errorDiv = page.locator('[class*="text-red"]').first();
|
||||
const hasError = await errorDiv.isVisible().catch(() => false);
|
||||
|
||||
if (hasError) {
|
||||
const errorText = await errorDiv.textContent();
|
||||
console.log(`Search error: ${errorText}`);
|
||||
await page.screenshot({ path: 'test-results/prod-02-search-error.png' });
|
||||
// Don't fail - document the error state
|
||||
} else {
|
||||
// Should see either results or job created
|
||||
await page.screenshot({ path: 'test-results/prod-02-search-submitted.png' });
|
||||
console.log('Search request submitted');
|
||||
}
|
||||
});
|
||||
|
||||
test('Step 3: Full journey - Search to Audio Selection', async ({ page }) => {
|
||||
test.setTimeout(300000); // 5 minutes
|
||||
|
||||
await page.goto(PROD_URL);
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// First check if there's already a job awaiting audio selection
|
||||
await page.click('button:has-text("Refresh")');
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
let jobCard = page.locator('[class*="rounded-lg"][class*="border"]').filter({
|
||||
hasText: /select audio/i
|
||||
}).first();
|
||||
|
||||
if (!await jobCard.isVisible()) {
|
||||
// Create new job via search
|
||||
console.log('Creating new job via search...');
|
||||
await page.getByRole('tab', { name: /search/i }).click();
|
||||
await page.getByLabel('Artist').fill(TEST_ARTIST);
|
||||
await page.getByLabel('Title').fill(TEST_TITLE);
|
||||
await page.getByRole('button', { name: /search.*create/i }).click();
|
||||
|
||||
// Wait for job to appear and reach audio selection state
|
||||
await page.waitForTimeout(10000);
|
||||
await page.click('button:has-text("Refresh")');
|
||||
await page.waitForTimeout(3000);
|
||||
|
||||
jobCard = page.locator('[class*="rounded-lg"][class*="border"]').filter({
|
||||
hasText: /select audio/i
|
||||
}).first();
|
||||
}
|
||||
|
||||
if (await jobCard.isVisible()) {
|
||||
console.log('Found job awaiting audio selection');
|
||||
await jobCard.click();
|
||||
await page.waitForTimeout(1000);
|
||||
await page.screenshot({ path: 'test-results/prod-03-job-expanded.png' });
|
||||
|
||||
// Open audio selection dialog
|
||||
const selectAudioBtn = page.getByRole('button', { name: /select audio/i });
|
||||
if (await selectAudioBtn.isVisible()) {
|
||||
await selectAudioBtn.click();
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
const dialog = page.locator('[role="dialog"]');
|
||||
if (await dialog.isVisible()) {
|
||||
await page.screenshot({ path: 'test-results/prod-03-audio-dialog.png', fullPage: true });
|
||||
|
||||
// Count audio options
|
||||
const selectButtons = dialog.getByRole('button', { name: /^select$/i });
|
||||
const optionCount = await selectButtons.count();
|
||||
console.log(`Found ${optionCount} audio options`);
|
||||
|
||||
if (optionCount > 0) {
|
||||
// Select first option
|
||||
console.log('Selecting first audio option...');
|
||||
await selectButtons.first().click();
|
||||
|
||||
// Wait for dialog to close (download may take time)
|
||||
const closed = await dialog.waitFor({ state: 'hidden', timeout: 120000 }).then(() => true).catch(() => false);
|
||||
if (closed) {
|
||||
console.log('Audio selection completed');
|
||||
} else {
|
||||
console.log('Dialog still open - may be processing');
|
||||
await page.keyboard.press('Escape');
|
||||
}
|
||||
|
||||
await page.screenshot({ path: 'test-results/prod-03-after-selection.png' });
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.log('No job awaiting audio selection');
|
||||
await page.screenshot({ path: 'test-results/prod-03-no-audio-job.png' });
|
||||
}
|
||||
});
|
||||
|
||||
test('Step 4: Full journey - Lyrics Review', async ({ page }) => {
|
||||
test.setTimeout(600000); // 10 minutes - review can take time
|
||||
|
||||
await page.goto(PROD_URL);
|
||||
await page.waitForLoadState('networkidle');
|
||||
await page.click('button:has-text("Refresh")');
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
// Look for job awaiting review
|
||||
const reviewJob = page.locator('[class*="rounded-lg"][class*="border"]').filter({
|
||||
hasText: /awaiting review|review lyrics/i
|
||||
}).first();
|
||||
|
||||
if (await reviewJob.isVisible()) {
|
||||
console.log('Found job awaiting lyrics review');
|
||||
await reviewJob.click();
|
||||
await page.waitForTimeout(1000);
|
||||
await page.screenshot({ path: 'test-results/prod-04-review-job.png' });
|
||||
|
||||
// Click review lyrics button (use .first() since there may be multiple jobs with this button)
|
||||
const reviewBtn = page.getByRole('button', { name: /review lyrics/i }).or(page.getByRole('link', { name: /review lyrics/i })).first();
|
||||
if (await reviewBtn.isVisible()) {
|
||||
console.log('Opening lyrics review UI...');
|
||||
|
||||
// The review button opens a new tab with the LyricsTranscriber UI
|
||||
const [popup] = await Promise.all([
|
||||
page.context().waitForEvent('page', { timeout: 15000 }).catch(() => null),
|
||||
reviewBtn.click()
|
||||
]);
|
||||
|
||||
if (popup) {
|
||||
await popup.waitForLoadState('networkidle', { timeout: 60000 }).catch(() => {
|
||||
console.log('Review UI network idle timeout - continuing anyway');
|
||||
});
|
||||
await popup.screenshot({ path: 'test-results/prod-04-review-ui.png', fullPage: true });
|
||||
console.log(`Review UI opened: ${popup.url()}`);
|
||||
|
||||
// Wait for the review UI to fully load
|
||||
await popup.waitForTimeout(5000);
|
||||
|
||||
// The LyricsTranscriber review UI should have:
|
||||
// - A preview video player
|
||||
// - Lyrics display with timing
|
||||
// - Edit controls
|
||||
// - A submit/complete button
|
||||
|
||||
// First, let's see what buttons are available
|
||||
const allButtons = await popup.getByRole('button').allTextContents();
|
||||
console.log(`Available buttons in review UI: ${allButtons.join(', ')}`);
|
||||
|
||||
// Take a screenshot after loading
|
||||
await popup.screenshot({ path: 'test-results/prod-04-review-ui-loaded.png', fullPage: true });
|
||||
|
||||
// The review flow in LyricsTranscriber is:
|
||||
// 1. Click "Preview Video" button to generate preview
|
||||
// 2. Wait for preview to generate (this opens a modal)
|
||||
// 3. Click "Complete Review" in the modal to submit
|
||||
|
||||
// Step 1: Click "Preview Video" button
|
||||
const previewBtn = popup.locator('button:has-text("Preview Video")').first();
|
||||
if (await previewBtn.isVisible({ timeout: 5000 }).catch(() => false)) {
|
||||
console.log('Found "Preview Video" button, clicking...');
|
||||
await previewBtn.click();
|
||||
|
||||
// Wait for preview to generate (can take up to 30-60 seconds)
|
||||
console.log('Waiting for preview video to generate...');
|
||||
await popup.waitForTimeout(10000);
|
||||
await popup.screenshot({ path: 'test-results/prod-04-preview-generating.png' });
|
||||
|
||||
// Step 2: Look for "Complete Review" button (appears after preview is ready or in modal)
|
||||
let submitted = false;
|
||||
const maxWaitAttempts = 12; // Wait up to 2 minutes for preview
|
||||
for (let i = 0; i < maxWaitAttempts && !submitted; i++) {
|
||||
// Check if popup is still open
|
||||
if (popup.isClosed()) {
|
||||
console.log('Popup closed - review may have been auto-submitted');
|
||||
submitted = true;
|
||||
break;
|
||||
}
|
||||
|
||||
// Look for Complete Review button
|
||||
const completeBtn = popup.locator('button:has-text("Complete Review")').first();
|
||||
if (await completeBtn.isVisible({ timeout: 5000 }).catch(() => false)) {
|
||||
console.log('Found "Complete Review" button, clicking...');
|
||||
await completeBtn.click();
|
||||
// Clicking Complete Review closes the popup, so catch any errors
|
||||
await popup.waitForTimeout(3000).catch(() => {
|
||||
console.log('Popup closed after clicking Complete Review (expected)');
|
||||
});
|
||||
submitted = true;
|
||||
console.log('Review submitted successfully!');
|
||||
} else {
|
||||
console.log(`Waiting for Complete Review button... (attempt ${i + 1}/${maxWaitAttempts})`);
|
||||
await popup.waitForTimeout(10000).catch(() => {});
|
||||
await popup.screenshot({ path: `test-results/prod-04-waiting-${i}.png` }).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
if (!submitted) {
|
||||
console.log('Could not find "Complete Review" button after waiting');
|
||||
const allButtons = await popup.getByRole('button').allTextContents().catch(() => []);
|
||||
console.log(`Available buttons: ${allButtons.filter(b => b.trim()).join(', ')}`);
|
||||
}
|
||||
} else {
|
||||
console.log('Preview Video button not found, trying direct Complete Review...');
|
||||
// Fallback: Maybe the modal is already open
|
||||
const completeBtn = popup.locator('button:has-text("Complete Review")').first();
|
||||
if (await completeBtn.isVisible({ timeout: 5000 }).catch(() => false)) {
|
||||
await completeBtn.click();
|
||||
await popup.waitForTimeout(3000);
|
||||
console.log('Review submitted via direct Complete Review button');
|
||||
await popup.screenshot({ path: 'test-results/prod-04-after-submit.png' });
|
||||
} else {
|
||||
console.log('Could not find Complete Review button');
|
||||
const allButtons = await popup.getByRole('button').allTextContents();
|
||||
console.log(`Available buttons: ${allButtons.filter(b => b.trim()).join(', ')}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Close popup if still open
|
||||
if (!popup.isClosed()) {
|
||||
await popup.close().catch(() => {});
|
||||
}
|
||||
|
||||
// Refresh main page to check status
|
||||
await page.click('button:has-text("Refresh")');
|
||||
await page.waitForTimeout(3000);
|
||||
await page.screenshot({ path: 'test-results/prod-04-after-review.png' });
|
||||
|
||||
// Check if job progressed past review
|
||||
const newStatus = await page.locator('[class*="rounded-lg"][class*="border"]').first().locator('span').allTextContents();
|
||||
console.log(`Job status after review: ${newStatus.filter(s => s.trim()).join(', ')}`);
|
||||
|
||||
// Verify the job is no longer in "awaiting review" state
|
||||
const pageTextAfter = await page.locator('body').textContent();
|
||||
if (pageTextAfter?.toLowerCase().includes('awaiting review')) {
|
||||
console.log('WARNING: Job still shows "awaiting review" after submission');
|
||||
} else if (pageTextAfter?.toLowerCase().includes('review complete') ||
|
||||
pageTextAfter?.toLowerCase().includes('rendering') ||
|
||||
pageTextAfter?.toLowerCase().includes('select instrumental')) {
|
||||
console.log('SUCCESS: Job progressed past review stage!');
|
||||
}
|
||||
|
||||
} else {
|
||||
// No popup - might have navigated in same page
|
||||
console.log('Review button did not open popup, checking current page...');
|
||||
await page.waitForTimeout(2000);
|
||||
await page.screenshot({ path: 'test-results/prod-04-review-same-page.png' });
|
||||
}
|
||||
} else {
|
||||
console.log('Review button not visible');
|
||||
}
|
||||
} else {
|
||||
console.log('No jobs awaiting lyrics review');
|
||||
await page.screenshot({ path: 'test-results/prod-04-no-review-job.png' });
|
||||
}
|
||||
});
|
||||
|
||||
test('Step 5: Full journey - Instrumental Selection', async ({ page }) => {
|
||||
test.setTimeout(300000); // 5 minutes
|
||||
|
||||
await page.goto(PROD_URL);
|
||||
await page.waitForLoadState('networkidle');
|
||||
await page.click('button:has-text("Refresh")');
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
// Look for job awaiting instrumental selection
|
||||
const instrumentalJob = page.locator('[class*="rounded-lg"][class*="border"]').filter({
|
||||
hasText: /select instrumental/i
|
||||
}).first();
|
||||
|
||||
if (await instrumentalJob.isVisible()) {
|
||||
console.log('Found job awaiting instrumental selection');
|
||||
await instrumentalJob.click();
|
||||
await page.waitForTimeout(1000);
|
||||
await page.screenshot({ path: 'test-results/prod-05-instrumental-job.png' });
|
||||
|
||||
// Click select instrumental button (use .first() since there may be multiple jobs with this button)
|
||||
const selectBtn = page.getByRole('button', { name: /select instrumental/i }).first();
|
||||
if (await selectBtn.isVisible()) {
|
||||
await selectBtn.click();
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
const dialog = page.locator('[role="dialog"]');
|
||||
if (await dialog.isVisible()) {
|
||||
await page.screenshot({ path: 'test-results/prod-05-instrumental-dialog.png' });
|
||||
|
||||
// Find and click "Clean" option (usually preferred)
|
||||
const cleanOption = dialog.getByRole('button', { name: /clean|select/i }).first();
|
||||
if (await cleanOption.isVisible()) {
|
||||
console.log('Selecting clean instrumental...');
|
||||
await cleanOption.click();
|
||||
|
||||
await dialog.waitFor({ state: 'hidden', timeout: 30000 }).catch(() => {
|
||||
console.log('Dialog still open after selection');
|
||||
});
|
||||
|
||||
await page.screenshot({ path: 'test-results/prod-05-after-instrumental.png' });
|
||||
console.log('Instrumental selection completed');
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.log('No jobs awaiting instrumental selection');
|
||||
await page.screenshot({ path: 'test-results/prod-05-no-instrumental-job.png' });
|
||||
}
|
||||
});
|
||||
|
||||
test('Step 6: Verify completed job - Downloads and Distribution', async ({ page }) => {
|
||||
test.setTimeout(180000); // 3 minutes
|
||||
|
||||
await page.goto(PROD_URL);
|
||||
await page.waitForLoadState('networkidle');
|
||||
await page.click('button:has-text("Refresh")');
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
// Look for completed job
|
||||
const completedJob = page.locator('[class*="rounded-lg"][class*="border"]').filter({
|
||||
hasText: /complete/i
|
||||
}).first();
|
||||
|
||||
if (await completedJob.isVisible()) {
|
||||
console.log('Found completed job');
|
||||
await completedJob.click();
|
||||
await page.waitForTimeout(2000);
|
||||
await page.screenshot({ path: 'test-results/prod-06-completed-job.png', fullPage: true });
|
||||
|
||||
// Look for download links
|
||||
const downloadSection = page.locator('text=Download').first();
|
||||
if (await downloadSection.isVisible()) {
|
||||
console.log('Downloads section visible');
|
||||
}
|
||||
|
||||
// Look for YouTube link
|
||||
const youtubeLink = page.locator('a[href*="youtube.com"], a[href*="youtu.be"]').first();
|
||||
if (await youtubeLink.isVisible()) {
|
||||
const href = await youtubeLink.getAttribute('href');
|
||||
console.log(`YouTube link found: ${href}`);
|
||||
} else {
|
||||
console.log('No YouTube link found');
|
||||
}
|
||||
|
||||
// Look for Dropbox link
|
||||
const dropboxLink = page.locator('a[href*="dropbox.com"]').first();
|
||||
if (await dropboxLink.isVisible()) {
|
||||
const href = await dropboxLink.getAttribute('href');
|
||||
console.log(`Dropbox link found: ${href}`);
|
||||
} else {
|
||||
console.log('No Dropbox link found');
|
||||
}
|
||||
|
||||
// Check for video download buttons
|
||||
const videoDownloads = page.locator('a:has-text("720p"), a:has-text("4K"), button:has-text("Download")');
|
||||
const downloadCount = await videoDownloads.count();
|
||||
console.log(`Found ${downloadCount} download options`);
|
||||
|
||||
} else {
|
||||
console.log('No completed jobs found');
|
||||
await page.screenshot({ path: 'test-results/prod-06-no-completed-job.png' });
|
||||
}
|
||||
});
|
||||
|
||||
test('Full E2E Journey - Complete track generation', async ({ page }) => {
|
||||
/**
|
||||
* FULL END-TO-END TEST
|
||||
*
|
||||
* This test goes through the entire journey:
|
||||
* 1. Search for a song
|
||||
* 2. Select audio
|
||||
* 3. Wait for preparation
|
||||
* 4. Review lyrics (or auto-accept in auto mode)
|
||||
* 5. Select instrumental
|
||||
* 6. Wait for render
|
||||
* 7. Verify distribution (YouTube, Dropbox)
|
||||
*
|
||||
* WARNING: This creates a real karaoke track on production!
|
||||
* Only run when you want to test the full system.
|
||||
*/
|
||||
test.setTimeout(900000); // 15 minutes - full generation takes time
|
||||
|
||||
// Use auto mode for non-interactive flow
|
||||
await page.goto(`${PROD_URL}?auto=true`);
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Verify auto mode banner
|
||||
const autoBanner = page.locator('text=Non-Interactive Mode');
|
||||
if (await autoBanner.isVisible()) {
|
||||
console.log('Auto mode enabled');
|
||||
} else {
|
||||
console.log('Auto mode may not have activated, continuing...');
|
||||
}
|
||||
|
||||
await page.screenshot({ path: 'test-results/prod-e2e-01-start.png' });
|
||||
|
||||
// Step 1: Search for song
|
||||
console.log('=== Step 1: Searching for song ===');
|
||||
await page.getByRole('tab', { name: /search/i }).click();
|
||||
await page.getByLabel('Artist').fill(TEST_ARTIST);
|
||||
await page.getByLabel('Title').fill(TEST_TITLE);
|
||||
|
||||
// Generate unique identifier to track our job
|
||||
const timestamp = Date.now();
|
||||
console.log(`Test timestamp: ${timestamp}`);
|
||||
|
||||
await page.getByRole('button', { name: /search.*create/i }).click();
|
||||
console.log('Search submitted, waiting for job creation...');
|
||||
|
||||
// Wait for job to appear
|
||||
await page.waitForTimeout(15000);
|
||||
await page.click('button:has-text("Refresh")');
|
||||
await page.screenshot({ path: 'test-results/prod-e2e-02-after-search.png' });
|
||||
|
||||
// Step 2-3: Audio selection (may happen automatically with search results, or need manual)
|
||||
console.log('=== Step 2: Audio selection ===');
|
||||
let needsAudioSelection = true;
|
||||
let attempts = 0;
|
||||
const maxAttempts = 30; // 2.5 minutes of checking
|
||||
|
||||
while (needsAudioSelection && attempts < maxAttempts) {
|
||||
await page.click('button:has-text("Refresh")');
|
||||
await page.waitForTimeout(5000);
|
||||
|
||||
// Check current state
|
||||
const pageText = await page.locator('body').textContent();
|
||||
|
||||
if (pageText?.toLowerCase().includes('select audio')) {
|
||||
console.log('Job needs audio selection');
|
||||
|
||||
// Find and click the job card
|
||||
const jobCard = page.locator('[class*="rounded-lg"][class*="border"]').filter({
|
||||
hasText: /select audio/i
|
||||
}).first();
|
||||
|
||||
if (await jobCard.isVisible()) {
|
||||
await jobCard.click();
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
const selectAudioBtn = page.getByRole('button', { name: /select audio/i });
|
||||
if (await selectAudioBtn.isVisible()) {
|
||||
await selectAudioBtn.click();
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
const dialog = page.locator('[role="dialog"]');
|
||||
if (await dialog.isVisible()) {
|
||||
const selectButtons = dialog.getByRole('button', { name: /^select$/i });
|
||||
if (await selectButtons.count() > 0) {
|
||||
console.log('Selecting first audio option');
|
||||
await selectButtons.first().click();
|
||||
await page.waitForTimeout(5000);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
needsAudioSelection = false;
|
||||
} else if (
|
||||
pageText?.toLowerCase().includes('downloading') ||
|
||||
pageText?.toLowerCase().includes('separating') ||
|
||||
pageText?.toLowerCase().includes('transcribing') ||
|
||||
pageText?.toLowerCase().includes('awaiting review') ||
|
||||
pageText?.toLowerCase().includes('select instrumental') ||
|
||||
pageText?.toLowerCase().includes('complete')
|
||||
) {
|
||||
console.log('Job has progressed past audio selection');
|
||||
needsAudioSelection = false;
|
||||
}
|
||||
|
||||
attempts++;
|
||||
}
|
||||
|
||||
await page.screenshot({ path: 'test-results/prod-e2e-03-after-audio.png' });
|
||||
|
||||
// Step 4: Wait for processing and lyrics review
|
||||
console.log('=== Step 3-4: Waiting for processing and review ===');
|
||||
|
||||
// Monitor progress and handle review stage
|
||||
attempts = 0;
|
||||
const maxProcessingAttempts = 120; // 10 minutes of processing
|
||||
let reviewAttempts = 0;
|
||||
const maxReviewAttempts = 3; // Try manual review completion up to 3 times
|
||||
|
||||
while (attempts < maxProcessingAttempts) {
|
||||
await page.click('button:has-text("Refresh")');
|
||||
await page.waitForTimeout(5000);
|
||||
|
||||
const pageText = await page.locator('body').textContent();
|
||||
|
||||
if (pageText?.toLowerCase().includes('select instrumental')) {
|
||||
console.log('Ready for instrumental selection');
|
||||
break;
|
||||
} else if (pageText?.toLowerCase().includes('complete')) {
|
||||
console.log('Job completed!');
|
||||
break;
|
||||
} else if (pageText?.toLowerCase().includes('failed')) {
|
||||
await page.screenshot({ path: 'test-results/prod-e2e-failed.png' });
|
||||
throw new Error('Job failed during processing');
|
||||
} else if (pageText?.toLowerCase().includes('awaiting review') || pageText?.toLowerCase().includes('review lyrics')) {
|
||||
// Job is awaiting review - auto-mode should handle this, but let's verify
|
||||
console.log('Job awaiting review - checking if auto-processing is working...');
|
||||
await page.screenshot({ path: 'test-results/prod-e2e-awaiting-review.png' });
|
||||
|
||||
// Wait a bit for auto-processor to kick in
|
||||
await page.waitForTimeout(10000);
|
||||
await page.click('button:has-text("Refresh")');
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
// Check if still awaiting review
|
||||
const stillAwaiting = await page.locator('body').textContent();
|
||||
if (stillAwaiting?.toLowerCase().includes('awaiting review') && reviewAttempts < maxReviewAttempts) {
|
||||
console.log(`Auto-processing not completing review. Attempting manual completion (attempt ${reviewAttempts + 1}/${maxReviewAttempts})...`);
|
||||
|
||||
// Find the job card and try to get the job ID
|
||||
const jobCard = page.locator('[class*="rounded-lg"][class*="border"]').filter({
|
||||
hasText: /awaiting review/i
|
||||
}).first();
|
||||
|
||||
if (await jobCard.isVisible()) {
|
||||
// Click to expand the job
|
||||
await jobCard.click();
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
// Try to find and click "Review Lyrics" button to open review UI
|
||||
const reviewBtn = page.getByRole('button', { name: /review lyrics/i }).or(page.getByRole('link', { name: /review lyrics/i })).first();
|
||||
|
||||
if (await reviewBtn.isVisible()) {
|
||||
console.log('Opening review UI...');
|
||||
|
||||
// The review button opens a new tab with the LyricsTranscriber UI
|
||||
const [popup] = await Promise.all([
|
||||
page.context().waitForEvent('page', { timeout: 15000 }).catch(() => null),
|
||||
reviewBtn.click()
|
||||
]);
|
||||
|
||||
if (popup) {
|
||||
console.log(`Review UI opened: ${popup.url()}`);
|
||||
await popup.waitForLoadState('networkidle', { timeout: 30000 }).catch(() => {});
|
||||
await popup.screenshot({ path: `test-results/prod-e2e-review-ui-${reviewAttempts}.png`, fullPage: true });
|
||||
|
||||
// Wait for the review UI to fully load
|
||||
await popup.waitForTimeout(5000);
|
||||
|
||||
// The review flow: Click "Preview Video" -> Wait -> Click "Complete Review"
|
||||
const previewBtn = popup.locator('button:has-text("Preview Video")').first();
|
||||
|
||||
if (await previewBtn.isVisible({ timeout: 5000 }).catch(() => false)) {
|
||||
console.log('Clicking "Preview Video" button...');
|
||||
await previewBtn.click();
|
||||
await popup.waitForTimeout(10000);
|
||||
|
||||
// Wait for "Complete Review" button to appear
|
||||
let reviewCompleted = false;
|
||||
for (let i = 0; i < 6 && !reviewCompleted; i++) {
|
||||
const completeBtn = popup.locator('button:has-text("Complete Review")').first();
|
||||
if (await completeBtn.isVisible({ timeout: 5000 }).catch(() => false)) {
|
||||
console.log('Clicking "Complete Review" button...');
|
||||
await completeBtn.click();
|
||||
await popup.waitForTimeout(3000);
|
||||
reviewCompleted = true;
|
||||
console.log('Review submitted via UI');
|
||||
} else {
|
||||
console.log(`Waiting for Complete Review... (${i + 1}/6)`);
|
||||
await popup.waitForTimeout(10000);
|
||||
}
|
||||
}
|
||||
|
||||
if (!reviewCompleted) {
|
||||
console.log('Could not complete review via UI');
|
||||
const allButtons = await popup.getByRole('button').allTextContents();
|
||||
console.log(`Available buttons: ${allButtons.filter(b => b.trim()).join(', ')}`);
|
||||
}
|
||||
} else {
|
||||
console.log('Preview Video button not found');
|
||||
}
|
||||
|
||||
await popup.close();
|
||||
} else {
|
||||
// No popup - might have navigated in same page
|
||||
console.log('Review button did not open popup, checking current page...');
|
||||
await page.waitForTimeout(2000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
reviewAttempts++;
|
||||
}
|
||||
}
|
||||
|
||||
// Log current stage
|
||||
const badges = await page.locator('[class*="rounded-lg"][class*="border"]').first().locator('span').allTextContents();
|
||||
console.log(`Current status: ${badges.filter(b => b.trim()).join(', ')}`);
|
||||
|
||||
attempts++;
|
||||
}
|
||||
|
||||
await page.screenshot({ path: 'test-results/prod-e2e-04-after-processing.png' });
|
||||
|
||||
// Step 5: Instrumental selection
|
||||
console.log('=== Step 5: Instrumental selection ===');
|
||||
|
||||
const instrumentalJob = page.locator('[class*="rounded-lg"][class*="border"]').filter({
|
||||
hasText: /select instrumental/i
|
||||
}).first();
|
||||
|
||||
if (await instrumentalJob.isVisible()) {
|
||||
await instrumentalJob.click();
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
const selectBtn = page.getByRole('button', { name: /select instrumental/i }).first();
|
||||
if (await selectBtn.isVisible()) {
|
||||
await selectBtn.click();
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
const dialog = page.locator('[role="dialog"]');
|
||||
if (await dialog.isVisible()) {
|
||||
// Select clean instrumental
|
||||
const cleanBtn = dialog.locator('button:has-text("Clean"), button:has-text("Select")').first();
|
||||
if (await cleanBtn.isVisible()) {
|
||||
console.log('Selecting clean instrumental');
|
||||
await cleanBtn.click();
|
||||
await page.waitForTimeout(3000);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await page.screenshot({ path: 'test-results/prod-e2e-05-after-instrumental.png' });
|
||||
|
||||
// Step 6: Wait for final render and distribution
|
||||
console.log('=== Step 6: Waiting for final render ===');
|
||||
|
||||
attempts = 0;
|
||||
const maxRenderAttempts = 60; // 5 minutes
|
||||
|
||||
while (attempts < maxRenderAttempts) {
|
||||
await page.click('button:has-text("Refresh")');
|
||||
await page.waitForTimeout(5000);
|
||||
|
||||
const pageText = await page.locator('body').textContent();
|
||||
|
||||
if (pageText?.toLowerCase().includes('complete')) {
|
||||
console.log('Job completed!');
|
||||
break;
|
||||
} else if (pageText?.toLowerCase().includes('failed')) {
|
||||
await page.screenshot({ path: 'test-results/prod-e2e-render-failed.png' });
|
||||
throw new Error('Job failed during rendering');
|
||||
}
|
||||
|
||||
const badges = await page.locator('[class*="rounded-lg"][class*="border"]').first().locator('span').allTextContents();
|
||||
console.log(`Render status: ${badges.filter(b => b.trim()).join(', ')}`);
|
||||
|
||||
attempts++;
|
||||
}
|
||||
|
||||
await page.screenshot({ path: 'test-results/prod-e2e-06-final.png', fullPage: true });
|
||||
|
||||
// Step 7: Verify results
|
||||
console.log('=== Step 7: Verifying results ===');
|
||||
|
||||
const completedJob = page.locator('[class*="rounded-lg"][class*="border"]').filter({
|
||||
hasText: /complete/i
|
||||
}).first();
|
||||
|
||||
if (await completedJob.isVisible()) {
|
||||
await completedJob.click();
|
||||
await page.waitForTimeout(2000);
|
||||
await page.screenshot({ path: 'test-results/prod-e2e-07-completed-details.png', fullPage: true });
|
||||
|
||||
// Check for YouTube link
|
||||
const youtubeLink = page.locator('a[href*="youtube.com"], a[href*="youtu.be"]').first();
|
||||
if (await youtubeLink.isVisible()) {
|
||||
const href = await youtubeLink.getAttribute('href');
|
||||
console.log(`SUCCESS: YouTube link found: ${href}`);
|
||||
} else {
|
||||
console.log('WARNING: No YouTube link found');
|
||||
}
|
||||
|
||||
// Check for Dropbox link
|
||||
const dropboxLink = page.locator('a[href*="dropbox.com"]').first();
|
||||
if (await dropboxLink.isVisible()) {
|
||||
const href = await dropboxLink.getAttribute('href');
|
||||
console.log(`SUCCESS: Dropbox link found: ${href}`);
|
||||
} else {
|
||||
console.log('WARNING: No Dropbox link found');
|
||||
}
|
||||
|
||||
// Count download options
|
||||
const downloads = page.locator('a:has-text("Download"), button:has-text("Download"), a:has-text("720p"), a:has-text("4K")');
|
||||
const downloadCount = await downloads.count();
|
||||
console.log(`Downloads available: ${downloadCount}`);
|
||||
|
||||
console.log('=== E2E TEST COMPLETE ===');
|
||||
} else {
|
||||
throw new Error('Job did not complete - check screenshots for debugging');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// API health check - quick sanity test
|
||||
test('Production API health check', async ({ request }) => {
|
||||
const response = await request.get(`${API_URL}/api/health`);
|
||||
expect(response.ok()).toBeTruthy();
|
||||
|
||||
const data = await response.json();
|
||||
console.log('API Health:', data);
|
||||
expect(data.status).toBe('healthy');
|
||||
});
|
||||
+73
-7
@@ -2,6 +2,8 @@
|
||||
* API client for karaoke-gen backend
|
||||
*/
|
||||
|
||||
import type { VideoThemeSummary, VideoThemeDetail, ThemesListResponse, ThemeDetailResponse, ColorOverrides } from './video-themes';
|
||||
|
||||
// In development, use relative URLs to go through Next.js proxy (avoids CORS)
|
||||
// In production (static export), use the full backend URL
|
||||
const API_BASE_URL = typeof window !== 'undefined' && window.location.hostname === 'localhost'
|
||||
@@ -220,13 +222,15 @@ export const api = {
|
||||
enable_txt?: boolean;
|
||||
brand_prefix?: string;
|
||||
enable_youtube_upload?: boolean;
|
||||
theme_id?: string;
|
||||
color_overrides?: ColorOverrides;
|
||||
}
|
||||
): Promise<UploadJobResponse> {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('artist', artist);
|
||||
formData.append('title', title);
|
||||
|
||||
|
||||
if (options?.enable_cdg !== undefined) {
|
||||
formData.append('enable_cdg', String(options.enable_cdg));
|
||||
}
|
||||
@@ -239,13 +243,19 @@ export const api = {
|
||||
if (options?.enable_youtube_upload !== undefined) {
|
||||
formData.append('enable_youtube_upload', String(options.enable_youtube_upload));
|
||||
}
|
||||
|
||||
if (options?.theme_id) {
|
||||
formData.append('theme_id', options.theme_id);
|
||||
}
|
||||
if (options?.color_overrides) {
|
||||
formData.append('color_overrides', JSON.stringify(options.color_overrides));
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_BASE_URL}/api/jobs/upload`, {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
body: formData,
|
||||
});
|
||||
|
||||
|
||||
return handleResponse<UploadJobResponse>(response);
|
||||
},
|
||||
|
||||
@@ -261,6 +271,8 @@ export const api = {
|
||||
enable_txt?: boolean;
|
||||
brand_prefix?: string;
|
||||
enable_youtube_upload?: boolean;
|
||||
theme_id?: string;
|
||||
color_overrides?: ColorOverrides;
|
||||
}
|
||||
): Promise<{ status: string; job_id: string; message: string }> {
|
||||
const body: Record<string, any> = { url };
|
||||
@@ -270,7 +282,9 @@ export const api = {
|
||||
if (options?.enable_txt !== undefined) body.enable_txt = options.enable_txt;
|
||||
if (options?.brand_prefix) body.brand_prefix = options.brand_prefix;
|
||||
if (options?.enable_youtube_upload !== undefined) body.enable_youtube_upload = options.enable_youtube_upload;
|
||||
|
||||
if (options?.theme_id) body.theme_id = options.theme_id;
|
||||
if (options?.color_overrides) body.color_overrides = options.color_overrides;
|
||||
|
||||
const response = await fetch(`${API_BASE_URL}/api/jobs/create-from-url`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -279,7 +293,7 @@ export const api = {
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
@@ -387,6 +401,8 @@ export const api = {
|
||||
enable_txt?: boolean;
|
||||
brand_prefix?: string;
|
||||
enable_youtube_upload?: boolean;
|
||||
theme_id?: string;
|
||||
color_overrides?: ColorOverrides;
|
||||
}
|
||||
): Promise<AudioSearchResponse> {
|
||||
const body: Record<string, any> = { artist, title, auto_download: autoDownload };
|
||||
@@ -394,7 +410,9 @@ export const api = {
|
||||
if (options?.enable_txt !== undefined) body.enable_txt = options.enable_txt;
|
||||
if (options?.brand_prefix) body.brand_prefix = options.brand_prefix;
|
||||
if (options?.enable_youtube_upload !== undefined) body.enable_youtube_upload = options.enable_youtube_upload;
|
||||
|
||||
if (options?.theme_id) body.theme_id = options.theme_id;
|
||||
if (options?.color_overrides) body.color_overrides = options.color_overrides;
|
||||
|
||||
const response = await fetch(`${API_BASE_URL}/api/audio-search/search`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -403,7 +421,7 @@ export const api = {
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
@@ -450,6 +468,54 @@ export const api = {
|
||||
});
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
// ==========================================================================
|
||||
// Theme API endpoints
|
||||
// ==========================================================================
|
||||
|
||||
/**
|
||||
* List all available video themes
|
||||
*/
|
||||
async listThemes(): Promise<VideoThemeSummary[]> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/themes`, {
|
||||
headers: getAuthHeaders()
|
||||
});
|
||||
const data = await handleResponse<ThemesListResponse>(response);
|
||||
return data.themes;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get full details for a specific theme
|
||||
*/
|
||||
async getTheme(themeId: string): Promise<VideoThemeDetail> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/themes/${themeId}`, {
|
||||
headers: getAuthHeaders()
|
||||
});
|
||||
const data = await handleResponse<ThemeDetailResponse>(response);
|
||||
return data.theme;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get preview URL for a theme
|
||||
*/
|
||||
async getThemePreview(themeId: string): Promise<string | null> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/themes/${themeId}/preview`, {
|
||||
headers: getAuthHeaders()
|
||||
});
|
||||
const data = await handleResponse<{ preview_url: string | null }>(response);
|
||||
return data.preview_url;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get YouTube description template for a theme
|
||||
*/
|
||||
async getThemeYoutubeDescription(themeId: string): Promise<string | null> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/themes/${themeId}/youtube-description`, {
|
||||
headers: getAuthHeaders()
|
||||
});
|
||||
const data = await handleResponse<{ description: string | null }>(response);
|
||||
return data.description;
|
||||
},
|
||||
};
|
||||
|
||||
export { ApiError };
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* Video theme types and utilities for karaoke video styles.
|
||||
*
|
||||
* These are pre-made style configurations stored in GCS that control
|
||||
* the visual appearance of generated karaoke videos.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Summary of a theme for listing in the theme selector.
|
||||
*/
|
||||
export interface VideoThemeSummary {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
preview_url: string | null;
|
||||
thumbnail_url: string | null;
|
||||
is_default: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Full theme details including style parameters.
|
||||
*/
|
||||
export interface VideoThemeDetail {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
preview_url: string | null;
|
||||
is_default: boolean;
|
||||
style_params: Record<string, any>;
|
||||
has_youtube_description: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Response from GET /api/themes
|
||||
*/
|
||||
export interface ThemesListResponse {
|
||||
themes: VideoThemeSummary[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Response from GET /api/themes/{theme_id}
|
||||
*/
|
||||
export interface ThemeDetailResponse {
|
||||
theme: VideoThemeDetail;
|
||||
}
|
||||
|
||||
/**
|
||||
* User color overrides for customizing a theme.
|
||||
* All colors are hex format (#RRGGBB).
|
||||
*/
|
||||
export interface ColorOverrides {
|
||||
/** Color for artist name on intro/end screens */
|
||||
artist_color?: string;
|
||||
/** Color for song title on intro/end screens */
|
||||
title_color?: string;
|
||||
/** Color for lyrics being sung (highlighted) */
|
||||
sung_lyrics_color?: string;
|
||||
/** Color for lyrics not yet sung */
|
||||
unsung_lyrics_color?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if color overrides has any values set.
|
||||
*/
|
||||
export function hasColorOverrides(overrides?: ColorOverrides): boolean {
|
||||
if (!overrides) return false;
|
||||
return !!(
|
||||
overrides.artist_color ||
|
||||
overrides.title_color ||
|
||||
overrides.sung_lyrics_color ||
|
||||
overrides.unsung_lyrics_color
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get clean color overrides object (only non-null values).
|
||||
*/
|
||||
export function cleanColorOverrides(overrides?: ColorOverrides): ColorOverrides | undefined {
|
||||
if (!overrides) return undefined;
|
||||
|
||||
const clean: ColorOverrides = {};
|
||||
if (overrides.artist_color) clean.artist_color = overrides.artist_color;
|
||||
if (overrides.title_color) clean.title_color = overrides.title_color;
|
||||
if (overrides.sung_lyrics_color) clean.sung_lyrics_color = overrides.sung_lyrics_color;
|
||||
if (overrides.unsung_lyrics_color) clean.unsung_lyrics_color = overrides.unsung_lyrics_color;
|
||||
|
||||
return Object.keys(clean).length > 0 ? clean : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate hex color format.
|
||||
*/
|
||||
export function isValidHexColor(color: string): boolean {
|
||||
return /^#[0-9A-Fa-f]{6}$/.test(color);
|
||||
}
|
||||
|
||||
/**
|
||||
* Default color override values based on common themes.
|
||||
*/
|
||||
export const DEFAULT_COLOR_PRESETS = {
|
||||
nomad: {
|
||||
artist_color: "#ffdf6b",
|
||||
title_color: "#ffffff",
|
||||
sung_lyrics_color: "#7070F7",
|
||||
unsung_lyrics_color: "#ffffff",
|
||||
},
|
||||
classic: {
|
||||
artist_color: "#ffffff",
|
||||
title_color: "#ffffff",
|
||||
sung_lyrics_color: "#00ff00",
|
||||
unsung_lyrics_color: "#ffffff",
|
||||
},
|
||||
} as const;
|
||||
@@ -18,6 +18,9 @@
|
||||
"test:e2e:debug": "playwright test --debug",
|
||||
"test:e2e:headed": "playwright test --headed",
|
||||
"test:e2e:record": "RECORD_FIXTURES=true playwright test",
|
||||
"test:e2e:prod": "playwright test --config=playwright.production.config.ts",
|
||||
"test:e2e:prod:headed": "playwright test --config=playwright.production.config.ts --headed",
|
||||
"test:e2e:prod:debug": "playwright test --config=playwright.production.config.ts --debug",
|
||||
"test:all": "npm run test:unit && npm run test:e2e",
|
||||
"fixtures:review": "npx ts-node e2e/fixtures/review-cli.ts"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { defineConfig, devices } from '@playwright/test';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
|
||||
// Load .env.local file if it exists (for KARAOKE_ACCESS_TOKEN)
|
||||
const envLocalPath = path.join(__dirname, '.env.local');
|
||||
if (fs.existsSync(envLocalPath)) {
|
||||
const envContent = fs.readFileSync(envLocalPath, 'utf-8');
|
||||
for (const line of envContent.split('\n')) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed && !trimmed.startsWith('#')) {
|
||||
const [key, ...valueParts] = trimmed.split('=');
|
||||
const value = valueParts.join('=');
|
||||
if (key && value && !process.env[key]) {
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Playwright configuration for PRODUCTION E2E tests.
|
||||
*
|
||||
* Tests run directly against gen.nomadkaraoke.com (no local dev server).
|
||||
* Used for testing the real production system end-to-end.
|
||||
*
|
||||
* Usage:
|
||||
* npx playwright test --config=playwright.production.config.ts
|
||||
* npm run test:e2e:prod
|
||||
*/
|
||||
export default defineConfig({
|
||||
testDir: './e2e',
|
||||
testMatch: '**/production-*.spec.ts',
|
||||
|
||||
// Run tests sequentially - we're testing real production
|
||||
fullyParallel: false,
|
||||
|
||||
// Fail the build on CI if you accidentally left test.only in the source code
|
||||
forbidOnly: !!process.env.CI,
|
||||
|
||||
// Retry failed tests in production (flakiness can happen)
|
||||
retries: 2,
|
||||
|
||||
// Single worker - we're testing against real production services
|
||||
workers: 1,
|
||||
|
||||
// Reporter to use
|
||||
reporter: [
|
||||
['html', { open: 'never', outputFolder: 'playwright-report-prod' }],
|
||||
['list'],
|
||||
],
|
||||
|
||||
// Shared settings for all tests
|
||||
use: {
|
||||
// Base URL for production
|
||||
baseURL: 'https://gen.nomadkaraoke.com',
|
||||
|
||||
// Collect trace always for debugging production issues
|
||||
trace: 'on',
|
||||
|
||||
// Always capture screenshots
|
||||
screenshot: 'on',
|
||||
|
||||
// Always capture video for production debugging
|
||||
video: 'on',
|
||||
|
||||
// Longer timeout for production API calls
|
||||
actionTimeout: 60000,
|
||||
|
||||
// Log network requests
|
||||
extraHTTPHeaders: {
|
||||
'x-playwright-test': 'production',
|
||||
},
|
||||
},
|
||||
|
||||
// Much longer timeout for production tests (karaoke generation takes time!)
|
||||
timeout: 900000, // 15 minutes per test
|
||||
|
||||
// Expect timeout for assertions
|
||||
expect: {
|
||||
timeout: 60000, // 60 seconds for expects
|
||||
},
|
||||
|
||||
// Configure projects (browsers)
|
||||
projects: [
|
||||
{
|
||||
name: 'chromium',
|
||||
use: { ...devices['Desktop Chrome'] },
|
||||
},
|
||||
],
|
||||
|
||||
// No webServer needed - we're testing production directly
|
||||
});
|
||||
@@ -287,6 +287,87 @@ github_actions_iap_tunnel = gcp.projects.IAMMember(
|
||||
member=github_actions_sa.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
# ==================== Claude Code Automation Service Account ====================
|
||||
# This service account provides long-lived read-only access for Claude Code CLI
|
||||
# to monitor deployments, view logs, and check build status without requiring
|
||||
# frequent OAuth re-authentication.
|
||||
|
||||
claude_automation_sa = serviceaccount.Account(
|
||||
"claude-automation-sa",
|
||||
account_id="claude-automation",
|
||||
display_name="Claude Code Automation",
|
||||
description="Service account for Claude Code CLI with read-only GCP access",
|
||||
)
|
||||
|
||||
# Grant Cloud Run viewer permissions (view services, revisions, status)
|
||||
claude_run_viewer = gcp.projects.IAMMember(
|
||||
"claude-automation-run-viewer",
|
||||
project=project_id,
|
||||
role="roles/run.viewer",
|
||||
member=claude_automation_sa.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
# Grant Logging viewer permissions (read logs)
|
||||
claude_logging_viewer = gcp.projects.IAMMember(
|
||||
"claude-automation-logging-viewer",
|
||||
project=project_id,
|
||||
role="roles/logging.viewer",
|
||||
member=claude_automation_sa.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
# Grant Monitoring viewer permissions (read metrics, dashboards)
|
||||
claude_monitoring_viewer = gcp.projects.IAMMember(
|
||||
"claude-automation-monitoring-viewer",
|
||||
project=project_id,
|
||||
role="roles/monitoring.viewer",
|
||||
member=claude_automation_sa.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
# Grant Cloud Build viewer permissions (view build status, logs)
|
||||
claude_cloudbuild_viewer = gcp.projects.IAMMember(
|
||||
"claude-automation-cloudbuild-viewer",
|
||||
project=project_id,
|
||||
role="roles/cloudbuild.builds.viewer",
|
||||
member=claude_automation_sa.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
# Grant Cloud Trace viewer permissions (view distributed traces)
|
||||
claude_cloudtrace_viewer = gcp.projects.IAMMember(
|
||||
"claude-automation-cloudtrace-viewer",
|
||||
project=project_id,
|
||||
role="roles/cloudtrace.user",
|
||||
member=claude_automation_sa.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
# Grant Cloud Tasks viewer permissions (view queue status)
|
||||
claude_cloudtasks_viewer = gcp.projects.IAMMember(
|
||||
"claude-automation-cloudtasks-viewer",
|
||||
project=project_id,
|
||||
role="roles/cloudtasks.viewer",
|
||||
member=claude_automation_sa.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
# Grant Storage viewer permissions (list buckets, view metadata - not object content)
|
||||
claude_storage_viewer = gcp.projects.IAMMember(
|
||||
"claude-automation-storage-viewer",
|
||||
project=project_id,
|
||||
role="roles/storage.objectViewer",
|
||||
member=claude_automation_sa.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
# Allow users to impersonate this service account
|
||||
# This enables using `gcloud auth application-default login --impersonate-service-account`
|
||||
# for long-lived credentials without downloadable keys
|
||||
claude_automation_impersonation = gcp.serviceaccount.IAMBinding(
|
||||
"claude-automation-impersonation",
|
||||
service_account_id=claude_automation_sa.name,
|
||||
role="roles/iam.serviceAccountTokenCreator",
|
||||
members=[
|
||||
"user:andrew@beveridge.uk",
|
||||
"user:admin@nomadkaraoke.com",
|
||||
],
|
||||
)
|
||||
|
||||
# ==================== Cloud Tasks Queues (Phase 1 Scalability) ====================
|
||||
# These queues provide guaranteed delivery and horizontal scaling for worker tasks.
|
||||
# Workers are triggered via Cloud Tasks instead of BackgroundTasks, ensuring:
|
||||
@@ -552,6 +633,9 @@ pulumi.export("backend_default_url", "https://karaoke-backend-ipzqd2k4yq-uc.a.ru
|
||||
pulumi.export("github_actions_service_account", github_actions_sa.email)
|
||||
pulumi.export("workload_identity_provider", workload_identity_provider.name)
|
||||
|
||||
# Claude Code automation exports
|
||||
pulumi.export("claude_automation_service_account", claude_automation_sa.email)
|
||||
|
||||
# Cloud Tasks queue exports (Phase 1 scalability)
|
||||
pulumi.export("audio_worker_queue", audio_worker_queue.name)
|
||||
pulumi.export("lyrics_worker_queue", lyrics_worker_queue.name)
|
||||
|
||||
@@ -31,6 +31,12 @@ from .video_generator import VideoGenerator
|
||||
from .video_background_processor import VideoBackgroundProcessor
|
||||
from .audio_fetcher import create_audio_fetcher, AudioFetcherError, NoResultsError, UserCancelledError
|
||||
|
||||
# Import lyrics_transcriber components for post-review countdown and video rendering
|
||||
from lyrics_transcriber.output.countdown_processor import CountdownProcessor
|
||||
from lyrics_transcriber.output.generator import OutputGenerator
|
||||
from lyrics_transcriber.types import CorrectionResult
|
||||
from lyrics_transcriber.core.config import OutputConfig as LyricsOutputConfig
|
||||
|
||||
|
||||
class KaraokePrep:
|
||||
def __init__(
|
||||
@@ -692,6 +698,112 @@ class KaraokePrep:
|
||||
|
||||
self.logger.info("=== Parallel Processing Complete ===")
|
||||
|
||||
# === POST-TRANSCRIPTION: Add countdown and render video ===
|
||||
# Since lyrics_processor.py now always defers countdown and video rendering,
|
||||
# we handle it here after human review is complete. This ensures the review UI
|
||||
# shows accurate, unshifted timestamps (same behavior as cloud backend).
|
||||
if processed_track.get("lyrics") and self.render_video:
|
||||
self.logger.info("=== Processing Countdown and Video Rendering ===")
|
||||
|
||||
from .utils import sanitize_filename
|
||||
sanitized_artist = sanitize_filename(self.artist)
|
||||
sanitized_title = sanitize_filename(self.title)
|
||||
lyrics_dir = os.path.join(track_output_dir, "lyrics")
|
||||
|
||||
# Find the corrections JSON file
|
||||
corrections_filename = f"{sanitized_artist} - {sanitized_title} (Lyrics Corrections).json"
|
||||
corrections_filepath = os.path.join(lyrics_dir, corrections_filename)
|
||||
|
||||
if os.path.exists(corrections_filepath):
|
||||
self.logger.info(f"Loading corrections from: {corrections_filepath}")
|
||||
|
||||
with open(corrections_filepath, 'r', encoding='utf-8') as f:
|
||||
corrections_data = json.load(f)
|
||||
|
||||
# Convert to CorrectionResult
|
||||
correction_result = CorrectionResult.from_dict(corrections_data)
|
||||
self.logger.info(f"Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
|
||||
|
||||
# Get the audio file path
|
||||
audio_path = processed_track["input_audio_wav"]
|
||||
|
||||
# Add countdown intro if needed (songs that start within 3 seconds)
|
||||
self.logger.info("Processing countdown intro (if needed)...")
|
||||
cache_dir = os.path.join(track_output_dir, "cache")
|
||||
os.makedirs(cache_dir, exist_ok=True)
|
||||
|
||||
countdown_processor = CountdownProcessor(
|
||||
cache_dir=cache_dir,
|
||||
logger=self.logger,
|
||||
)
|
||||
|
||||
correction_result, audio_path, padding_added, padding_seconds = countdown_processor.process(
|
||||
correction_result=correction_result,
|
||||
audio_filepath=audio_path,
|
||||
)
|
||||
|
||||
# Update processed_track with countdown info
|
||||
processed_track["countdown_padding_added"] = padding_added
|
||||
processed_track["countdown_padding_seconds"] = padding_seconds
|
||||
if padding_added:
|
||||
processed_track["padded_vocals_audio"] = audio_path
|
||||
self.logger.info(
|
||||
f"=== COUNTDOWN PADDING ADDED ===\n"
|
||||
f"Added {padding_seconds}s padding to audio and shifted timestamps.\n"
|
||||
f"Instrumental tracks will be padded after separation to maintain sync."
|
||||
)
|
||||
else:
|
||||
self.logger.info("No countdown needed - song starts after 3 seconds")
|
||||
|
||||
# Save the updated corrections with countdown timestamps
|
||||
updated_corrections_data = correction_result.to_dict()
|
||||
with open(corrections_filepath, 'w', encoding='utf-8') as f:
|
||||
json.dump(updated_corrections_data, f, indent=2)
|
||||
self.logger.info(f"Saved countdown-adjusted corrections to: {corrections_filepath}")
|
||||
|
||||
# Render video with lyrics
|
||||
self.logger.info("Rendering karaoke video with synchronized lyrics...")
|
||||
|
||||
output_config = LyricsOutputConfig(
|
||||
output_dir=lyrics_dir,
|
||||
cache_dir=cache_dir,
|
||||
output_styles_json=self.style_params_json,
|
||||
render_video=True,
|
||||
generate_cdg=False,
|
||||
generate_plain_text=True,
|
||||
generate_lrc=True,
|
||||
video_resolution="4k",
|
||||
subtitle_offset_ms=self.subtitle_offset_ms,
|
||||
)
|
||||
|
||||
output_generator = OutputGenerator(output_config, self.logger)
|
||||
output_prefix = f"{sanitized_artist} - {sanitized_title}"
|
||||
|
||||
outputs = output_generator.generate_outputs(
|
||||
transcription_corrected=correction_result,
|
||||
audio_filepath=audio_path,
|
||||
output_prefix=output_prefix,
|
||||
)
|
||||
|
||||
# Copy video to expected location in parent directory
|
||||
if outputs and outputs.get("video_filepath"):
|
||||
source_video = outputs["video_filepath"]
|
||||
dest_video = os.path.join(track_output_dir, f"{artist_title} (With Vocals).mkv")
|
||||
shutil.copy2(source_video, dest_video)
|
||||
self.logger.info(f"Video rendered successfully: {dest_video}")
|
||||
processed_track["with_vocals_video"] = dest_video
|
||||
|
||||
# Update ASS filepath for video background processing
|
||||
if outputs.get("ass_filepath"):
|
||||
processed_track["ass_filepath"] = outputs["ass_filepath"]
|
||||
else:
|
||||
self.logger.warning("Video rendering did not produce expected output")
|
||||
else:
|
||||
self.logger.warning(f"Corrections file not found: {corrections_filepath}")
|
||||
self.logger.warning("Skipping countdown processing and video rendering")
|
||||
elif not self.render_video:
|
||||
self.logger.info("Video rendering disabled - skipping countdown and video generation")
|
||||
|
||||
# Apply video background if requested and lyrics were processed
|
||||
if self.video_background_processor and processed_track.get("lyrics"):
|
||||
self.logger.info("=== Processing Video Background ===")
|
||||
|
||||
@@ -364,35 +364,20 @@ class LyricsProcessor:
|
||||
self.logger.info(f" rapidapi_key: {env_config.get('rapidapi_key')[:3] + '...' if env_config.get('rapidapi_key') else 'None'}")
|
||||
self.logger.info(f" lyrics_file: {self.lyrics_file}")
|
||||
|
||||
# Detect if we're running in a serverless environment (Modal)
|
||||
# Modal sets specific environment variables we can check for
|
||||
is_serverless = (
|
||||
os.getenv("MODAL_TASK_ID") is not None or
|
||||
os.getenv("MODAL_FUNCTION_NAME") is not None or
|
||||
os.path.exists("/.modal") # Modal creates this directory in containers
|
||||
)
|
||||
|
||||
# In serverless environment, disable interactive review even if skip_transcription_review=False
|
||||
# This preserves CLI behavior while fixing serverless hanging
|
||||
enable_review_setting = not self.skip_transcription_review and not is_serverless
|
||||
|
||||
if is_serverless and not self.skip_transcription_review:
|
||||
self.logger.info("Detected serverless environment - disabling interactive review to prevent hanging")
|
||||
|
||||
# In serverless environment, disable video generation during Phase 1 to save compute
|
||||
# Video will be generated in Phase 2 after human review
|
||||
serverless_render_video = render_video and not is_serverless
|
||||
|
||||
if is_serverless and render_video:
|
||||
self.logger.info("Detected serverless environment - deferring video generation until after review")
|
||||
|
||||
if is_serverless:
|
||||
self.logger.info("Detected serverless environment - deferring countdown processing until after review")
|
||||
# Always defer countdown and video rendering to a later phase.
|
||||
# This ensures the review UI (both local and cloud) shows original timing
|
||||
# without the 3-second countdown shift. The caller is responsible for:
|
||||
# - Local CLI: karaoke_gen.py adds countdown and renders video after transcription
|
||||
# - Cloud backend: render_video_worker.py adds countdown and renders video
|
||||
#
|
||||
# This design ensures consistent behavior regardless of environment,
|
||||
# and the review UI always shows accurate, unshifted timestamps.
|
||||
self.logger.info("Deferring countdown and video rendering to post-review phase")
|
||||
|
||||
output_config = OutputConfig(
|
||||
output_styles_json=self.style_params_json,
|
||||
output_dir=lyrics_dir,
|
||||
render_video=serverless_render_video, # Disable video in serverless Phase 1
|
||||
render_video=False, # Always defer - caller handles video rendering after countdown
|
||||
fetch_lyrics=True,
|
||||
run_transcription=not self.skip_transcription,
|
||||
run_correction=True,
|
||||
@@ -400,9 +385,9 @@ class LyricsProcessor:
|
||||
generate_lrc=True,
|
||||
generate_cdg=False, # CDG generation disabled (not currently supported)
|
||||
video_resolution="4k",
|
||||
enable_review=enable_review_setting,
|
||||
enable_review=not self.skip_transcription_review, # Honor the caller's setting
|
||||
subtitle_offset_ms=self.subtitle_offset_ms,
|
||||
add_countdown=not is_serverless, # Defer countdown to Phase 2 (render_video_worker)
|
||||
add_countdown=False, # Always defer - caller handles countdown after review
|
||||
)
|
||||
|
||||
# Add this log entry to debug the OutputConfig
|
||||
|
||||
@@ -242,9 +242,17 @@ def create_parser(prog: str = "karaoke-gen") -> argparse.ArgumentParser:
|
||||
|
||||
# Style Configuration
|
||||
style_group = parser.add_argument_group("Style Configuration")
|
||||
style_group.add_argument(
|
||||
"--theme",
|
||||
help="Optional: Theme ID for pre-made styles stored in GCS (e.g., 'nomad', 'default'). "
|
||||
"When using a theme, CDG/TXT are enabled by default. "
|
||||
"Example: --theme=nomad",
|
||||
)
|
||||
style_group.add_argument(
|
||||
"--style_params_json",
|
||||
help="Optional: Path to JSON file containing style configuration. Example: --style_params_json='/path/to/style_params.json'",
|
||||
help="Optional: Path to JSON file containing style configuration. "
|
||||
"Takes precedence over --theme if both are provided. "
|
||||
"Example: --style_params_json='/path/to/style_params.json'",
|
||||
)
|
||||
style_group.add_argument(
|
||||
"--style_override",
|
||||
|
||||
@@ -292,6 +292,8 @@ class RemoteKaraokeClient:
|
||||
# Two-phase workflow (Batch 6)
|
||||
prep_only: bool = False,
|
||||
keep_brand_code: Optional[str] = None,
|
||||
# Theme system
|
||||
theme_id: Optional[str] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Submit a new karaoke generation job from a YouTube/online URL.
|
||||
@@ -322,6 +324,7 @@ class RemoteKaraokeClient:
|
||||
clean_instrumental_model: Model for clean instrumental separation
|
||||
backing_vocals_models: List of models for backing vocals separation
|
||||
other_stems_models: List of models for other stems (bass, drums, etc.)
|
||||
theme_id: Theme ID from GCS themes (e.g., 'nomad', 'default')
|
||||
"""
|
||||
self.logger.info(f"Submitting URL-based job: {url}")
|
||||
|
||||
@@ -367,7 +370,10 @@ class RemoteKaraokeClient:
|
||||
create_request['prep_only'] = prep_only
|
||||
if keep_brand_code:
|
||||
create_request['keep_brand_code'] = keep_brand_code
|
||||
|
||||
# Theme system
|
||||
if theme_id:
|
||||
create_request['theme_id'] = theme_id
|
||||
|
||||
self.logger.info(f"Creating URL-based job at {self.config.service_url}/api/jobs/create-from-url")
|
||||
|
||||
response = self._request('POST', '/api/jobs/create-from-url', json=create_request)
|
||||
@@ -396,9 +402,9 @@ class RemoteKaraokeClient:
|
||||
return result
|
||||
|
||||
def submit_job(
|
||||
self,
|
||||
filepath: str,
|
||||
artist: str,
|
||||
self,
|
||||
filepath: str,
|
||||
artist: str,
|
||||
title: str,
|
||||
style_params_path: Optional[str] = None,
|
||||
enable_cdg: bool = True,
|
||||
@@ -425,6 +431,8 @@ class RemoteKaraokeClient:
|
||||
# Two-phase workflow (Batch 6)
|
||||
prep_only: bool = False,
|
||||
keep_brand_code: Optional[str] = None,
|
||||
# Theme system
|
||||
theme_id: Optional[str] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Submit a new karaoke generation job with optional style configuration.
|
||||
@@ -456,6 +464,7 @@ class RemoteKaraokeClient:
|
||||
backing_vocals_models: List of models for backing vocals separation
|
||||
other_stems_models: List of models for other stems (bass, drums, etc.)
|
||||
existing_instrumental: Path to existing instrumental file to use instead of AI separation
|
||||
theme_id: Theme ID from GCS themes (e.g., 'nomad', 'default')
|
||||
"""
|
||||
file_path = Path(filepath)
|
||||
|
||||
@@ -574,7 +583,10 @@ class RemoteKaraokeClient:
|
||||
create_request['prep_only'] = prep_only
|
||||
if keep_brand_code:
|
||||
create_request['keep_brand_code'] = keep_brand_code
|
||||
|
||||
# Theme system
|
||||
if theme_id:
|
||||
create_request['theme_id'] = theme_id
|
||||
|
||||
response = self._request('POST', '/api/jobs/create-with-upload-urls', json=create_request)
|
||||
|
||||
if response.status_code != 200:
|
||||
@@ -1195,6 +1207,8 @@ class RemoteKaraokeClient:
|
||||
clean_instrumental_model: Optional[str] = None,
|
||||
backing_vocals_models: Optional[list] = None,
|
||||
other_stems_models: Optional[list] = None,
|
||||
# Theme system
|
||||
theme_id: Optional[str] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Search for audio by artist and title (Batch 5 - Flacfetch integration).
|
||||
@@ -1247,7 +1261,10 @@ class RemoteKaraokeClient:
|
||||
request_data['backing_vocals_models'] = backing_vocals_models
|
||||
if other_stems_models:
|
||||
request_data['other_stems_models'] = other_stems_models
|
||||
|
||||
# Theme system
|
||||
if theme_id:
|
||||
request_data['theme_id'] = theme_id
|
||||
|
||||
# Prepare style files for upload if provided
|
||||
style_files = []
|
||||
local_style_files: Dict[str, str] = {} # file_type -> local_path
|
||||
@@ -3029,6 +3046,8 @@ def main():
|
||||
logger.info(f"Searching for: {artist} - {title}")
|
||||
if getattr(args, 'auto_download', False) or config.non_interactive:
|
||||
logger.info(f"Auto-download: enabled (will auto-select best source)")
|
||||
if getattr(args, 'theme', None):
|
||||
logger.info(f"Theme: {args.theme}")
|
||||
if args.style_params_json:
|
||||
logger.info(f"Style: {args.style_params_json}")
|
||||
logger.info(f"CDG: {args.enable_cdg}, TXT: {args.enable_txt}")
|
||||
@@ -3070,6 +3089,8 @@ def main():
|
||||
clean_instrumental_model=getattr(args, 'clean_instrumental_model', None),
|
||||
backing_vocals_models=getattr(args, 'backing_vocals_models', None),
|
||||
other_stems_models=getattr(args, 'other_stems_models', None),
|
||||
# Theme system
|
||||
theme_id=getattr(args, 'theme', None),
|
||||
)
|
||||
|
||||
job_id = result.get('job_id')
|
||||
@@ -3106,6 +3127,8 @@ def main():
|
||||
logger.info(f"Title: {title}")
|
||||
if not artist and not title and is_url_input:
|
||||
logger.info(f"Artist/Title: (will be auto-detected from URL)")
|
||||
if getattr(args, 'theme', None):
|
||||
logger.info(f"Theme: {args.theme}")
|
||||
if args.style_params_json:
|
||||
logger.info(f"Style: {args.style_params_json}")
|
||||
logger.info(f"CDG: {args.enable_cdg}, TXT: {args.enable_txt}")
|
||||
@@ -3206,6 +3229,8 @@ def main():
|
||||
# Two-phase workflow (Batch 6)
|
||||
prep_only=getattr(args, 'prep_only', False),
|
||||
keep_brand_code=keep_brand_code_value,
|
||||
# Theme system
|
||||
theme_id=getattr(args, 'theme', None),
|
||||
)
|
||||
else:
|
||||
# File-based job submission
|
||||
@@ -3238,6 +3263,8 @@ def main():
|
||||
# Two-phase workflow (Batch 6)
|
||||
prep_only=getattr(args, 'prep_only', False),
|
||||
keep_brand_code=keep_brand_code_value,
|
||||
# Theme system
|
||||
theme_id=getattr(args, 'theme', None),
|
||||
)
|
||||
job_id = result.get('job_id')
|
||||
style_assets = result.get('style_assets_uploaded', [])
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.76.2"
|
||||
version = "0.76.10"
|
||||
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"
|
||||
|
||||
Executable
+367
@@ -0,0 +1,367 @@
|
||||
#!/bin/bash
|
||||
# Upload a theme to GCS
|
||||
# Usage: BRANDING_DIR=/path/to/NomadBranding ./upload-theme.sh [theme_id]
|
||||
|
||||
set -e
|
||||
|
||||
THEME_ID="${1:-nomad}"
|
||||
BUCKET="karaoke-gen-storage-nomadkaraoke"
|
||||
THEMES_PATH="themes"
|
||||
|
||||
# BRANDING_DIR must be set via environment variable
|
||||
BRANDING_DIR="${BRANDING_DIR:-}"
|
||||
|
||||
if [ -z "$BRANDING_DIR" ]; then
|
||||
echo "Error: BRANDING_DIR environment variable must be set"
|
||||
echo "Example: export BRANDING_DIR=/path/to/NomadBranding"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ ! -d "$BRANDING_DIR" ]; then
|
||||
echo "Error: BRANDING_DIR does not exist: $BRANDING_DIR"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "=== Uploading theme: $THEME_ID to gs://$BUCKET/$THEMES_PATH/ ==="
|
||||
echo "Using branding assets from: $BRANDING_DIR"
|
||||
|
||||
# Create temporary directory for processing
|
||||
TEMP_DIR=$(mktemp -d)
|
||||
trap 'rm -rf "$TEMP_DIR"' EXIT
|
||||
|
||||
# Function to upload the Nomad theme
|
||||
upload_nomad_theme() {
|
||||
echo ""
|
||||
echo "=== Setting up Nomad theme ==="
|
||||
|
||||
THEME_PATH="$THEMES_PATH/nomad"
|
||||
|
||||
# Create style_params.json with GCS paths
|
||||
cat > "$TEMP_DIR/style_params.json" << 'EOF'
|
||||
{
|
||||
"intro": {
|
||||
"video_duration": 5,
|
||||
"existing_image": null,
|
||||
"background_color": "#000000",
|
||||
"background_image": "karaoke-title-screen-background-nomad-4k.png",
|
||||
"font": "AvenirNext-Bold.ttf",
|
||||
"artist_color": "#ffdf6b",
|
||||
"artist_text_transform": "uppercase",
|
||||
"title_color": "#ffffff",
|
||||
"title_gradient": null,
|
||||
"title_text_transform": "uppercase",
|
||||
"title_region": "370,980,3100,350",
|
||||
"artist_region": "370,1400,3100,450",
|
||||
"artist_gradient": null,
|
||||
"extra_text": null,
|
||||
"extra_text_color": "#ffffff",
|
||||
"extra_text_gradient": null,
|
||||
"extra_text_region": null,
|
||||
"extra_text_text_transform": "uppercase"
|
||||
},
|
||||
"karaoke": {
|
||||
"background_image": "karaoke-background-image-nomad-4k.png",
|
||||
"background_color": "#000000",
|
||||
"font_path": "AvenirNext-Bold.ttf",
|
||||
"font": "Avenir Next Bold",
|
||||
"ass_name": "Nomad",
|
||||
"primary_color": "112, 112, 247, 255",
|
||||
"secondary_color": "255, 255, 255, 255",
|
||||
"outline_color": "26, 58, 235, 255",
|
||||
"back_color": "0, 255, 0, 255",
|
||||
"bold": false,
|
||||
"italic": false,
|
||||
"underline": false,
|
||||
"strike_out": false,
|
||||
"scale_x": 100,
|
||||
"scale_y": 100,
|
||||
"spacing": 0,
|
||||
"angle": 0.0,
|
||||
"border_style": 1,
|
||||
"outline": 1,
|
||||
"shadow": 0,
|
||||
"margin_l": 0,
|
||||
"margin_r": 0,
|
||||
"margin_v": 0,
|
||||
"encoding": 0
|
||||
},
|
||||
"end": {
|
||||
"video_duration": 5,
|
||||
"existing_image": null,
|
||||
"background_color": "#000000",
|
||||
"background_image": "karaoke-background-image-nomad-4k.png",
|
||||
"font": "AvenirNext-Bold.ttf",
|
||||
"artist_color": "#ffdf6b",
|
||||
"artist_text_transform": "uppercase",
|
||||
"title_color": "#ffffff",
|
||||
"title_gradient": null,
|
||||
"title_text_transform": "uppercase",
|
||||
"title_region": "370,900,3100,350",
|
||||
"artist_region": "370,1450,3100,200",
|
||||
"artist_gradient": null,
|
||||
"extra_text": "THANK YOU FOR SINGING!",
|
||||
"extra_text_color": "#ff7acc",
|
||||
"extra_text_region": "370,400,3100,400",
|
||||
"extra_text_text_transform": "uppercase",
|
||||
"extra_text_gradient": null
|
||||
},
|
||||
"cdg": {
|
||||
"clear_mode": "eager",
|
||||
"sync_offset": 0,
|
||||
"lead_in_threshold": 300,
|
||||
"lead_in_duration": 30,
|
||||
"lead_in_total": 200,
|
||||
"lead_in_symbols": ["/>", ">", ">", ">"],
|
||||
"row": 4,
|
||||
"line_tile_height": 3,
|
||||
"lines_per_page": 4,
|
||||
"title_color": "#ffffff",
|
||||
"artist_color": "#ffdf6b",
|
||||
"background_color": "#111427",
|
||||
"border_color": "#111427",
|
||||
"active_fill": "#7070F7",
|
||||
"active_stroke": "#000000",
|
||||
"inactive_fill": "#ff7acc",
|
||||
"inactive_stroke": "#000000",
|
||||
"instrumental_font_color": "#ffdf6b",
|
||||
"font_path": "AvenirNext-Bold.ttf",
|
||||
"font_size": 18,
|
||||
"stroke_width": 0,
|
||||
"stroke_style": "octagon",
|
||||
"instrumental_gap_threshold": 1500,
|
||||
"instrumental_text": "INSTRUMENTAL",
|
||||
"instrumental_background": "cdg-instrumental-background-nomad-notes.png",
|
||||
"instrumental_transition": "topleftmusicalnotes",
|
||||
"title_screen_background": "cdg-title-screen-background-nomad-simple.png",
|
||||
"title_screen_transition": "largecentertexttoplogo",
|
||||
"title_artist_gap": 10,
|
||||
"intro_duration_seconds": 5.0,
|
||||
"first_syllable_buffer_seconds": 3.0,
|
||||
"outro_background": "cdg-title-screen-background-nomad-simple.png",
|
||||
"outro_transition": "largecentertexttoplogo",
|
||||
"outro_text_line1": "THANK YOU FOR SINGING!",
|
||||
"outro_text_line2": "nomadkaraoke.com",
|
||||
"outro_line1_color": "#ffffff",
|
||||
"outro_line2_color": "#ffdf6b",
|
||||
"outro_line1_line2_gap": 30
|
||||
}
|
||||
}
|
||||
EOF
|
||||
|
||||
echo "Uploading style_params.json..."
|
||||
gsutil cp "$TEMP_DIR/style_params.json" "gs://$BUCKET/$THEME_PATH/style_params.json"
|
||||
|
||||
# Validate all required branding files exist before uploading
|
||||
echo "Validating required branding files..."
|
||||
REQUIRED_FILES=(
|
||||
"$BRANDING_DIR/youtube-video-description.txt"
|
||||
"$BRANDING_DIR/AvenirNext-Bold.ttf"
|
||||
"$BRANDING_DIR/karaoke-title-screen-background-nomad-4k.png"
|
||||
"$BRANDING_DIR/karaoke-background-image-nomad-4k.png"
|
||||
"$BRANDING_DIR/cdg-instrumental-background-nomad-notes.png"
|
||||
"$BRANDING_DIR/cdg-title-screen-background-nomad-simple.png"
|
||||
)
|
||||
|
||||
for file in "${REQUIRED_FILES[@]}"; do
|
||||
if [ ! -f "$file" ]; then
|
||||
echo "Error: Required file not found: $file"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
echo "All required files found."
|
||||
|
||||
echo "Uploading youtube_description.txt..."
|
||||
gsutil cp "$BRANDING_DIR/youtube-video-description.txt" "gs://$BUCKET/$THEME_PATH/youtube_description.txt"
|
||||
|
||||
echo "Uploading assets..."
|
||||
# Font
|
||||
gsutil cp "$BRANDING_DIR/AvenirNext-Bold.ttf" "gs://$BUCKET/$THEME_PATH/assets/AvenirNext-Bold.ttf"
|
||||
|
||||
# Background images
|
||||
gsutil cp "$BRANDING_DIR/karaoke-title-screen-background-nomad-4k.png" "gs://$BUCKET/$THEME_PATH/assets/karaoke-title-screen-background-nomad-4k.png"
|
||||
gsutil cp "$BRANDING_DIR/karaoke-background-image-nomad-4k.png" "gs://$BUCKET/$THEME_PATH/assets/karaoke-background-image-nomad-4k.png"
|
||||
|
||||
# CDG assets
|
||||
gsutil cp "$BRANDING_DIR/cdg-instrumental-background-nomad-notes.png" "gs://$BUCKET/$THEME_PATH/assets/cdg-instrumental-background-nomad-notes.png"
|
||||
gsutil cp "$BRANDING_DIR/cdg-title-screen-background-nomad-simple.png" "gs://$BUCKET/$THEME_PATH/assets/cdg-title-screen-background-nomad-simple.png"
|
||||
|
||||
# Create preview image (use an existing image as preview for now)
|
||||
echo "Uploading preview image..."
|
||||
gsutil cp "$BRANDING_DIR/karaoke-background-image-nomad-4k.png" "gs://$BUCKET/$THEME_PATH/preview.png"
|
||||
|
||||
echo "Nomad theme uploaded successfully!"
|
||||
}
|
||||
|
||||
# Function to upload the default theme (simple black background)
|
||||
upload_default_theme() {
|
||||
echo ""
|
||||
echo "=== Setting up Default theme ==="
|
||||
|
||||
THEME_PATH="$THEMES_PATH/default"
|
||||
|
||||
# Create a simple default style_params.json (no custom assets)
|
||||
cat > "$TEMP_DIR/default_style_params.json" << 'EOF'
|
||||
{
|
||||
"intro": {
|
||||
"video_duration": 5,
|
||||
"existing_image": null,
|
||||
"background_color": "#000000",
|
||||
"background_image": null,
|
||||
"font": null,
|
||||
"artist_color": "#ffffff",
|
||||
"artist_text_transform": "uppercase",
|
||||
"title_color": "#ffffff",
|
||||
"title_gradient": null,
|
||||
"title_text_transform": "uppercase",
|
||||
"title_region": "370,980,3100,350",
|
||||
"artist_region": "370,1400,3100,450"
|
||||
},
|
||||
"karaoke": {
|
||||
"background_image": null,
|
||||
"background_color": "#000000",
|
||||
"font_path": null,
|
||||
"font": null,
|
||||
"ass_name": "Default",
|
||||
"primary_color": "0, 255, 0, 255",
|
||||
"secondary_color": "255, 255, 255, 255",
|
||||
"outline_color": "0, 0, 0, 255",
|
||||
"back_color": "0, 0, 0, 255",
|
||||
"bold": false,
|
||||
"italic": false,
|
||||
"underline": false,
|
||||
"strike_out": false,
|
||||
"scale_x": 100,
|
||||
"scale_y": 100,
|
||||
"spacing": 0,
|
||||
"angle": 0.0,
|
||||
"border_style": 1,
|
||||
"outline": 2,
|
||||
"shadow": 0,
|
||||
"margin_l": 0,
|
||||
"margin_r": 0,
|
||||
"margin_v": 0,
|
||||
"encoding": 0
|
||||
},
|
||||
"end": {
|
||||
"video_duration": 5,
|
||||
"existing_image": null,
|
||||
"background_color": "#000000",
|
||||
"background_image": null,
|
||||
"font": null,
|
||||
"artist_color": "#ffffff",
|
||||
"artist_text_transform": "uppercase",
|
||||
"title_color": "#ffffff",
|
||||
"title_gradient": null,
|
||||
"title_text_transform": "uppercase",
|
||||
"title_region": "370,900,3100,350",
|
||||
"artist_region": "370,1450,3100,200",
|
||||
"extra_text": null
|
||||
},
|
||||
"cdg": {
|
||||
"clear_mode": "eager",
|
||||
"sync_offset": 0,
|
||||
"lead_in_threshold": 300,
|
||||
"lead_in_duration": 30,
|
||||
"lead_in_total": 200,
|
||||
"lead_in_symbols": ["/>", ">", ">", ">"],
|
||||
"row": 4,
|
||||
"line_tile_height": 3,
|
||||
"lines_per_page": 4,
|
||||
"title_color": "#ffffff",
|
||||
"artist_color": "#ffffff",
|
||||
"background_color": "#000000",
|
||||
"border_color": "#000000",
|
||||
"active_fill": "#00ff00",
|
||||
"active_stroke": "#000000",
|
||||
"inactive_fill": "#ffffff",
|
||||
"inactive_stroke": "#000000",
|
||||
"instrumental_font_color": "#ffff00",
|
||||
"font_path": null,
|
||||
"font_size": 18,
|
||||
"stroke_width": 1,
|
||||
"stroke_style": "octagon",
|
||||
"instrumental_gap_threshold": 1500,
|
||||
"instrumental_text": "INSTRUMENTAL",
|
||||
"instrumental_background": null,
|
||||
"instrumental_transition": "default",
|
||||
"title_screen_background": null,
|
||||
"title_screen_transition": "default",
|
||||
"title_artist_gap": 10,
|
||||
"intro_duration_seconds": 5.0,
|
||||
"first_syllable_buffer_seconds": 3.0,
|
||||
"outro_background": null,
|
||||
"outro_transition": "default",
|
||||
"outro_text_line1": "THANK YOU FOR SINGING!",
|
||||
"outro_text_line2": "",
|
||||
"outro_line1_color": "#ffffff",
|
||||
"outro_line2_color": "#ffffff",
|
||||
"outro_line1_line2_gap": 30
|
||||
}
|
||||
}
|
||||
EOF
|
||||
|
||||
echo "Uploading default style_params.json..."
|
||||
gsutil cp "$TEMP_DIR/default_style_params.json" "gs://$BUCKET/$THEME_PATH/style_params.json"
|
||||
|
||||
echo "Default theme uploaded successfully!"
|
||||
}
|
||||
|
||||
# Function to create/update the theme metadata
|
||||
create_metadata() {
|
||||
echo ""
|
||||
echo "=== Creating theme metadata ==="
|
||||
|
||||
cat > "$TEMP_DIR/_metadata.json" << 'EOF'
|
||||
{
|
||||
"version": 1,
|
||||
"themes": [
|
||||
{
|
||||
"id": "nomad",
|
||||
"name": "Nomad Karaoke",
|
||||
"description": "Professional karaoke style with golden artist text, purple sung lyrics, and beautiful backgrounds",
|
||||
"is_default": true
|
||||
},
|
||||
{
|
||||
"id": "default",
|
||||
"name": "Classic",
|
||||
"description": "Simple black background with white text and green highlighted lyrics",
|
||||
"is_default": false
|
||||
}
|
||||
]
|
||||
}
|
||||
EOF
|
||||
|
||||
echo "Uploading _metadata.json..."
|
||||
gsutil cp "$TEMP_DIR/_metadata.json" "gs://$BUCKET/$THEMES_PATH/_metadata.json"
|
||||
|
||||
echo "Metadata created successfully!"
|
||||
}
|
||||
|
||||
# Main execution
|
||||
case "$THEME_ID" in
|
||||
"nomad")
|
||||
upload_nomad_theme
|
||||
create_metadata
|
||||
;;
|
||||
"default")
|
||||
upload_default_theme
|
||||
create_metadata
|
||||
;;
|
||||
"all")
|
||||
upload_nomad_theme
|
||||
upload_default_theme
|
||||
create_metadata
|
||||
;;
|
||||
"metadata")
|
||||
create_metadata
|
||||
;;
|
||||
*)
|
||||
echo "Unknown theme: $THEME_ID"
|
||||
echo "Usage: $0 [nomad|default|all|metadata]"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
echo ""
|
||||
echo "=== Theme upload complete! ==="
|
||||
echo "Verify with: gsutil ls -r gs://$BUCKET/$THEMES_PATH/"
|
||||
Reference in new issue
Block a user