Compare commits

..
Author SHA1 Message Date
Andrew BeveridgeandClaude Opus 4.5 2614a2c14c Address CodeRabbit review feedback
- Add thread-safe singleton initialization for ThemeService using double-checked locking
- Make BRANDING_DIR configurable via environment variable in upload-theme.sh
- Fix trap command quoting (use single quotes for deferred expansion)
- Add validation for required branding files before upload

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 17:51:43 -05:00
Andrew BeveridgeandClaude Opus 4.5 80115b7e34 Add theme system for pre-made video styles
- Backend: Add theme models, service, and API routes for theme selection
- Backend: Update job creation to accept theme_id and color_overrides
- Backend: Enable CDG/TXT by default when theme is selected
- Frontend: Add ThemeSelector and ColorOverridesPanel components
- Frontend: Integrate theme selection into JobSubmission form
- CLI: Add --theme argument for remote CLI
- Upload Nomad theme to GCS at themes/nomad/

Themes are stored in GCS and include style params, assets, YouTube
description templates, and preview images. Users can select a theme
and optionally override colors (artist, title, sung/unsung lyrics).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 15:17:48 -05:00
Andrew BeveridgeandClaude Opus 4.5 cdae92d0b7 Fix review-data endpoint to use fallback audio sources
The endpoint required file_urls.lyrics.audio which was never set by
the lyrics worker. Now falls back to:
1. stems.lead_vocals (best for reviewing lyrics sync)
2. input_media_gcs_path (original audio)

This fixes jobs getting stuck in awaiting_review status with
"Review data not available" error.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 13:47:52 -05:00
Andrew BeveridgeandClaude Opus 4.5 6e3cf007d2 Add Claude automation service account for long-lived GCP access
- Create claude-automation SA with read-only GCP permissions:
  - run.viewer, logging.viewer, monitoring.viewer
  - cloudbuild.builds.viewer, cloudtrace.user
  - cloudtasks.viewer, storage.objectViewer
- Enable impersonation for andrew@beveridge.uk and admin@nomadkaraoke.com
- Add playwright-report-prod to gitignore

This allows Claude Code CLI to monitor deployments, view logs, and
check build status without requiring frequent OAuth re-authentication.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 13:29:33 -05:00
Andrew BeveridgeandClaude Opus 4.5 bf6f3ba78b Fix CDG/TXT generation failing for jobs without custom styles
Changed enable_cdg and enable_txt defaults from true to false since
CDG/TXT generation requires a complete style configuration with 35+
parameters. Jobs created without custom styles would fail at the
video generation stage with "Missing required style parameters".

Also updated E2E tests to properly interact with the lyrics review UI:
- Click "Preview Video" button to trigger preview generation
- Wait for "Complete Review" button to appear
- Submit the review to advance the job to instrumental selection

Changes:
- backend/models/job.py: Default enable_cdg/enable_txt to False
- backend/models/requests.py: Same
- backend/api/routes/file_upload.py: Same
- backend/api/routes/audio_search.py: Same
- backend/tests: Updated tests expecting new defaults
- frontend/e2e: Improved review UI interaction in E2E tests
- pyproject.toml: Bump version to 0.76.6

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 11:52:04 -05:00
Andrew Beveridge ☄️andClaude Opus 4.5 d1a5892793 Enable YouTube upload by default for web service jobs (#66)
Root cause: Jobs created via the web UI were missing youtube_description_template
field, which caused the video_worker to skip YouTube upload even when credentials
were configured.

Changes:
- Add default_enable_youtube_upload, default_brand_prefix, default_youtube_description
  settings to backend/config.py
- Apply defaults in audio_search.py when creating jobs
- Add DEFAULT_ENABLE_YOUTUBE_UPLOAD=true and DEFAULT_BRAND_PREFIX=NOMAD env vars
  to cloudbuild.yaml for production deployment

This ensures web service jobs will automatically upload to YouTube and use the
NOMAD brand prefix without requiring explicit request parameters.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 10:39:53 -05:00
Andrew Beveridge ☄️ 4a7b616dde Merge pull request #65 from nomadkaraoke/fix/e2e-test-strict-mode-violations
Fix E2E tests for production - strict mode violations
2025-12-27 09:13:44 -05:00
Andrew Beveridge ☄️andcoderabbitai[bot] e40a122841 Update frontend/e2e/production-full-journey.spec.ts
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-12-27 09:12:51 -05:00
Andrew BeveridgeandClaude Opus 4.5 251d3fa971 Fix E2E tests for production - strict mode violations
Fixed Playwright strict mode violations in production E2E tests where
multiple elements matched locators. Added .first() to selectors for
Review Lyrics and Select Instrumental buttons when multiple jobs
exist in the queue.

Test results: 8/8 tests passing including full E2E journey.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 04:55:42 -05:00
Andrew Beveridge ☄️ a24060c4d2 Merge pull request #64 from nomadkaraoke/refactor/defer-countdown-always
Refactor: Always defer countdown to post-review phase
2025-12-27 04:05:29 -05:00
Andrew Beveridge 2ab0f0dea3 Added agent instructions for current goal 2025-12-27 04:04:47 -05:00
Andrew Beveridge 41df208e5d Merge main into refactor/defer-countdown-always 2025-12-27 03:57:44 -05:00
Andrew Beveridge ☄️ 7ffb219b9f Merge pull request #63 from nomadkaraoke/feature/retry-cancelled-jobs
feat: Allow retrying cancelled jobs
2025-12-27 03:56:29 -05:00
Andrew BeveridgeandClaude Opus 4.5 f740c68f4b Refactor: Always defer countdown to post-review phase
This removes the is_serverless environment detection from lyrics_processor.py
and makes both local CLI and cloud backend follow the same pattern:
1. Transcription (no countdown) - timestamps match original audio
2. Human review - UI shows accurate, unshifted timestamps
3. Add countdown (if song starts within 3s)
4. Render video

Previously, the serverless detection only checked for Modal environment
variables (MODAL_TASK_ID, MODAL_FUNCTION_NAME, /.modal), missing Cloud Run
(K_SERVICE). This caused the review UI to show shifted timestamps when
running on Cloud Run.

Instead of adding more environment detection, this refactor ensures
consistent behavior regardless of environment:

- lyrics_processor.py: Always sets add_countdown=False and render_video=False
- karaoke_gen.py: Added post-transcription section that loads corrections,
  processes countdown via CountdownProcessor, and renders video via
  OutputGenerator

This aligns with the architectural goals in BACKEND-FEATURE-PARITY-PLAN.md
to share more code between local and cloud paths.

Fixes: Lyrics review UI showing countdown-shifted timestamps on Cloud Run

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 03:52:04 -05:00
Andrew BeveridgeandClaude Opus 4.5 14c0abd40f feat: Allow retrying cancelled jobs
- Add CANCELLED to state transitions allowing retry to DOWNLOADING,
  INSTRUMENTAL_SELECTED, REVIEW_COMPLETE, and LYRICS_COMPLETE
- Add DOWNLOADING to FAILED transitions for restart from beginning
- Update retry endpoint to accept both FAILED and CANCELLED jobs
- Add new retry path that restarts from beginning when input audio exists
- Update frontend JobActions to show retry button for cancelled jobs
- Add tests for cancelled job retry functionality

This enables users to restart cancelled jobs from their last checkpoint
or from the beginning if the input audio is still available in GCS.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 03:42:38 -05:00
Andrew Beveridge 4b01f1100f Added testing and docs instructions for claude 2025-12-27 03:17:11 -05:00
Andrew Beveridge 6f1bafbcec Merge branch 'feature/frontend-ui-testing' 2025-12-27 01:59:38 -05:00
Andrew BeveridgeandClaude Opus 4.5 37bdb1e93a Fix yarn.lock for CI deployment
Regenerate yarn.lock to be consistent with package.json

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 01:58:35 -05:00
Andrew Beveridge d6aaaa8544 Merge branch 'main' of github.com:nomadkaraoke/karaoke-gen into feature/frontend-ui-testing 2025-12-27 01:55:50 -05:00
Andrew Beveridge 229d23ead1 Merge branch 'feature/frontend-ui-testing' of github.com:nomadkaraoke/karaoke-gen into feature/frontend-ui-testing 2025-12-27 01:53:39 -05:00
Andrew Beveridge ☄️ 2112596133 Merge pull request #61 from nomadkaraoke/feature/frontend-ui-testing
Frontend UI improvements, testing infrastructure, and download optimization
2025-12-27 01:53:03 -05:00
Andrew Beveridge f2d2bbacd9 Fixed frontend tests 2025-12-27 01:51:58 -05:00
Andrew Beveridge ☄️ d0ff5bff33 Merge branch 'main' into feature/frontend-ui-testing 2025-12-27 01:43:32 -05:00
Andrew BeveridgeandClaude Opus 4.5 7d8b7266e2 Fix issues flagged by coderabbit review
- Document unused output_dir parameter in _download_by_id_remote
- Apply default theme to DOM when no stored value exists
- Clear auth token from state after successful authentication
- Fix misleading comment in vite.config.ts
- Clarify CDG generation comment in lyrics_processor.py
- Improve accessibility in AIFeedbackModal (role, aria, labels, keyboard)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 01:37:17 -05:00
Andrew BeveridgeandClaude Opus 4.5 252c05a72b Add comprehensive countdown padding documentation
Created docs/01-reference/COUNTDOWN-PADDING.md covering:
- How CountdownProcessor works in lyrics-transcriber
- Standalone CLI workflow with instrumental padding
- Cloud backend workflow with deferred countdown
- Troubleshooting guide and data flow diagrams

Old countdown docs already in archived folder.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 01:23:34 -05:00
Andrew BeveridgeandClaude Opus 4.5 b69c3a1360 Bump version to 0.76.1
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 01:20:45 -05:00
Andrew Beveridge 989abeaf1b Fixed unintended countdown padding in lyrics review phase. Reworked song selection to use direct download by ID with new flacfetch endpoints instead of running a repeated flacfetch search 2025-12-27 01:15:55 -05:00
Andrew BeveridgeandClaude Opus 4.5 d3315593c9 Fix audio selection error when using remote flacfetch service
The issue occurred because the AudioSearchService singleton cached the
remote_search_id in service-level state, which could become stale when
concurrent requests overwrote it. This caused downloads to fail with
"'dict' object has no attribute 'source_name'" when the remote download
path wasn't properly triggered.

Changes:
- Store remote_search_id in job's state_data during search
- Pass remote_search_id explicitly to download methods
- Update _download_remote to accept search_id parameter
- Add last_remote_search_id property to AudioSearchService

This ensures each job has its own search context for downloads,
preventing race conditions in concurrent usage.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 00:56:04 -05:00
Andrew BeveridgeandClaude Opus 4.5 f48fc39328 Redesign JobCard for cleaner, more intuitive UX
- Replace status badge with subtle colored status text inline with date
- Move cancel button (now red) to left side of actions row
- Move primary action button (Select Audio, Review Lyrics) to right side
- Change primary action buttons from orange to blue for better readability
- Remove orange border highlighting on interactive jobs
- Reorder JobActions: Cancel first, then Delete, Retry, Logs
- Clean up unused imports

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 00:38:58 -05:00
Andrew BeveridgeandClaude Opus 4.5 15cc62d8e3 Improve JobCard layout for better UX
- Remove progress bar (status chip already shows status)
- Remove divider line for cleaner look
- Combine Job ID and date on single line: "ID: xyz • date/time"
- Put all action buttons on one row (primary + logs + cancel)
- Show Review Lyrics button for both awaiting_review and in_review status
- Make buttons more compact with smaller padding

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 00:32:31 -05:00
Andrew BeveridgeandClaude Opus 4.5 d2c7a907af Unify frontend UI styling between karaoke-gen and lyrics-transcriber
- Add Nomad Karaoke logo to both frontend headers
- Fix SVG viewBox to display logo at correct size
- Implement working dark/light mode toggle for both UIs
- Make karaoke-gen layout full-width to match lyrics-transcriber
- Standardize header height (70px) across both UIs
- Use lucide-react icons (Sun/Moon) for theme toggle in both UIs
- Add CSS variables for theme-aware styling in karaoke-gen
- Refactor lyrics-transcriber theme system for dynamic switching

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 00:24:25 -05:00
Andrew BeveridgeandClaude Opus 4.5 93bdacdbf2 Add comprehensive frontend testing with unified test command
- Fix JobCard tests for non-collapsible UI (20 tests)
- Add AuthStatus and AuthDialog component tests (14 tests)
- Add extractErrorMessage utility tests (12 tests)
- Export extractErrorMessage for testability
- Update jest.config.js to exclude e2e/ folder from Jest
- Fix E2E test selectors for strict mode compliance
- Add test:all command to run unit + E2E tests
- Update CLAUDE.md with frontend testing requirements

Test commands:
- npm run test:unit - Unit tests only
- npm run test:e2e - E2E tests only
- npm run test:all - Both (for CI)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 18:00:35 -05:00
Andrew BeveridgeandClaude Opus 4.5 0ed5559451 Improve frontend UX: auth in header, non-collapsible jobs, better errors
- Move auth status/logout to main header (new AuthStatus, AuthDialog components)
- Remove collapsible functionality from JobCard - details always visible
- Handle unauthenticated state gracefully (no API errors when not logged in)
- Fix [object Object] error display with extractErrorMessage helper
- Add DialogTitle for accessibility compliance
- Update dialog.tsx to merge className props with cn()
- Add screenshot E2E test for AudioSearchDialog
- Version unified from pyproject.toml via next.config.mjs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 17:44:46 -05:00
110 changed files with 14120 additions and 2134 deletions

No files matched your search

+123
View File
@@ -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
+31 -3
View File
@@ -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.
@@ -77,7 +85,7 @@ This ensures every commit pushed to the repository has a unique version number f
**Before committing and pushing ANY changes, you MUST run the full test suite.**
### Test Command
### Backend Test Command
```bash
make test 2>&1 | tail -n 500
@@ -88,14 +96,34 @@ make test 2>&1 | tail -n 500
- Always pipe output through `tail -n 500` to limit output and preserve context window
- The tail output will show test results and any failures at the end
This is the **only command you need**. It runs all tests in order and fails fast if any test fails:
This runs all backend tests in order and fails fast if any test fails:
1. Unit tests (karaoke_gen package) with coverage check
2. Backend unit tests
3. E2E integration tests with emulators (auto-starts/stops emulators)
### Frontend Test Command
When working in the `frontend/` directory, run:
```bash
cd frontend && npm run test:all 2>&1 | tail -n 200
```
This runs:
1. **Unit tests** (Jest) - Component and utility tests
2. **E2E tests** (Playwright) - Browser-based integration tests
**Note:** E2E tests require `KARAOKE_ACCESS_TOKEN` environment variable to be set in `frontend/.env.local`.
Individual test commands:
- `npm run test:unit` - Run unit tests only
- `npm run test:e2e` - Run E2E tests only
- `npm run test:ci` - Run unit tests with coverage
### Pre-commit Checklist
- [ ] `make test` passes
- [ ] `make test` passes (for backend changes)
- [ ] `cd frontend && npm run test:all` passes (for frontend changes)
- [ ] Version in `pyproject.toml` has been bumped
- [ ] `coderabbit review --plain` has been run to get comprehensive analysis and suggestions for cleaner, more maintainable code. Apply the feedback to improve accessibility, structure, and best practices.
+1 -1
View File
@@ -214,7 +214,7 @@ karaoke-gen-remote \
|----------|-------------|---------|
| `KARAOKE_GEN_URL` | Backend service URL | Required |
| `KARAOKE_GEN_AUTH_TOKEN` | Admin auth token (for protected endpoints) | Optional |
| `REVIEW_UI_URL` | Lyrics review UI URL | `https://lyrics.nomadkaraoke.com` |
| `REVIEW_UI_URL` | Lyrics review UI URL | `https://gen.nomadkaraoke.com/lyrics/` |
| `POLL_INTERVAL` | Seconds between status polls | `5` |
**Note:** The `REVIEW_UI_URL` defaults to the hosted lyrics review UI. For local development, set it to `http://localhost:5173` if you're running the frontend dev server.
+92 -54
View File
@@ -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)")
@@ -241,14 +241,17 @@ async def _download_and_start_processing(
search_results = job.state_data.get('audio_search_results', [])
if not search_results:
raise HTTPException(status_code=400, detail="No search results available")
if selection_index < 0 or selection_index >= len(search_results):
raise HTTPException(
status_code=400,
detail=f"Invalid selection index {selection_index}. Valid range: 0-{len(search_results)-1}"
)
selected = search_results[selection_index]
# Get remote_search_id from state_data (stored during initial search)
remote_search_id = job.state_data.get('remote_search_id')
# Transition to downloading state
job_manager.transition_to_state(
@@ -266,20 +269,41 @@ async def _download_and_start_processing(
# Determine if this is a remote torrent download
is_torrent_source = selected.get('provider') in ['RED', 'OPS']
is_remote_enabled = audio_search_service.is_remote_enabled()
# Check if we can use download_by_id (preferred - avoids re-searching)
source_id = selected.get('source_id')
source_name = selected.get('provider')
target_file = selected.get('target_file')
download_url = selected.get('url')
# For remote torrent downloads, have flacfetch VM upload directly to GCS
if is_torrent_source and is_remote_enabled:
# Generate GCS path for remote upload
gcs_destination = f"uploads/{job_id}/audio/"
logger.info(f"Using remote download with GCS upload to: {gcs_destination}")
result = audio_search_service.download(
result_index=selection_index,
output_dir="", # Not used for remote
gcs_path=gcs_destination,
)
# Use download_by_id if we have source_id (preferred - no re-search needed)
if source_id and source_name:
logger.info(f"Using download_by_id for {source_name} ID={source_id} with GCS upload to: {gcs_destination}")
result = audio_search_service.download_by_id(
source_name=source_name,
source_id=source_id,
output_dir="", # Not used for remote
target_file=target_file,
download_url=download_url,
gcs_path=gcs_destination,
)
else:
# Fallback to search-based download (requires re-search)
logger.info(f"No source_id available, falling back to search-based download to: {gcs_destination}")
result = audio_search_service.download(
result_index=selection_index,
output_dir="", # Not used for remote
gcs_path=gcs_destination,
remote_search_id=remote_search_id,
)
# For remote downloads, filepath is already the GCS path
if result.filepath.startswith("gs://"):
# Extract the path portion after the bucket name
@@ -294,34 +318,48 @@ async def _download_and_start_processing(
# Fallback: treat as local path (shouldn't happen for remote)
filename = os.path.basename(result.filepath)
audio_gcs_path = f"uploads/{job_id}/audio/{filename}"
logger.warning(f"Remote download returned local path: {result.filepath}, uploading manually")
with open(result.filepath, 'rb') as f:
storage_service.upload_fileobj(f, audio_gcs_path, content_type='audio/flac')
logger.info(f"Remote download complete, GCS path: {audio_gcs_path}")
else:
# Local download (YouTube or fallback)
temp_dir = tempfile.mkdtemp(prefix=f"audio_download_{job_id}_")
result = audio_search_service.download(
result_index=selection_index,
output_dir=temp_dir,
)
# Use download_by_id if we have source_id and remote is enabled
if source_id and source_name and is_remote_enabled:
logger.info(f"Using download_by_id for local download: {source_name} ID={source_id}")
result = audio_search_service.download_by_id(
source_name=source_name,
source_id=source_id,
output_dir=temp_dir,
target_file=target_file,
download_url=download_url,
)
else:
# Fallback to search-based download
result = audio_search_service.download(
result_index=selection_index,
output_dir=temp_dir,
remote_search_id=remote_search_id, # Pass for potential fallback scenarios
)
# Upload to GCS
filename = os.path.basename(result.filepath)
audio_gcs_path = f"uploads/{job_id}/audio/{filename}"
with open(result.filepath, 'rb') as f:
storage_service.upload_fileobj(
f,
audio_gcs_path,
content_type='audio/flac' # flacfetch typically returns FLAC
)
logger.info(f"Uploaded audio to GCS: {audio_gcs_path}")
# Clean up temp file
try:
os.remove(result.filepath)
@@ -386,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})")
@@ -425,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,
@@ -542,13 +585,17 @@ async def search_audio(
job_manager.fail_job(job_id, f"Audio search failed: {e}")
raise HTTPException(status_code=500, detail=f"Search failed: {e}")
# Store results in job state_data
# Store results in job state_data, including remote_search_id if available
results_dicts = [r.to_dict() for r in search_results]
state_data_update = {
'audio_search_results': results_dicts,
'audio_search_count': len(results_dicts),
}
# Store remote_search_id for use during download (important for concurrent requests)
if audio_search_service.last_remote_search_id:
state_data_update['remote_search_id'] = audio_search_service.last_remote_search_id
job_manager.update_job(job_id, {
'state_data': {
'audio_search_results': results_dicts,
'audio_search_count': len(results_dicts),
}
'state_data': state_data_update
})
# If auto_download, select best and start processing
@@ -715,25 +762,16 @@ async def select_audio_source(
detail=f"Job is not awaiting audio selection (status: {job.status})"
)
# Re-instantiate the audio search service (it caches raw results from search)
# For production, we'd need to re-search or store raw results differently
# Get search service instance
# Note: With download_by_id, we no longer need to re-search to populate the cache.
# The source_id stored in job.state_data['audio_search_results'] is sufficient.
audio_search_service = get_audio_search_service()
# Re-run search to populate the cache
# This is necessary because the service caches raw results in memory
# Validate search results exist in job state_data
search_results = job.state_data.get('audio_search_results', [])
if not search_results:
raise HTTPException(status_code=400, detail="No search results cached for this job")
artist = job.audio_search_artist or job.artist
title = job.audio_search_title or job.title
try:
# Re-search to populate cache
audio_search_service.search(artist, title)
except Exception as e:
logger.warning(f"Re-search failed, trying direct download: {e}")
selection_info = await _download_and_start_processing(
job_id=job_id,
selection_index=body.selection_index,
+201 -38
View File
@@ -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
View File
@@ -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:
+162
View File
@@ -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"
)
+10
View File
@@ -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
View File
@@ -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
View File
@@ -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)
+5 -5
View File
@@ -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
+153
View File
@@ -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}"
+218 -18
View File
@@ -247,28 +247,32 @@ class AudioSearchService:
output_dir: str,
output_filename: Optional[str] = None,
gcs_path: Optional[str] = None,
remote_search_id: Optional[str] = None,
) -> AudioDownloadResult:
"""
Download audio from a cached search result.
This method uses the cached results from the last search() call.
The API flow is:
1. Client calls search() -> gets list of results
2. Client picks an index
3. Client calls download(index) -> gets downloaded file
If a remote flacfetch service is configured and the search was performed
remotely (for torrent sources), uses the remote service for download.
Args:
result_index: Index of the result to download (from search results)
output_dir: Directory to save the downloaded file
output_filename: Optional filename (without extension)
gcs_path: Optional GCS path for remote uploads (e.g., "uploads/job123/audio/")
remote_search_id: Optional search_id for remote downloads. If provided,
uses this instead of the cached _remote_search_id. This is important
for concurrent requests where the service-level cache may be stale.
Returns:
AudioDownloadResult with the downloaded file path
Raises:
DownloadError: If download fails or no cached result for index
"""
@@ -278,18 +282,21 @@ class AudioSearchService:
f"Available indices: 0-{len(self._cached_results) - 1}. "
"Run search() first."
)
result = self._cached_results[result_index]
logger.info(f"Downloading: {result.artist} - {result.title} from {result.provider}")
# Use provided search_id or fall back to service-level cache
effective_search_id = remote_search_id or self._remote_search_id
# Check if this was a remote search (torrent sources need remote download)
if self._remote_search_id and self._remote_client:
if effective_search_id and self._remote_client:
# Check if this is a torrent source that needs remote handling
is_torrent = result.provider in ["RED", "OPS"]
if is_torrent:
return self._download_remote(result_index, output_dir, output_filename, gcs_path)
return self._download_remote(result_index, output_dir, output_filename, gcs_path, effective_search_id)
# Delegate to shared FlacFetcher (local download)
fetch_result = self._fetcher.download(result, output_dir, output_filename)
@@ -298,21 +305,182 @@ class AudioSearchService:
return fetch_result
def download_by_id(
self,
source_name: str,
source_id: str,
output_dir: str,
output_filename: Optional[str] = None,
target_file: Optional[str] = None,
download_url: Optional[str] = None,
gcs_path: Optional[str] = None,
) -> AudioDownloadResult:
"""
Download audio directly by source ID (no prior search required).
This is the preferred method when you have stored the source_id from a
previous search and want to download later without re-searching. This
avoids unnecessary API calls to private trackers.
Args:
source_name: Provider name (RED, OPS, YouTube, Spotify)
source_id: Source-specific ID (torrent ID, video ID, track ID)
output_dir: Directory to save the downloaded file
output_filename: Optional filename (without extension)
target_file: For torrents, specific file to extract from the torrent
download_url: For YouTube/Spotify, direct URL (optional)
gcs_path: Optional GCS path for remote uploads
Returns:
AudioDownloadResult with the downloaded file path
Raises:
DownloadError: If download fails
"""
logger.info(f"Download by ID: {source_name} ID={source_id}")
# For torrent sources, must use remote client
if source_name in ["RED", "OPS"]:
if not self._remote_client:
raise DownloadError(
f"Cannot download from {source_name} without remote flacfetch service"
)
return self._download_by_id_remote(
source_name=source_name,
source_id=source_id,
output_dir=output_dir,
output_filename=output_filename,
target_file=target_file,
download_url=download_url,
gcs_path=gcs_path,
)
# For YouTube/Spotify, can use local flacfetch via FetchManager.download_by_id
# But we currently only have remote support, so use remote if available
if self._remote_client:
return self._download_by_id_remote(
source_name=source_name,
source_id=source_id,
output_dir=output_dir,
output_filename=output_filename,
target_file=target_file,
download_url=download_url,
gcs_path=gcs_path,
)
# Local download for YouTube/Spotify (fallback)
# Use the local fetcher's download_by_id if available
raise DownloadError(
f"Local download_by_id not yet implemented for {source_name}. "
"Configure FLACFETCH_API_URL for remote downloads."
)
def _download_by_id_remote(
self,
source_name: str,
source_id: str,
output_dir: str, # Not used for remote downloads (files go to GCS or remote server)
output_filename: Optional[str] = None,
target_file: Optional[str] = None,
download_url: Optional[str] = None,
gcs_path: Optional[str] = None,
) -> AudioDownloadResult:
"""
Download by ID using the remote flacfetch service.
Note: output_dir is accepted for API compatibility but ignored for remote
downloads. Remote downloads either go to GCS (if gcs_path is set) or to
the remote server's download directory.
"""
# output_dir is intentionally unused - remote downloads don't use local paths
_ = output_dir
try:
# Enable nested event loops
try:
running_loop = asyncio.get_running_loop()
nest_asyncio.apply(running_loop)
except RuntimeError:
pass
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
# Start download
download_id = loop.run_until_complete(
self._remote_client.download_by_id(
source_name=source_name,
source_id=source_id,
output_filename=output_filename,
target_file=target_file,
download_url=download_url,
gcs_path=gcs_path,
)
)
logger.info(f"Remote download by ID started: {download_id}")
# Wait for completion
def log_progress(status):
progress = status.get("progress", 0)
speed = status.get("download_speed_kbps", 0)
logger.debug(f"Download progress: {progress:.1f}% ({speed:.1f} KB/s)")
final_status = loop.run_until_complete(
self._remote_client.wait_for_download(
download_id,
timeout=600,
progress_callback=log_progress,
)
)
finally:
loop.close()
# Determine file path
filepath = final_status.get("gcs_path") or final_status.get("output_path")
if not filepath:
raise DownloadError("Remote download completed but no file path returned")
logger.info(f"Remote download by ID complete: {filepath}")
return AudioDownloadResult(
filepath=filepath,
artist="", # Not available without search
title="", # Not available without search
provider=source_name,
quality="", # Not available without search
)
except FlacfetchServiceError as e:
raise DownloadError(f"Remote download by ID failed: {e}") from e
except Exception as e:
logger.error(f"Remote download by ID error: {e}")
raise DownloadError(f"Remote download by ID failed: {e}") from e
def _download_remote(
self,
result_index: int,
output_dir: str,
output_filename: Optional[str] = None,
gcs_path: Optional[str] = None,
search_id: Optional[str] = None,
) -> AudioDownloadResult:
"""
Download using the remote flacfetch service.
The remote service downloads via torrent and optionally uploads to GCS.
Args:
result_index: Index of the result to download
output_dir: Directory to save downloaded file
output_filename: Optional filename
gcs_path: Optional GCS path for remote uploads
search_id: Remote search ID to use (overrides self._remote_search_id)
"""
if not self._remote_search_id:
effective_search_id = search_id or self._remote_search_id
if not effective_search_id:
raise DownloadError("No remote search ID - run search() first")
result = self._cached_results[result_index]
try:
@@ -329,7 +497,7 @@ class AudioSearchService:
# Start download
download_id = loop.run_until_complete(
self._remote_client.download(
search_id=self._remote_search_id,
search_id=effective_search_id,
result_index=result_index,
output_filename=output_filename,
gcs_path=gcs_path,
@@ -434,22 +602,54 @@ class AudioSearchService:
output_dir: str,
output_filename: Optional[str] = None,
gcs_path: Optional[str] = None,
remote_search_id: Optional[str] = None,
) -> AudioDownloadResult:
"""
Async version of download for use in async routes.
Note: Currently wraps sync download in executor. Future optimization
could make this fully async.
"""
loop = asyncio.get_event_loop()
return await loop.run_in_executor(
None,
lambda: self.download(result_index, output_dir, output_filename, gcs_path)
None,
lambda: self.download(result_index, output_dir, output_filename, gcs_path, remote_search_id)
)
async def download_by_id_async(
self,
source_name: str,
source_id: str,
output_dir: str,
output_filename: Optional[str] = None,
target_file: Optional[str] = None,
download_url: Optional[str] = None,
gcs_path: Optional[str] = None,
) -> AudioDownloadResult:
"""
Async version of download_by_id for use in async routes.
"""
loop = asyncio.get_event_loop()
return await loop.run_in_executor(
None,
lambda: self.download_by_id(
source_name, source_id, output_dir, output_filename,
target_file, download_url, gcs_path
)
)
def is_remote_enabled(self) -> bool:
"""Check if remote flacfetch service is configured."""
return self._remote_client is not None
@property
def last_remote_search_id(self) -> Optional[str]:
"""Get the search_id from the last remote search.
This should be stored in job state_data after search and passed
back to download() to ensure correct remote download handling.
"""
return self._remote_search_id
async def check_remote_health(self) -> Optional[dict]:
"""
+61
View File
@@ -199,6 +199,67 @@ class FlacfetchClient:
except httpx.HTTPStatusError as e:
raise FlacfetchServiceError(f"Download start failed: {e.response.status_code} - {e.response.text}")
async def download_by_id(
self,
source_name: str,
source_id: str,
output_filename: Optional[str] = None,
target_file: Optional[str] = None,
download_url: Optional[str] = None,
gcs_path: Optional[str] = None,
) -> str:
"""
Start downloading directly by source ID (no prior search required).
This is useful when you have stored the source_id from a previous search
and want to download later without re-searching.
Args:
source_name: Provider name (RED, OPS, YouTube, Spotify)
source_id: Source-specific ID (torrent ID, video ID, track ID)
output_filename: Optional custom filename (without extension)
target_file: For torrents, specific file to extract
download_url: For YouTube/Spotify, direct URL (optional)
gcs_path: GCS path for upload (e.g., "uploads/job123/audio/")
Returns:
Download ID for tracking progress
Raises:
FlacfetchServiceError: On download start failure
"""
try:
async with httpx.AsyncClient() as client:
payload = {
"source_name": source_name,
"source_id": source_id,
}
if output_filename:
payload["output_filename"] = output_filename
if target_file:
payload["target_file"] = target_file
if download_url:
payload["download_url"] = download_url
if gcs_path:
payload["upload_to_gcs"] = True
payload["gcs_path"] = gcs_path
resp = await client.post(
f"{self.base_url}/download-by-id",
headers=self._headers(),
json=payload,
timeout=self.timeout,
)
resp.raise_for_status()
data = resp.json()
return data["download_id"]
except httpx.RequestError as e:
raise FlacfetchServiceError(f"Download by ID request failed: {e}")
except httpx.HTTPStatusError as e:
raise FlacfetchServiceError(f"Download by ID failed: {e.response.status_code} - {e.response.text}")
async def get_download_status(self, download_id: str) -> Dict[str, Any]:
"""
Get the current status of a download.
+469
View File
@@ -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
+3 -3
View File
@@ -547,9 +547,9 @@ class TestRemoteDownloadPath:
# Call download - should route to remote
result = service.download(0, "/tmp", gcs_path="uploads/job123/audio/")
# Verify remote download was called
service._download_remote.assert_called_once_with(0, "/tmp", None, "uploads/job123/audio/")
# Verify remote download was called (includes search_id as last parameter)
service._download_remote.assert_called_once_with(0, "/tmp", None, "uploads/job123/audio/", "remote_search_123")
assert result.filepath == "gs://bucket/uploads/job123/audio/Waterloo.flac"
def test_download_uses_remote_for_ops_provider(self):
+9 -7
View File
@@ -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
+3 -2
View File
@@ -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
+162 -1
View File
@@ -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
+516
View File
@@ -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!"
+11 -7
View File
@@ -185,15 +185,19 @@ async def process_render_video(job_id: str) -> bool:
storage.download_file(audio_gcs_path, audio_path)
job_log.info(f"Audio downloaded: {os.path.getsize(audio_path)} bytes")
# Check if corrections have countdown padding and pad audio if needed
# This ensures the audio matches the shifted timestamps in the corrections
# Process countdown intro if needed (for songs that start too quickly)
# This adds "3... 2... 1..." segment and pads audio with 3s silence
# Note: Countdown is deferred to this stage (not during lyrics transcription)
# so the review UI can show the original timing without the 3s shift
countdown_processor = CountdownProcessor(cache_dir=temp_dir, logger=logger)
if countdown_processor.has_countdown(correction_result):
job_log.info("Detected countdown in corrections - creating padded audio for sync")
audio_path = countdown_processor.create_padded_audio_only(audio_path)
job_log.info(f"Padded audio created: {audio_path}")
correction_result, audio_path, padding_added, padding_seconds = countdown_processor.process(
correction_result=correction_result,
audio_filepath=audio_path,
)
if padding_added:
job_log.info(f"Countdown added: {padding_seconds}s padding applied to audio and timestamps shifted")
else:
job_log.info("No countdown detected in corrections - using original audio")
job_log.info("No countdown needed - song starts after 3 seconds")
# 6. Get or create styles using the unified style loader
job_log.info("Loading style configuration...")
+1 -1
View File
@@ -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:
@@ -249,7 +249,7 @@ This section provides a comprehensive comparison of all CLI parameters between `
| # | Parameter | Local | Remote | Description |
|---|-----------|-------|--------|-------------|
| R1 | `--service-url` | N/A | 🔹 | **Backend service URL.** URL of the karaoke-gen cloud backend. Can also be set via `KARAOKE_GEN_URL` environment variable. Required for remote mode. |
| R2 | `--review-ui-url` | N/A | 🔹 | **Lyrics review UI URL.** URL of the hosted lyrics review web application. Default: `https://lyrics.nomadkaraoke.com`. |
| R2 | `--review-ui-url` | N/A | 🔹 | **Lyrics review UI URL.** URL of the hosted lyrics review web application. Default: `https://gen.nomadkaraoke.com/lyrics/`. |
| R3 | `--poll-interval` | N/A | 🔹 | **Status poll frequency.** Seconds between job status checks while monitoring. Default: 5 seconds. |
| R4 | `--environment` | N/A | 🔹 | **Job environment tag.** Tag jobs with environment label (test/production/development) for filtering and cleanup. Sent as `X-Environment` header. |
| R5 | `--client-id` | N/A | 🔹 | **Client identifier tag.** Tag jobs with client/user identifier for filtering. Sent as `X-Client-ID` header. |
+265
View File
@@ -0,0 +1,265 @@
# Countdown Padding Feature
This document explains how the countdown padding feature works across the karaoke-gen system, including both the standalone CLI tool and the cloud backend.
## Overview
When a song's vocals start within the first 3 seconds, karaoke singers don't have enough time to prepare. The countdown padding feature addresses this by:
1. Adding 3 seconds of silence to the start of the audio
2. Shifting all lyrics timestamps forward by 3 seconds
3. Adding a "3... 2... 1..." countdown segment (displayed at 0.1s - 2.9s)
This gives singers a visual countdown before the lyrics begin.
## Technical Details
### CountdownProcessor (lyrics-transcriber)
The core countdown logic lives in the `lyrics-transcriber` library:
**File:** `lyrics_transcriber/output/countdown_processor.py`
**Constants:**
- `COUNTDOWN_THRESHOLD_SECONDS = 3.0` - Trigger countdown if first word starts within this time
- `COUNTDOWN_PADDING_SECONDS = 3.0` - Amount of silence to add
- `COUNTDOWN_START_TIME = 0.1` - When countdown text starts displaying
- `COUNTDOWN_END_TIME = 2.9` - When countdown text ends
- `COUNTDOWN_TEXT = "3... 2... 1..."` - The countdown text displayed
**Key Methods:**
- `process(correction_result, audio_filepath)` - Main entry point. Returns `(modified_result, padded_audio_path, padding_added, padding_seconds)`
- `_needs_countdown(correction_result)` - Checks if first word starts within 3 seconds
- `_create_padded_audio(audio_filepath)` - Uses ffmpeg to prepend silence
- `_add_countdown_to_result(correction_result)` - Shifts timestamps and adds countdown segment
- `has_countdown(correction_result)` - Detects if countdown already exists (for loading saved corrections)
**FFmpeg Command Used:**
```bash
ffmpeg -y -hide_banner -loglevel error \
-f lavfi -t 3.0 -i anullsrc=channel_layout=stereo:sample_rate=44100 \
-i input_audio.flac \
-filter_complex "[0:a][1:a]concat=n=2:v=0:a=1[out]" \
-map "[out]" \
-c:a flac \
output_padded.flac
```
This prepends 3 seconds of stereo silence (44.1kHz) and uses FLAC to preserve audio quality.
## Workflow: Standalone CLI (karaoke-gen)
When using the karaoke-gen CLI tool locally:
```
┌─────────────────────────────────────────────────────────────────────┐
│ STANDALONE CLI WORKFLOW │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ 1. LyricsTranscriber.process() │
│ └─> add_countdown=True (default) │
│ └─> CountdownProcessor adds countdown + pads vocals audio │
│ └─> Returns: padded_audio_filepath, countdown_padding_added │
│ │
│ 2. Audio Separation │
│ └─> Creates instrumental files (original timing) │
│ │
│ 3. Apply Padding to Instrumentals │
│ └─> AudioProcessor.apply_countdown_padding_to_instrumentals() │
│ └─> Pads all instrumental variants to match vocals │
│ └─> Creates files with "(Padded)" suffix │
│ │
│ 4. Final Video Generation │
│ └─> Uses padded vocals + padded instrumental │
│ └─> Everything is synchronized │
│ │
└─────────────────────────────────────────────────────────────────────┘
```
**Key Files:**
- `karaoke_gen/lyrics_processor.py` - Calls LyricsTranscriber, captures padding info
- `karaoke_gen/audio_processor.py` - `apply_countdown_padding_to_instrumentals()` and `pad_audio_file()`
- `karaoke_gen/karaoke_gen.py` - Orchestrates the workflow, applies padding after separation
**Instrumental File Naming:**
- Original: `Artist - Song (Instrumental model.ckpt).flac`
- Padded: `Artist - Song (Instrumental model.ckpt) (Padded).flac`
## Workflow: Cloud Backend
The cloud backend has a two-phase workflow with human review in between. This requires special handling to avoid sync issues.
```
┌─────────────────────────────────────────────────────────────────────┐
│ CLOUD BACKEND WORKFLOW │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ PHASE 1: Lyrics Worker (lyrics_worker.py) │
│ ───────────────────────────────────────── │
│ └─> LyricsTranscriber.process() │
│ └─> add_countdown=FALSE <── Deferred to Phase 2 │
│ └─> Corrections saved WITHOUT countdown │
│ └─> Original audio timing preserved │
│ │
│ HUMAN REVIEW (Review UI) │
│ ──────────────────────── │
│ └─> User reviews/edits lyrics │
│ └─> Audio playback uses original (un-padded) audio │
│ └─> Timestamps match audio perfectly │
│ │
│ PHASE 2: Render Video Worker (render_video_worker.py) │
│ ───────────────────────────────────────────────────── │
│ └─> CountdownProcessor.process() called HERE │
│ └─> Adds countdown segment + shifts timestamps │
│ └─> Creates padded audio for video rendering │
│ └─> Final video has countdown + synced audio │
│ │
└─────────────────────────────────────────────────────────────────────┘
```
**Why Defer Countdown to Phase 2?**
Previously, countdown was added during Phase 1 (lyrics transcription). This caused a problem:
1. Lyrics corrections were saved with countdown segment + shifted timestamps
2. The padded audio file was created in a temp directory that was deleted
3. Review UI served the original (un-padded) audio
4. **Result:** 3-second sync mismatch between lyrics and audio in review UI
By deferring countdown to Phase 2:
- Review UI shows original timing (audio and lyrics are perfectly synced)
- Users can accurately review and edit lyrics
- Countdown is added just before final video rendering
**Key Files:**
- `karaoke_gen/lyrics_processor.py:405` - Sets `add_countdown=not is_serverless`
- `backend/workers/render_video_worker.py:188-200` - Adds countdown using `CountdownProcessor.process()`
**Serverless Detection:**
```python
is_serverless = (
os.getenv("MODAL_TASK_ID") is not None or
os.getenv("MODAL_FUNCTION_NAME") is not None or
os.path.exists("/.modal")
)
```
## Finalization Step (karaoke_finalise)
The `KaraokeFinalise` class handles creating the final karaoke video with instrumental audio.
**File:** `karaoke_gen/karaoke_finalise/karaoke_finalise.py`
It includes a safety net in `remux_with_instrumental()`:
- If `countdown_padding_seconds` is set but instrumental doesn't have "(Padded)" in the name
- It automatically pads the instrumental before remuxing
- This ensures vocals and instrumental stay synchronized
## Detecting Existing Countdown
When loading saved corrections (e.g., from a JSON file), you can detect if countdown was applied:
```python
countdown_processor = CountdownProcessor(cache_dir=temp_dir)
has_countdown = countdown_processor.has_countdown(correction_result)
# Or check for countdown text in first segment
first_segment = correction_result.corrected_segments[0]
is_countdown = first_segment.text == "3... 2... 1..."
```
You can also detect from LRC files:
```python
# LyricsProcessor._detect_countdown_padding_from_lrc()
# Checks for "3... 2... 1..." text or first timestamp >= 2.5s
```
## Configuration
### Disabling Countdown
To disable countdown for a specific transcription:
```python
from lyrics_transcriber.core.config import OutputConfig
output_config = OutputConfig(
# ... other options
add_countdown=False, # Disable countdown
)
```
### Padding Amount
The padding amount is currently fixed at 3.0 seconds. To change this, you would need to modify the constants in `CountdownProcessor`.
## Troubleshooting
### Issue: Countdown appears but audio is out of sync
**Cause:** Instrumental audio wasn't padded to match vocals.
**Solution:**
- Check that `countdown_padding_added` was captured from transcription
- Verify `apply_countdown_padding_to_instrumentals()` was called
- Look for "(Padded)" in instrumental filenames
### Issue: Review UI shows 3-second offset
**Cause:** Countdown was added during transcription instead of rendering phase.
**Solution:**
- This was fixed in v0.76.1
- Ensure `add_countdown=False` for serverless mode
- Countdown should only be added in `render_video_worker.py`
### Issue: No countdown even though song starts immediately
**Cause:** First word timestamp might be exactly at or after 3.0 seconds.
**Check:**
- Look at the first segment's first word start_time
- Countdown triggers only if `first_word_start < 3.0`
## Testing
### Unit Tests
Countdown padding tests are in `tests/unit/test_countdown_padding.py`:
```bash
python -m pytest tests/unit/test_countdown_padding.py -v
```
Tests cover:
- `pad_audio_file()` success, failure, and timeout
- `apply_countdown_padding_to_instrumentals()` for clean and combined instrumentals
- Integration with `LyricsProcessor` and `KaraokeGen`
- Custom instrumental padding
- Idempotency (skipping already-padded files)
## Data Flow Summary
```
┌─────────────────────────────────────────────────────────────────────┐
│ DATA FLOW │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ Input: Song with vocals starting at 1.5s │
│ │
│ After Countdown Processing: │
│ ───────────────────────────── │
│ • Audio: 3s silence + original audio │
│ • First segment: "3... 2... 1..." at 0.1s-2.9s │
│ • Original first word: moved from 1.5s → 4.5s │
│ • All subsequent timestamps: shifted +3.0s │
│ │
│ Result: Singer sees countdown, has time to prepare │
│ │
└─────────────────────────────────────────────────────────────────────┘
```
## Version History
- **v0.76.1** - Fixed cloud backend sync issue by deferring countdown to render phase
- **v0.70.x** - Initial countdown padding implementation integrated from lyrics-transcriber
+1
View File
@@ -0,0 +1 @@
playwright-report-prod/
+20 -1
View File
@@ -4,7 +4,7 @@
@custom-variant dark (&:is(.dark *));
:root {
/* Matching instrumental review UI color scheme */
/* Dark theme (default) - Matching instrumental review UI color scheme */
--bg: #0f0f0f;
--card: #1a1a1a;
--card-border: #2a2a2a;
@@ -41,6 +41,25 @@
--radius: 0.5rem;
}
:root.light {
/* Light theme */
--bg: #f8fafc;
--card: #ffffff;
--card-border: #e2e8f0;
--waveform-bg: #f1f5f9;
--text: #1e293b;
--text-muted: #64748b;
--primary: #3b82f6;
--primary-hover: #2563eb;
--secondary: #f1f5f9;
--secondary-hover: #e2e8f0;
--success: #22c55e;
--warning: #f59e0b;
--danger: #ef4444;
--pink: #ec4899;
--blue: #60a5fa;
}
@theme inline {
--font-sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
--font-mono: "SF Mono", Monaco, "Cascadia Code", monospace;
+5 -10
View File
@@ -3,20 +3,15 @@ import type { Metadata } from "next"
import "./globals.css"
export const metadata: Metadata = {
title: "Karaoke Generator - Nomad Karaoke",
title: "Nomad Karaoke: Generator",
description: "Generate professional karaoke videos with AI-powered vocal separation and synchronized lyrics",
icons: {
icon: [
{
url: "/icon-light-32x32.png",
media: "(prefers-color-scheme: light)",
},
{
url: "/icon-dark-32x32.png",
media: "(prefers-color-scheme: dark)",
},
{ url: "/favicon.ico", sizes: "any" },
{ url: "/favicon-16x16.png", sizes: "16x16", type: "image/png" },
{ url: "/favicon-32x32.png", sizes: "32x32", type: "image/png" },
],
apple: "/apple-icon.png",
apple: "/apple-touch-icon.png",
},
}
+81 -34
View File
@@ -1,15 +1,16 @@
"use client"
import { useState, useEffect } from "react"
import { api, Job } from "@/lib/api"
import { api, Job, getAccessToken } from "@/lib/api"
import { useAutoMode, getAutoModeFromUrl } from "@/lib/auto-mode"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Music2, RefreshCw, Loader2, Zap, ZapOff } from "lucide-react"
import { Music2, RefreshCw, Loader2, Zap, ZapOff, KeyRound, Moon, Sun } from "lucide-react"
import { JobCard } from "@/components/job"
import { JobSubmission } from "@/components/job/JobSubmission"
import { AuthBanner } from "@/components/auth-banner"
import { AuthStatus } from "@/components/auth"
import { AutoProcessor } from "@/components/AutoProcessor"
import { useTheme } from "@/lib/theme"
import {
Tooltip,
TooltipContent,
@@ -20,7 +21,14 @@ import {
export default function HomePage() {
const [jobs, setJobs] = useState<Job[]>([])
const [isLoadingJobs, setIsLoadingJobs] = useState(true)
const [isAuthenticated, setIsAuthenticated] = useState(false)
const { enabled: autoModeEnabled, setEnabled: setAutoMode, toggle: toggleAutoMode } = useAutoMode()
const { isDarkMode, toggleTheme, mounted } = useTheme()
// Check auth status on mount
useEffect(() => {
setIsAuthenticated(!!getAccessToken())
}, [])
// Initialize auto-mode from URL parameter on mount
useEffect(() => {
@@ -30,38 +38,48 @@ export default function HomePage() {
}
}, [setAutoMode])
// Load jobs on mount
// Load jobs on mount (only if authenticated)
useEffect(() => {
if (!isAuthenticated) {
setIsLoadingJobs(false)
return
}
loadJobs()
// Poll for updates every 10 seconds
const interval = setInterval(loadJobs, 10000)
return () => clearInterval(interval)
}, [])
}, [isAuthenticated])
async function loadJobs() {
if (!getAccessToken()) {
setIsLoadingJobs(false)
return
}
try {
const data = await api.listJobs({ limit: 20 })
setJobs(data)
} catch (err) {
console.error("Failed to load jobs:", err)
} catch (err: any) {
// Don't log auth errors - user just needs to authenticate
if (err?.status !== 401) {
console.error("Failed to load jobs:", err)
}
} finally {
setIsLoadingJobs(false)
}
}
return (
<div className="min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950">
<div className="min-h-screen" style={{ background: 'var(--bg)' }}>
{/* AutoProcessor - handles non-interactive mode */}
<AutoProcessor jobs={jobs} onJobsChanged={loadJobs} />
{/* Header */}
<header className="border-b border-slate-800 bg-slate-950/50 backdrop-blur-sm sticky top-0 z-10">
<div className="container mx-auto px-4 py-4 flex items-center justify-between">
<header className="border-b backdrop-blur-sm sticky top-0 z-10" style={{ borderColor: 'var(--card-border)', backgroundColor: 'var(--card)' }}>
<div className="px-4 py-3 flex items-center justify-between">
<div className="flex items-center gap-3">
<Music2 className="w-8 h-8 text-amber-500" />
<img src="/nomad-karaoke-logo.svg" alt="Nomad Karaoke" className="h-10" />
<div>
<h1 className="text-xl font-bold text-white">Karaoke Generator</h1>
<p className="text-xs text-slate-400">by Nomad Karaoke</p>
<h1 className="text-xl font-bold" style={{ color: 'var(--text)' }}>Karaoke Generator</h1>
</div>
</div>
<div className="flex items-center gap-2">
@@ -72,11 +90,8 @@ export default function HomePage() {
variant="ghost"
size="sm"
onClick={toggleAutoMode}
className={`${
autoModeEnabled
? "text-amber-400 hover:text-amber-300 bg-amber-500/10"
: "text-slate-400 hover:text-white"
}`}
className={autoModeEnabled ? "text-amber-400 hover:text-amber-300 bg-amber-500/10" : ""}
style={!autoModeEnabled ? { color: 'var(--text-muted)' } : undefined}
>
{autoModeEnabled ? (
<Zap className="w-4 h-4 mr-2" />
@@ -90,7 +105,7 @@ export default function HomePage() {
<p className="font-medium">
{autoModeEnabled ? "Auto Mode Enabled" : "Auto Mode Disabled"}
</p>
<p className="text-xs text-slate-400 mt-1">
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
{autoModeEnabled
? "Jobs will auto-complete review and select clean instrumental (like -y flag)"
: "Click to enable non-interactive mode"}
@@ -102,17 +117,41 @@ export default function HomePage() {
variant="ghost"
size="sm"
onClick={loadJobs}
disabled={isLoadingJobs}
className="text-slate-400 hover:text-white"
disabled={isLoadingJobs || !isAuthenticated}
style={{ color: 'var(--text-muted)' }}
>
<RefreshCw className={`w-4 h-4 mr-2 ${isLoadingJobs ? 'animate-spin' : ''}`} />
Refresh
</Button>
<AuthStatus />
{mounted && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="sm"
onClick={toggleTheme}
style={{ color: 'var(--text-muted)' }}
>
{isDarkMode ? (
<Sun className="w-4 h-4" />
) : (
<Moon className="w-4 h-4" />
)}
</Button>
</TooltipTrigger>
<TooltipContent side="bottom">
<p>{isDarkMode ? "Switch to light mode" : "Switch to dark mode"}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
</div>
</div>
</header>
<main className="container mx-auto px-4 py-8 max-w-5xl space-y-6">
<main className="px-4 py-8 space-y-6">
{/* Auto Mode Banner */}
{autoModeEnabled && (
<div className="bg-amber-500/10 border border-amber-500/30 rounded-lg p-4 flex items-center gap-3">
@@ -134,15 +173,23 @@ export default function HomePage() {
</div>
)}
{/* Authentication Banner */}
<AuthBanner />
{/* Unauthenticated state */}
{!isAuthenticated && (
<div className="bg-amber-500/10 border border-amber-500/30 rounded-lg p-6 text-center">
<KeyRound className="w-8 h-8 text-amber-400 mx-auto mb-3" />
<h3 className="text-lg font-medium mb-2" style={{ color: 'var(--text)' }}>Authentication Required</h3>
<p className="text-sm mb-4" style={{ color: 'var(--text-muted)' }}>
Click the Login button in the header to enter your access token
</p>
</div>
)}
<div className="grid lg:grid-cols-2 gap-8">
{/* Submit Job Card */}
<Card className="border-slate-800 bg-slate-900/50 backdrop-blur">
<Card className="backdrop-blur" style={{ borderColor: 'var(--card-border)', backgroundColor: 'var(--card)' }}>
<CardHeader>
<CardTitle className="text-white">Create Karaoke Video</CardTitle>
<CardDescription className="text-slate-400">
<CardTitle style={{ color: 'var(--text)' }}>Create Karaoke Video</CardTitle>
<CardDescription style={{ color: 'var(--text-muted)' }}>
Upload an audio file, provide a YouTube URL, or search for audio by artist & title
</CardDescription>
</CardHeader>
@@ -152,19 +199,19 @@ export default function HomePage() {
</Card>
{/* Jobs List Card */}
<Card className="border-slate-800 bg-slate-900/50 backdrop-blur">
<Card className="backdrop-blur" style={{ borderColor: 'var(--card-border)', backgroundColor: 'var(--card)' }}>
<CardHeader>
<CardTitle className="text-white flex items-center justify-between">
<CardTitle className="flex items-center justify-between" style={{ color: 'var(--text)' }}>
Recent Jobs
{isLoadingJobs && <Loader2 className="w-4 h-4 animate-spin text-slate-400" />}
{isLoadingJobs && <Loader2 className="w-4 h-4 animate-spin" style={{ color: 'var(--text-muted)' }} />}
</CardTitle>
<CardDescription className="text-slate-400">
<CardDescription style={{ color: 'var(--text-muted)' }}>
{jobs.length} job{jobs.length !== 1 ? 's' : ''} found
</CardDescription>
</CardHeader>
<CardContent>
{jobs.length === 0 ? (
<div className="text-center py-8 text-slate-500">
<div className="text-center py-8" style={{ color: 'var(--text-muted)' }}>
<Music2 className="w-12 h-12 mx-auto mb-3 opacity-50" />
<p>No jobs yet. Create one to get started!</p>
</div>
@@ -181,8 +228,8 @@ export default function HomePage() {
</main>
{/* Footer */}
<footer className="border-t border-slate-800 mt-12 py-6">
<div className="container mx-auto px-4 text-center text-sm text-slate-500">
<footer className="border-t mt-12 py-6" style={{ borderColor: 'var(--card-border)' }}>
<div className="px-4 text-center text-sm" style={{ color: 'var(--text-muted)' }}>
<p>
Powered by{" "}
<a href="https://github.com/nomadkaraoke/karaoke-gen" className="text-amber-500 hover:underline">
@@ -0,0 +1,162 @@
/**
* Tests for AuthStatus and AuthDialog components
*/
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { AuthStatus } from '../auth/AuthStatus'
import { AuthDialog } from '../auth/AuthDialog'
import { getAccessToken, setAccessToken, clearAccessToken } from '@/lib/api'
// Mock the api module
jest.mock('@/lib/api', () => ({
getAccessToken: jest.fn(),
setAccessToken: jest.fn(),
clearAccessToken: jest.fn(),
}))
const mockGetAccessToken = getAccessToken as jest.Mock
const mockSetAccessToken = setAccessToken as jest.Mock
const mockClearAccessToken = clearAccessToken as jest.Mock
// Mock window.location.reload
const mockReload = jest.fn()
Object.defineProperty(window, 'location', {
value: { reload: mockReload },
writable: true,
})
describe('AuthStatus', () => {
beforeEach(() => {
jest.clearAllMocks()
})
it('shows Login button when not authenticated', () => {
mockGetAccessToken.mockReturnValue(null)
render(<AuthStatus />)
expect(screen.getByRole('button', { name: /login/i })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: /logout/i })).not.toBeInTheDocument()
})
it('shows Logout button when authenticated', () => {
mockGetAccessToken.mockReturnValue('test-token')
render(<AuthStatus />)
expect(screen.getByRole('button', { name: /logout/i })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: /login/i })).not.toBeInTheDocument()
})
it('opens auth dialog when Login is clicked', () => {
mockGetAccessToken.mockReturnValue(null)
render(<AuthStatus />)
fireEvent.click(screen.getByRole('button', { name: /login/i }))
// Dialog should appear with "Authentication Required" title
expect(screen.getByText('Authentication Required')).toBeInTheDocument()
})
it('clears token and reloads when Logout is clicked', () => {
mockGetAccessToken.mockReturnValue('test-token')
render(<AuthStatus />)
fireEvent.click(screen.getByRole('button', { name: /logout/i }))
expect(mockClearAccessToken).toHaveBeenCalled()
expect(mockReload).toHaveBeenCalled()
})
it('calls onAuthChange callback when logging out', () => {
mockGetAccessToken.mockReturnValue('test-token')
const mockOnAuthChange = jest.fn()
render(<AuthStatus onAuthChange={mockOnAuthChange} />)
fireEvent.click(screen.getByRole('button', { name: /logout/i }))
expect(mockOnAuthChange).toHaveBeenCalled()
})
})
describe('AuthDialog', () => {
const mockOnClose = jest.fn()
const mockOnSuccess = jest.fn()
beforeEach(() => {
jest.clearAllMocks()
})
it('renders when open is true', () => {
render(<AuthDialog open={true} onClose={mockOnClose} onSuccess={mockOnSuccess} />)
expect(screen.getByText('Authentication Required')).toBeInTheDocument()
expect(screen.getByPlaceholderText('Enter access token')).toBeInTheDocument()
})
it('does not render when open is false', () => {
render(<AuthDialog open={false} onClose={mockOnClose} onSuccess={mockOnSuccess} />)
expect(screen.queryByText('Authentication Required')).not.toBeInTheDocument()
})
it('calls onClose when Cancel is clicked', () => {
render(<AuthDialog open={true} onClose={mockOnClose} onSuccess={mockOnSuccess} />)
fireEvent.click(screen.getByRole('button', { name: /cancel/i }))
expect(mockOnClose).toHaveBeenCalled()
})
it('disables Authenticate button when token is empty', () => {
render(<AuthDialog open={true} onClose={mockOnClose} onSuccess={mockOnSuccess} />)
const authenticateBtn = screen.getByRole('button', { name: /authenticate/i })
expect(authenticateBtn).toBeDisabled()
})
it('enables Authenticate button when token is entered', () => {
render(<AuthDialog open={true} onClose={mockOnClose} onSuccess={mockOnSuccess} />)
const input = screen.getByPlaceholderText('Enter access token')
fireEvent.change(input, { target: { value: 'my-token' } })
const authenticateBtn = screen.getByRole('button', { name: /authenticate/i })
expect(authenticateBtn).not.toBeDisabled()
})
it('sets token and calls onSuccess when form is submitted', async () => {
render(<AuthDialog open={true} onClose={mockOnClose} onSuccess={mockOnSuccess} />)
const input = screen.getByPlaceholderText('Enter access token')
fireEvent.change(input, { target: { value: 'my-token' } })
const authenticateBtn = screen.getByRole('button', { name: /authenticate/i })
fireEvent.click(authenticateBtn)
expect(mockSetAccessToken).toHaveBeenCalledWith('my-token')
expect(mockOnSuccess).toHaveBeenCalled()
})
it('trims whitespace from token', () => {
render(<AuthDialog open={true} onClose={mockOnClose} onSuccess={mockOnSuccess} />)
const input = screen.getByPlaceholderText('Enter access token')
fireEvent.change(input, { target: { value: ' my-token ' } })
const authenticateBtn = screen.getByRole('button', { name: /authenticate/i })
fireEvent.click(authenticateBtn)
expect(mockSetAccessToken).toHaveBeenCalledWith('my-token')
})
it('shows error for empty token submission', () => {
render(<AuthDialog open={true} onClose={mockOnClose} onSuccess={mockOnSuccess} />)
// Token with only whitespace
const input = screen.getByPlaceholderText('Enter access token')
fireEvent.change(input, { target: { value: ' ' } })
// Button should still be disabled for whitespace-only input
const authenticateBtn = screen.getByRole('button', { name: /authenticate/i })
expect(authenticateBtn).toBeDisabled()
})
})
@@ -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()
})
})
})
+48 -56
View File
@@ -1,8 +1,10 @@
/**
* Tests for JobCard component
*
* Note: Job cards are no longer collapsible - details are always visible
*/
import { render, screen, fireEvent } from '@testing-library/react'
import { render, screen } from '@testing-library/react'
import { JobCard } from '../job/JobCard'
import { Job } from '@/lib/api'
import { useAutoMode } from '@/lib/auto-mode'
@@ -63,33 +65,49 @@ describe('JobCard', () => {
expect(screen.getByText('Test Artist - Test Song')).toBeInTheDocument()
})
it('shows job ID in expanded details', () => {
it('shows job ID (details always visible)', () => {
render(<JobCard job={mockJob} onRefresh={mockOnRefresh} />)
// Expand details
fireEvent.click(screen.getByText('Test Artist - Test Song'))
expect(screen.getByText(/Job ID:/)).toBeInTheDocument()
expect(screen.getByText('123')).toBeInTheDocument()
// Details are always visible now (no need to click to expand)
// ID is shown in format: "ID: 123 • date • status"
expect(screen.getByText(/ID:/)).toBeInTheDocument()
expect(screen.getByText(/123/)).toBeInTheDocument()
})
it('shows progress bar for processing jobs', () => {
it('shows job actions (details always visible)', () => {
render(<JobCard job={mockJob} onRefresh={mockOnRefresh} />)
const progressBar = document.querySelector('[style*="width: 50%"]')
expect(progressBar).toBeInTheDocument()
// Actions should be immediately visible
expect(screen.getByTestId('job-actions')).toBeInTheDocument()
})
// Note: Progress bars have been removed from JobCard in favor of a simpler design
it('shows error message for failed jobs', () => {
const failedJob = { ...mockJob, status: 'failed', error_message: 'Something went wrong' }
render(<JobCard job={failedJob} onRefresh={mockOnRefresh} />)
// Expand details
fireEvent.click(screen.getByText('Test Artist - Test Song'))
expect(screen.getByText('Something went wrong')).toBeInTheDocument()
})
// Note: Orange border for interactive jobs removed - uses default slate border now
it('applies green border for complete jobs', () => {
const completeJob = { ...mockJob, status: 'complete' }
const { container } = render(<JobCard job={completeJob} onRefresh={mockOnRefresh} />)
const card = container.firstChild
expect(card).toHaveClass('border-green-500/30')
})
it('applies red border for failed jobs', () => {
const failedJob = { ...mockJob, status: 'failed' }
const { container } = render(<JobCard job={failedJob} onRefresh={mockOnRefresh} />)
const card = container.firstChild
expect(card).toHaveClass('border-red-500/30')
})
describe('when auto-mode is disabled', () => {
beforeEach(() => {
mockUseAutoMode.mockReturnValue({
@@ -98,35 +116,29 @@ describe('JobCard', () => {
})
})
it('shows lyrics review button for awaiting_review status', () => {
const reviewJob = { ...mockJob, status: 'awaiting_review' }
it('shows lyrics review link for awaiting_review status', () => {
const reviewJob = { ...mockJob, status: 'awaiting_review', review_token: 'test-token-123' }
render(<JobCard job={reviewJob} onRefresh={mockOnRefresh} />)
// Expand details
fireEvent.click(screen.getByText('Test Artist - Test Song'))
const reviewLink = screen.getByText('Review Lyrics')
expect(reviewLink).toBeInTheDocument()
expect(reviewLink.closest('a')).toHaveAttribute('href', expect.stringContaining('lyrics.nomadkaraoke.com'))
const href = reviewLink.closest('a')?.getAttribute('href') || ''
expect(href).toContain('gen.nomadkaraoke.com/lyrics')
expect(href).toContain('baseApiUrl=')
expect(href).toContain('reviewToken=test-token-123')
})
it('shows audio search button for awaiting_audio_selection status', () => {
const audioSelectionJob = { ...mockJob, status: 'awaiting_audio_selection' }
render(<JobCard job={audioSelectionJob} onRefresh={mockOnRefresh} />)
// Expand details
fireEvent.click(screen.getByText('Test Artist - Test Song'))
expect(screen.getByRole('button', { name: 'Select Audio Source' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Select Audio' })).toBeInTheDocument()
})
it('shows instrumental selection button for awaiting_instrumental_selection status', () => {
const instrumentalJob = { ...mockJob, status: 'awaiting_instrumental_selection' }
render(<JobCard job={instrumentalJob} onRefresh={mockOnRefresh} />)
// Expand details
fireEvent.click(screen.getByText('Test Artist - Test Song'))
expect(screen.getByRole('button', { name: 'Select Instrumental' })).toBeInTheDocument()
})
})
@@ -143,9 +155,6 @@ describe('JobCard', () => {
const reviewJob = { ...mockJob, status: 'awaiting_review' }
render(<JobCard job={reviewJob} onRefresh={mockOnRefresh} />)
// Expand details
fireEvent.click(screen.getByText('Test Artist - Test Song'))
expect(screen.getByText(/Will auto-accept/)).toBeInTheDocument()
expect(screen.queryByText('Review Lyrics')).not.toBeInTheDocument()
})
@@ -154,9 +163,6 @@ describe('JobCard', () => {
const instrumentalJob = { ...mockJob, status: 'awaiting_instrumental_selection' }
render(<JobCard job={instrumentalJob} onRefresh={mockOnRefresh} />)
// Expand details
fireEvent.click(screen.getByText('Test Artist - Test Song'))
expect(screen.getByText(/Will auto-select clean/)).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Select Instrumental' })).not.toBeInTheDocument()
})
@@ -165,11 +171,8 @@ describe('JobCard', () => {
const audioJob = { ...mockJob, status: 'awaiting_audio_selection' }
render(<JobCard job={audioJob} onRefresh={mockOnRefresh} />)
// Expand details
fireEvent.click(screen.getByText('Test Artist - Test Song'))
expect(screen.getByText(/Will auto-select first/)).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Select Audio Source' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Select Audio' })).not.toBeInTheDocument()
})
it('shows auto-processing indicator when processing', () => {
@@ -181,9 +184,6 @@ describe('JobCard', () => {
const reviewJob = { ...mockJob, status: 'awaiting_review' }
render(<JobCard job={reviewJob} onRefresh={mockOnRefresh} />)
// Expand details
fireEvent.click(screen.getByText('Test Artist - Test Song'))
expect(screen.getByText(/Auto-processing.../)).toBeInTheDocument()
})
})
@@ -192,28 +192,20 @@ describe('JobCard', () => {
const completeJob = { ...mockJob, status: 'complete' }
render(<JobCard job={completeJob} onRefresh={mockOnRefresh} />)
// Expand details
fireEvent.click(screen.getByText('Test Artist - Test Song'))
expect(screen.getByTestId('output-links')).toBeInTheDocument()
})
it('toggles details on click', () => {
render(<JobCard job={mockJob} onRefresh={mockOnRefresh} />)
it('handles unknown artist gracefully', () => {
const noArtistJob = { ...mockJob, artist: undefined }
render(<JobCard job={noArtistJob} onRefresh={mockOnRefresh} />)
// Should not show actions initially
expect(screen.queryByTestId('job-actions')).not.toBeInTheDocument()
expect(screen.getByText('Unknown - Test Song')).toBeInTheDocument()
})
// Click to expand
fireEvent.click(screen.getByText('Test Artist - Test Song'))
it('handles unknown title gracefully', () => {
const noTitleJob = { ...mockJob, title: undefined }
render(<JobCard job={noTitleJob} onRefresh={mockOnRefresh} />)
// Should show actions now
expect(screen.getByTestId('job-actions')).toBeInTheDocument()
// Click to collapse
fireEvent.click(screen.getByText('Test Artist - Test Song'))
// Should hide actions again
expect(screen.queryByTestId('job-actions')).not.toBeInTheDocument()
expect(screen.getByText('Test Artist - Unknown')).toBeInTheDocument()
})
})
@@ -3,9 +3,11 @@
import { useState, useEffect, useMemo } from "react"
import { api, AudioSearchResult } from "@/lib/api"
import { Button } from "@/components/ui/button"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Loader2, Music2, HardDrive, Calendar, Clock, Users, Eye, FileAudio, Disc3, Building2 } from "lucide-react"
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"
import { Loader2, Music2, ChevronDown, ChevronUp } from "lucide-react"
// Version from pyproject.toml (single source of truth)
const APP_VERSION = process.env.NEXT_PUBLIC_APP_VERSION || "0.0.0"
interface AudioSearchDialogProps {
jobId: string
@@ -14,37 +16,127 @@ interface AudioSearchDialogProps {
onSelect: () => void
}
// Category display order and labels
// Extended result type to include all backend fields
interface ExtendedAudioSearchResult extends AudioSearchResult {
channel?: string
view_count?: number
formatted_duration?: string
formatted_size?: string
release_type?: string
label?: string
edition_info?: string
target_file?: string
quality_data?: {
format?: string
bit_depth?: number
sample_rate?: number
bitrate?: number
media?: string
}
}
// Category configuration matching flacfetch
interface CategoryConfig {
name: string
maxDisplay: number
color: string
borderColor: string
}
const CATEGORY_CONFIG: Record<string, CategoryConfig> = {
'TOP SEEDED': { name: 'TOP SEEDED', maxDisplay: 3, color: 'text-amber-400', borderColor: 'border-amber-500/30' },
'HI-RES 24-BIT': { name: 'HI-RES 24-BIT', maxDisplay: 3, color: 'text-purple-400', borderColor: 'border-purple-500/30' },
'STUDIO ALBUMS': { name: 'STUDIO ALBUMS', maxDisplay: 3, color: 'text-blue-400', borderColor: 'border-blue-500/30' },
'SINGLES': { name: 'SINGLES', maxDisplay: 2, color: 'text-cyan-400', borderColor: 'border-cyan-500/30' },
'LIVE VERSIONS': { name: 'LIVE VERSIONS', maxDisplay: 2, color: 'text-pink-400', borderColor: 'border-pink-500/30' },
'COMPILATIONS': { name: 'COMPILATIONS', maxDisplay: 2, color: 'text-teal-400', borderColor: 'border-teal-500/30' },
'VINYL RIPS': { name: 'VINYL RIPS', maxDisplay: 2, color: 'text-orange-400', borderColor: 'border-orange-500/30' },
'YOUTUBE/LOSSY': { name: 'YOUTUBE/LOSSY', maxDisplay: 3, color: 'text-red-400', borderColor: 'border-red-500/30' },
'OTHER': { name: 'OTHER', maxDisplay: 3, color: 'text-slate-400', borderColor: 'border-slate-500/30' },
}
const CATEGORY_ORDER = [
'TOP SEEDED',
'HI-RES 24-BIT',
'STUDIO ALBUMS',
'SINGLES',
'LIVE VERSIONS',
'COMPILATIONS',
'VINYL RIPS',
'YOUTUBE/LOSSY',
'OTHER'
]
const CATEGORY_COLORS: Record<string, string> = {
'TOP SEEDED': 'text-amber-400 border-amber-500/30',
'HI-RES 24-BIT': 'text-purple-400 border-purple-500/30',
'STUDIO ALBUMS': 'text-blue-400 border-blue-500/30',
'LIVE VERSIONS': 'text-pink-400 border-pink-500/30',
'COMPILATIONS': 'text-cyan-400 border-cyan-500/30',
'YOUTUBE/LOSSY': 'text-red-400 border-red-500/30',
'OTHER': 'text-slate-400 border-slate-500/30',
// Categorize a single result based on flacfetch logic
function categorizeResult(result: ExtendedAudioSearchResult): string {
const isLossless = result.is_lossless === true
const is24Bit = result.quality_data?.bit_depth === 24
const seeders = result.seeders ?? 0
const provider = result.provider?.toLowerCase() ?? ''
const releaseType = result.release_type?.toLowerCase() ?? ''
const media = result.quality_data?.media?.toLowerCase() ?? ''
// YouTube and lossy sources
if (provider === 'youtube' || !isLossless) {
return 'YOUTUBE/LOSSY'
}
// Top seeded (50+ seeders, lossless)
if (isLossless && seeders >= 50) {
return 'TOP SEEDED'
}
// Hi-res 24-bit
if (isLossless && is24Bit) {
return 'HI-RES 24-BIT'
}
// Vinyl rips
if (isLossless && media === 'vinyl') {
return 'VINYL RIPS'
}
// Live versions
if (isLossless && (releaseType === 'live album' || releaseType === 'bootleg' || releaseType.includes('live'))) {
return 'LIVE VERSIONS'
}
// Compilations
if (isLossless && (releaseType === 'compilation' || releaseType === 'soundtrack' || releaseType === 'anthology')) {
return 'COMPILATIONS'
}
// Singles/EPs
if (isLossless && (releaseType === 'single' || releaseType === 'ep')) {
return 'SINGLES'
}
// Studio albums
if (isLossless && (releaseType === 'album' || !releaseType)) {
return 'STUDIO ALBUMS'
}
return 'OTHER'
}
export function AudioSearchDialog({ jobId, open, onClose, onSelect }: AudioSearchDialogProps) {
const [results, setResults] = useState<AudioSearchResult[]>([])
const [results, setResults] = useState<ExtendedAudioSearchResult[]>([])
const [isLoading, setIsLoading] = useState(true)
const [isSelecting, setIsSelecting] = useState<number | null>(null)
const [error, setError] = useState("")
const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set())
// Debug: Log component version on mount
useEffect(() => {
console.log(`[AudioSearchDialog] App version: ${APP_VERSION}`)
}, [])
// Load results when dialog opens
useEffect(() => {
if (open) {
console.log(`[AudioSearchDialog v${APP_VERSION}] Dialog opened for job: ${jobId}`)
loadResults()
setExpandedCategories(new Set()) // Reset expanded state
}
}, [open, jobId])
@@ -52,10 +144,13 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect }: AudioSearc
setIsLoading(true)
setError("")
try {
console.log(`[AudioSearchDialog v${APP_VERSION}] Loading results...`)
const data = await api.getAudioSearchResults(jobId)
setResults(data.results || [])
console.log(`[AudioSearchDialog v${APP_VERSION}] Raw API response:`, data)
console.log(`[AudioSearchDialog v${APP_VERSION}] Results count: ${data.results?.length || 0}`)
setResults((data.results || []) as ExtendedAudioSearchResult[])
} catch (err: any) {
console.error("Failed to load search results:", err)
console.error(`[AudioSearchDialog v${APP_VERSION}] Failed to load search results:`, err)
setError(err.message || "Failed to load search results")
} finally {
setIsLoading(false)
@@ -64,32 +159,34 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect }: AudioSearc
// Group results by category
const groupedResults = useMemo(() => {
const groups: Record<string, AudioSearchResult[]> = {}
const groups: Record<string, ExtendedAudioSearchResult[]> = {}
for (const result of results) {
const category = result.category || 'OTHER'
const category = categorizeResult(result)
if (!groups[category]) {
groups[category] = []
}
groups[category].push(result)
}
// Sort categories by predefined order
const sortedGroups: [string, AudioSearchResult[]][] = []
// Sort by category order
const sortedGroups: Array<{ category: string; results: ExtendedAudioSearchResult[]; config: CategoryConfig }> = []
for (const cat of CATEGORY_ORDER) {
if (groups[cat]) {
sortedGroups.push([cat, groups[cat]])
delete groups[cat]
if (groups[cat] && groups[cat].length > 0) {
sortedGroups.push({
category: cat,
results: groups[cat],
config: CATEGORY_CONFIG[cat]
})
}
}
// Add any remaining categories
for (const [cat, items] of Object.entries(groups)) {
sortedGroups.push([cat, items])
}
return sortedGroups
}, [results])
// Count total categories
const totalCategories = groupedResults.length
async function handleSelect(index: number) {
setIsSelecting(index)
setError("")
@@ -105,189 +202,188 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect }: AudioSearc
}
}
function formatDuration(seconds?: number): string {
if (!seconds) return ""
const mins = Math.floor(seconds / 60)
const secs = Math.round(seconds % 60)
return `${mins}:${secs.toString().padStart(2, "0")}`
function toggleCategory(category: string) {
setExpandedCategories(prev => {
const next = new Set(prev)
if (next.has(category)) {
next.delete(category)
} else {
next.add(category)
}
return next
})
}
function formatViews(views?: number): string {
if (!views) return ""
if (views >= 1000000) return `${(views / 1000000).toFixed(1)}M`
if (views >= 1000) return `${(views / 1000).toFixed(1)}K`
return views.toString()
// Get display name - use channel for YouTube, artist for others
function getDisplayName(result: ExtendedAudioSearchResult): string {
if (result.provider === "YouTube" && result.channel) {
return result.channel
}
return result.artist || ""
}
function formatSize(mb?: number): string {
if (!mb) return ""
return `${mb.toFixed(1)} MB`
// Format views/seeders compactly
function formatCount(count?: number): string {
if (!count && count !== 0) return "-"
if (count >= 1000000) return `${(count / 1000000).toFixed(1)}M`
if (count >= 1000) return `${(count / 1000).toFixed(1)}K`
return count.toString()
}
// Format release metadata line
function formatMetadata(result: ExtendedAudioSearchResult): string {
const parts: string[] = []
if (result.release_type) parts.push(result.release_type)
if (result.year) parts.push(result.year.toString())
if (result.label) parts.push(result.label)
if (result.edition_info) parts.push(result.edition_info)
if (result.quality_data?.media) parts.push(result.quality_data.media)
return parts.length > 0 ? `[${parts.join(' / ')}]` : ''
}
// Get quality display string
function formatQuality(result: ExtendedAudioSearchResult): string {
if (result.quality) return result.quality
const qd = result.quality_data
if (!qd) return '-'
const parts: string[] = []
if (qd.format) parts.push(qd.format)
if (qd.bit_depth) parts.push(`${qd.bit_depth}bit`)
if (qd.bitrate) parts.push(`${qd.bitrate}kbps`)
if (qd.media) parts.push(qd.media)
return parts.join(' ') || '-'
}
return (
<Dialog open={open} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="max-w-4xl h-[85vh] flex flex-col bg-slate-900 border-slate-700 p-0">
<DialogHeader className="px-6 pt-6 pb-4 border-b border-slate-800">
<DialogTitle className="text-white text-lg">Select Audio Source</DialogTitle>
<DialogDescription className="text-slate-400">
Found {results.length} results across {groupedResults.length} categories
</DialogDescription>
</DialogHeader>
<DialogContent className="max-w-7xl w-[95vw] max-h-[90vh] flex flex-col bg-slate-900 border-slate-700 !p-0 gap-0 overflow-hidden">
<div className="px-4 py-2.5 border-b border-slate-700 shrink-0 bg-slate-900 flex items-center justify-between">
<DialogTitle className="text-white text-sm font-semibold flex items-center gap-2">
Select Audio Source
<span className="text-[10px] px-1.5 py-0.5 rounded bg-slate-700 text-slate-400 font-mono">v{APP_VERSION}</span>
<span className="text-slate-400 font-normal text-xs">
({results.length} results across {totalCategories} categories)
</span>
</DialogTitle>
</div>
{error && (
<div className="px-4 py-2 text-xs text-red-400 bg-red-500/10 border-b border-slate-800">
{error}
</div>
)}
{isLoading ? (
<div className="flex-1 flex items-center justify-center">
<Loader2 className="w-6 h-6 animate-spin text-slate-400" />
<span className="ml-2 text-slate-400">Loading search results...</span>
<div className="flex-1 flex items-center justify-center py-12">
<Loader2 className="w-5 h-5 animate-spin text-slate-400" />
<span className="ml-2 text-sm text-slate-400">Loading...</span>
</div>
) : error && results.length === 0 ? (
<div className="flex-1 flex items-center justify-center text-red-400">{error}</div>
) : results.length === 0 ? (
<div className="flex-1 flex flex-col items-center justify-center text-slate-500">
<Music2 className="w-12 h-12 mb-3 opacity-50" />
<p>No audio sources found</p>
<div className="flex-1 flex flex-col items-center justify-center py-12 text-slate-500">
<Music2 className="w-8 h-8 mb-2 opacity-50" />
<p className="text-sm">No audio sources found</p>
</div>
) : (
<ScrollArea className="flex-1 px-6">
<div className="space-y-6 py-4">
{error && (
<div className="text-sm text-red-400 bg-red-500/10 rounded-lg p-3">
{error}
</div>
)}
<div className="flex-1 overflow-y-auto min-h-0 p-4">
{/* Two-column grid on desktop */}
<div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
{groupedResults.map(({ category, results: catResults, config }) => {
const isExpanded = expandedCategories.has(category)
const displayResults = isExpanded ? catResults : catResults.slice(0, config.maxDisplay)
const hiddenCount = catResults.length - config.maxDisplay
const hasMore = hiddenCount > 0
{groupedResults.map(([category, items]) => (
<div key={category} className="space-y-2">
{/* Category Header */}
<div className={`flex items-center gap-2 text-sm font-semibold ${CATEGORY_COLORS[category]?.split(' ')[0] || 'text-slate-400'}`}>
<span>{category}</span>
<span className="text-slate-500 font-normal">({items.length})</span>
</div>
return (
<div key={category} className="border border-slate-700 rounded-lg overflow-hidden bg-slate-800/20">
{/* Category Header */}
<div className={`px-3 py-2 bg-slate-800/70 flex items-center justify-between ${config.color}`}>
<div className="flex items-center gap-2 text-xs font-semibold">
<span>{category}</span>
<span className="text-slate-500 font-normal">({catResults.length})</span>
</div>
{hasMore && (
<button
onClick={() => toggleCategory(category)}
className="text-[10px] text-slate-400 hover:text-white flex items-center gap-1"
>
{isExpanded ? (
<>Show less <ChevronUp className="w-3 h-3" /></>
) : (
<>+{hiddenCount} more <ChevronDown className="w-3 h-3" /></>
)}
</button>
)}
</div>
{/* Results in category */}
<div className="space-y-2">
{items.map((result) => (
<div
key={result.index}
className={`border rounded-lg p-3 hover:bg-slate-800/50 transition-colors ${
CATEGORY_COLORS[category]?.split(' ')[1] || 'border-slate-700'
}`}
>
<div className="flex items-start gap-3">
{/* Index number */}
<div className="text-slate-500 text-sm font-mono w-6 shrink-0 pt-0.5">
{/* Results in category */}
<div className="divide-y divide-slate-700/50">
{displayResults.map((result) => (
<div
key={result.index}
className="px-3 py-1.5 hover:bg-slate-800/50 flex items-center gap-2 text-xs"
>
{/* Index */}
<span className="w-5 text-slate-500 font-mono shrink-0 text-[10px]">
{result.index + 1}.
</div>
</span>
{/* Content */}
<div className="flex-1 min-w-0 space-y-1.5">
{/* Title row */}
<div className="flex items-start gap-2">
{/* Lossless badge */}
{/* Main content - 2 lines */}
<div className="flex-1 min-w-0">
{/* Line 1: badges + artist + title + quality + size + seeders */}
<div className="flex items-center gap-1 flex-wrap">
{result.is_lossless && (
<span className="text-[10px] px-1.5 py-0.5 rounded bg-green-600/20 text-green-400 font-medium shrink-0">
<span className="text-[8px] px-1 py-0.5 rounded bg-green-600/20 text-green-400 font-medium">
LOSSLESS
</span>
)}
{/* Provider badge */}
<span className={`text-[10px] px-1.5 py-0.5 rounded font-medium shrink-0 ${
result.provider === 'RED' ? 'bg-red-600/20 text-red-400' :
result.provider === 'OPS' ? 'bg-blue-600/20 text-blue-400' :
result.provider === 'YouTube' ? 'bg-red-600/20 text-red-400' :
'bg-slate-600/20 text-slate-400'
<span className={`text-[8px] px-1 py-0.5 rounded font-medium ${
result.provider === "YouTube" ? "bg-red-600/20 text-red-400" :
result.provider === "RED" ? "bg-red-600/30 text-red-300" :
result.provider === "OPS" ? "bg-blue-600/20 text-blue-400" :
"bg-slate-600/20 text-slate-400"
}`}>
{result.provider}
</span>
{/* Artist - Title */}
<span className="text-white font-medium">
{result.artist}
<span className="text-green-400 font-medium">{getDisplayName(result)}</span>
<span className="text-slate-500">-</span>
<span className="text-white">{result.title}</span>
<span className={`text-[10px] ${result.is_lossless ? "text-green-400" : "text-slate-400"}`}>
({formatQuality(result)})
</span>
<span className="text-slate-400">-</span>
<span className="text-white">
{result.title}
</span>
</div>
{/* Album/Release info row */}
{(result.album || result.release_type) && (
<div className="flex items-center gap-1 text-xs">
<span className="text-slate-500">[</span>
{result.release_type && (
<span className="text-cyan-400">{result.release_type}</span>
)}
{result.release_type && result.year && (
<span className="text-slate-500">/</span>
)}
{result.year && (
<span className="text-yellow-400">{result.year}</span>
)}
{(result.release_type || result.year) && result.label && (
<span className="text-slate-500">/</span>
)}
{result.label && (
<span className="text-slate-400 truncate max-w-[200px]">{result.label}</span>
)}
<span className="text-slate-500">]</span>
{result.album && (
<>
<span className="text-slate-500 ml-1">-</span>
<span className="text-slate-300 truncate">{result.album}</span>
</>
)}
</div>
)}
{/* Technical details row */}
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-slate-400">
{/* Quality */}
{result.quality && (
<span className={`px-1.5 py-0.5 rounded ${
result.is_lossless ? "bg-green-600/20 text-green-400" : "bg-slate-600/30 text-slate-400"
}`}>
{result.quality}
</span>
)}
{/* Duration */}
{result.duration && (
<span className="flex items-center gap-1">
<Clock className="w-3 h-3" />
{formatDuration(result.duration)}
</span>
)}
{/* File size */}
{result.size_mb && (
<span className="flex items-center gap-1">
<FileAudio className="w-3 h-3" />
{formatSize(result.size_mb)}
</span>
)}
{/* Seeders (for torrents) */}
{result.seeders !== undefined && (
<span className={`flex items-center gap-1 ${
<span className="text-[10px] text-slate-400">{result.formatted_size || '-'}</span>
{result.seeders !== undefined && result.seeders !== null ? (
<span className={`text-[10px] ${
result.seeders >= 50 ? 'text-green-400' :
result.seeders >= 10 ? 'text-yellow-400' :
'text-red-400'
}`}>
<Users className="w-3 h-3" />
{result.seeders} seeders
{result.seeders} seed
</span>
)}
{/* Views (for YouTube) */}
{result.views && (
<span className="flex items-center gap-1 text-slate-400">
<Eye className="w-3 h-3" />
{formatViews(result.views)} views
) : result.view_count !== undefined ? (
<span className={`text-[10px] ${
result.view_count >= 1000000 ? 'text-green-400' :
result.view_count >= 10000 ? 'text-yellow-400' :
'text-slate-400'
}`}>
{formatCount(result.view_count)} views
</span>
)}
) : null}
</div>
{/* Filename row */}
{result.filename && (
<div className="text-[11px] text-slate-500 font-mono truncate">
"{result.filename}"
{/* Line 2: metadata + filename */}
{(formatMetadata(result) || result.target_file) && (
<div className="flex items-center gap-1.5 text-[10px] text-slate-500">
{formatMetadata(result) && (
<span className="truncate">{formatMetadata(result)}</span>
)}
{result.target_file && (
<span className="font-mono truncate">"{result.target_file}"</span>
)}
</div>
)}
</div>
@@ -297,7 +393,7 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect }: AudioSearc
size="sm"
onClick={() => handleSelect(result.index)}
disabled={isSelecting !== null}
className="bg-amber-600 hover:bg-amber-500 text-white shrink-0"
className="w-14 h-6 text-[9px] bg-amber-600 hover:bg-amber-500 text-white px-2 shrink-0"
>
{isSelecting === result.index ? (
<Loader2 className="w-3 h-3 animate-spin" />
@@ -306,13 +402,13 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect }: AudioSearc
)}
</Button>
</div>
</div>
))}
))}
</div>
</div>
</div>
))}
)
})}
</div>
</ScrollArea>
</div>
)}
</DialogContent>
</Dialog>
+91
View File
@@ -0,0 +1,91 @@
"use client"
import { useState } from "react"
import { KeyRound } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { setAccessToken } from "@/lib/api"
interface AuthDialogProps {
open: boolean
onClose: () => void
onSuccess: () => void
}
export function AuthDialog({ open, onClose, onSuccess }: AuthDialogProps) {
const [token, setToken] = useState("")
const [error, setError] = useState("")
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (token.trim()) {
setAccessToken(token.trim())
setError("")
setToken("") // Clear token from state for security
onSuccess()
} else {
setError("Please enter a valid token")
}
}
return (
<Dialog open={open} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="sm:max-w-md bg-slate-900 border-slate-700">
<DialogHeader>
<DialogTitle className="text-white flex items-center gap-2">
<KeyRound className="w-5 h-5 text-amber-400" />
Authentication Required
</DialogTitle>
<DialogDescription className="text-slate-400">
Enter your access token to use the Karaoke Generator
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<Input
type="password"
placeholder="Enter access token"
value={token}
onChange={(e) => {
setToken(e.target.value)
setError("")
}}
className="bg-slate-800 border-slate-600 text-white"
autoFocus
/>
{error && (
<p className="text-xs text-red-400 mt-1">{error}</p>
)}
</div>
<div className="flex justify-end gap-2">
<Button
type="button"
variant="ghost"
onClick={onClose}
className="text-slate-400"
>
Cancel
</Button>
<Button
type="submit"
disabled={!token.trim()}
className="bg-amber-600 hover:bg-amber-500"
>
Authenticate
</Button>
</div>
<p className="text-xs text-slate-500 text-center">
Contact an admin to get an access token
</p>
</form>
</DialogContent>
</Dialog>
)
}
+67
View File
@@ -0,0 +1,67 @@
"use client"
import { useState, useEffect } from "react"
import { KeyRound, LogOut } from "lucide-react"
import { Button } from "@/components/ui/button"
import { getAccessToken, clearAccessToken } from "@/lib/api"
import { AuthDialog } from "./AuthDialog"
interface AuthStatusProps {
onAuthChange?: () => void
}
export function AuthStatus({ onAuthChange }: AuthStatusProps) {
const [isAuthenticated, setIsAuthenticated] = useState(false)
const [showAuthDialog, setShowAuthDialog] = useState(false)
useEffect(() => {
setIsAuthenticated(!!getAccessToken())
}, [])
const handleLogout = () => {
clearAccessToken()
setIsAuthenticated(false)
onAuthChange?.()
window.location.reload()
}
const handleAuthSuccess = () => {
setIsAuthenticated(true)
setShowAuthDialog(false)
onAuthChange?.()
window.location.reload()
}
if (isAuthenticated) {
return (
<Button
variant="ghost"
size="sm"
onClick={handleLogout}
className="text-slate-400 hover:text-white"
>
<LogOut className="w-4 h-4 mr-2" />
Logout
</Button>
)
}
return (
<>
<Button
variant="ghost"
size="sm"
onClick={() => setShowAuthDialog(true)}
className="text-amber-400 hover:text-amber-300"
>
<KeyRound className="w-4 h-4 mr-2" />
Login
</Button>
<AuthDialog
open={showAuthDialog}
onClose={() => setShowAuthDialog(false)}
onSuccess={handleAuthSuccess}
/>
</>
)
}
+2
View File
@@ -0,0 +1,2 @@
export { AuthStatus } from "./AuthStatus"
export { AuthDialog } from "./AuthDialog"
+190
View File
@@ -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>
)
}
+47 -43
View File
@@ -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)
@@ -65,16 +65,43 @@ export function JobActions({ job, onRefresh, showLogs, onToggleLogs }: JobAction
return (
<div className="flex flex-wrap gap-2" onClick={(e) => e.stopPropagation()}>
<Button
size="sm"
variant="ghost"
onClick={onToggleLogs}
className="text-xs text-slate-400 hover:text-white"
>
<FileText className="w-3 h-3 mr-1" />
{showLogs ? "Hide" : "Show"} Logs
</Button>
{/* Cancel button first (red) */}
{canCancel && (
<Button
size="sm"
variant="ghost"
onClick={handleCancel}
disabled={isCancelling}
className="text-xs text-red-400 hover:text-red-300"
>
{isCancelling ? (
<Loader2 className="w-3 h-3 mr-1 animate-spin" />
) : (
<XCircle className="w-3 h-3 mr-1" />
)}
Cancel
</Button>
)}
{/* Delete button (red) */}
{canDelete && (
<Button
size="sm"
variant="ghost"
onClick={handleDelete}
disabled={isDeleting}
className="text-xs text-red-400 hover:text-red-300"
>
{isDeleting ? (
<Loader2 className="w-3 h-3 mr-1 animate-spin" />
) : (
<Trash2 className="w-3 h-3 mr-1" />
)}
Delete
</Button>
)}
{/* Retry button */}
{canRetry && (
<Button
size="sm"
@@ -92,39 +119,16 @@ export function JobActions({ job, onRefresh, showLogs, onToggleLogs }: JobAction
</Button>
)}
{canCancel && (
<Button
size="sm"
variant="ghost"
onClick={handleCancel}
disabled={isCancelling}
className="text-xs text-orange-400 hover:text-orange-300"
>
{isCancelling ? (
<Loader2 className="w-3 h-3 mr-1 animate-spin" />
) : (
<XCircle className="w-3 h-3 mr-1" />
)}
Cancel
</Button>
)}
{canDelete && (
<Button
size="sm"
variant="ghost"
onClick={handleDelete}
disabled={isDeleting}
className="text-xs text-red-400 hover:text-red-300"
>
{isDeleting ? (
<Loader2 className="w-3 h-3 mr-1 animate-spin" />
) : (
<Trash2 className="w-3 h-3 mr-1" />
)}
Delete
</Button>
)}
{/* Show/Hide Logs */}
<Button
size="sm"
variant="ghost"
onClick={onToggleLogs}
className="text-xs text-slate-400 hover:text-white"
>
<FileText className="w-3 h-3 mr-1" />
{showLogs ? "Hide" : "Show"} Logs
</Button>
</div>
)
}
+148 -154
View File
@@ -3,55 +3,46 @@
import { useState } from "react"
import { Job } from "@/lib/api"
import { useAutoMode } from "@/lib/auto-mode"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
Loader2, CheckCircle2, XCircle, Clock, AlertCircle,
ChevronDown, ChevronUp, ExternalLink, Zap
} from "lucide-react"
import { Loader2, ExternalLink, Zap } from "lucide-react"
import { JobActions } from "./JobActions"
import { JobLogs } from "./JobLogs"
import { OutputLinks } from "./OutputLinks"
import { InstrumentalSelector } from "./InstrumentalSelector"
import { AudioSearchDialog } from "../audio-search/AudioSearchDialog"
// Status badge styling
const statusConfig: Record<string, { color: string; icon: React.ReactNode; label: string }> = {
pending: { color: "bg-slate-500", icon: <Clock className="w-3 h-3" />, label: "Pending" },
searching_audio: { color: "bg-blue-500", icon: <Loader2 className="w-3 h-3 animate-spin" />, label: "Searching Audio" },
awaiting_audio_selection: { color: "bg-orange-500", icon: <AlertCircle className="w-3 h-3" />, label: "Select Audio" },
downloading: { color: "bg-blue-500", icon: <Loader2 className="w-3 h-3 animate-spin" />, label: "Downloading" },
downloading_audio: { color: "bg-blue-500", icon: <Loader2 className="w-3 h-3 animate-spin" />, label: "Downloading" },
separating_stage1: { color: "bg-purple-500", icon: <Loader2 className="w-3 h-3 animate-spin" />, label: "Separating (1/2)" },
separating_stage2: { color: "bg-purple-500", icon: <Loader2 className="w-3 h-3 animate-spin" />, label: "Separating (2/2)" },
audio_complete: { color: "bg-purple-600", icon: <CheckCircle2 className="w-3 h-3" />, label: "Audio Ready" },
transcribing: { color: "bg-amber-500", icon: <Loader2 className="w-3 h-3 animate-spin" />, label: "Transcribing" },
correcting: { color: "bg-amber-500", icon: <Loader2 className="w-3 h-3 animate-spin" />, label: "Correcting" },
lyrics_complete: { color: "bg-amber-600", icon: <CheckCircle2 className="w-3 h-3" />, label: "Lyrics Ready" },
generating_screens: { color: "bg-cyan-500", icon: <Loader2 className="w-3 h-3 animate-spin" />, label: "Generating Screens" },
awaiting_review: { color: "bg-orange-500", icon: <AlertCircle className="w-3 h-3" />, label: "Awaiting Review" },
in_review: { color: "bg-orange-600", icon: <Loader2 className="w-3 h-3 animate-spin" />, label: "In Review" },
review_complete: { color: "bg-teal-500", icon: <CheckCircle2 className="w-3 h-3" />, label: "Review Complete" },
rendering_video: { color: "bg-indigo-500", icon: <Loader2 className="w-3 h-3 animate-spin" />, label: "Rendering Video" },
awaiting_instrumental_selection: { color: "bg-pink-500", icon: <AlertCircle className="w-3 h-3" />, label: "Select Instrumental" },
instrumental_selected: { color: "bg-pink-600", icon: <CheckCircle2 className="w-3 h-3" />, label: "Instrumental Selected" },
generating_video: { color: "bg-violet-500", icon: <Loader2 className="w-3 h-3 animate-spin" />, label: "Generating Video" },
encoding: { color: "bg-violet-600", icon: <Loader2 className="w-3 h-3 animate-spin" />, label: "Encoding" },
packaging: { color: "bg-violet-700", icon: <Loader2 className="w-3 h-3 animate-spin" />, label: "Packaging" },
uploading: { color: "bg-green-500", icon: <Loader2 className="w-3 h-3 animate-spin" />, label: "Uploading" },
complete: { color: "bg-green-600", icon: <CheckCircle2 className="w-3 h-3" />, label: "Complete" },
failed: { color: "bg-red-600", icon: <XCircle className="w-3 h-3" />, label: "Failed" },
cancelled: { color: "bg-gray-500", icon: <XCircle className="w-3 h-3" />, label: "Cancelled" },
// Status text styling (subtle colored text instead of badges)
const statusConfig: Record<string, { textColor: string; label: string }> = {
pending: { textColor: "text-slate-400", label: "Pending" },
searching_audio: { textColor: "text-blue-400", label: "Searching..." },
awaiting_audio_selection: { textColor: "text-amber-400", label: "Needs audio" },
downloading: { textColor: "text-blue-400", label: "Downloading..." },
downloading_audio: { textColor: "text-blue-400", label: "Downloading..." },
separating_stage1: { textColor: "text-purple-400", label: "Separating 1/2..." },
separating_stage2: { textColor: "text-purple-400", label: "Separating 2/2..." },
audio_complete: { textColor: "text-purple-400", label: "Audio ready" },
transcribing: { textColor: "text-blue-400", label: "Transcribing..." },
correcting: { textColor: "text-blue-400", label: "Correcting..." },
lyrics_complete: { textColor: "text-teal-400", label: "Lyrics ready" },
generating_screens: { textColor: "text-cyan-400", label: "Generating screens..." },
awaiting_review: { textColor: "text-amber-400", label: "Needs review" },
in_review: { textColor: "text-blue-400", label: "In review..." },
review_complete: { textColor: "text-teal-400", label: "Review complete" },
rendering_video: { textColor: "text-indigo-400", label: "Rendering..." },
awaiting_instrumental_selection: { textColor: "text-amber-400", label: "Needs instrumental" },
instrumental_selected: { textColor: "text-pink-400", label: "Instrumental selected" },
generating_video: { textColor: "text-violet-400", label: "Generating video..." },
encoding: { textColor: "text-violet-400", label: "Encoding..." },
packaging: { textColor: "text-violet-400", label: "Packaging..." },
uploading: { textColor: "text-green-400", label: "Uploading..." },
complete: { textColor: "text-green-400", label: "Complete" },
failed: { textColor: "text-red-400", label: "Failed" },
cancelled: { textColor: "text-slate-500", label: "Cancelled" },
}
export function StatusBadge({ status }: { status: string }) {
const config = statusConfig[status] || { color: "bg-gray-500", icon: <Clock className="w-3 h-3" />, label: status }
return (
<Badge className={`${config.color} text-white gap-1`}>
{config.icon}
{config.label}
</Badge>
)
function StatusText({ status }: { status: string }) {
const config = statusConfig[status] || { textColor: "text-slate-400", label: status }
return <span className={config.textColor}>{config.label}</span>
}
interface JobCardProps {
@@ -60,7 +51,6 @@ interface JobCardProps {
}
export function JobCard({ job, onRefresh }: JobCardProps) {
const [showDetails, setShowDetails] = useState(false)
const [showLogs, setShowLogs] = useState(false)
const [showAudioSearch, setShowAudioSearch] = useState(false)
const [showInstrumentalSelector, setShowInstrumentalSelector] = useState(false)
@@ -68,6 +58,7 @@ export function JobCard({ job, onRefresh }: JobCardProps) {
const createdAt = new Date(job.created_at).toLocaleString()
const isInteractive = job.status === "awaiting_review" ||
job.status === "in_review" ||
job.status === "awaiting_instrumental_selection" ||
job.status === "awaiting_audio_selection"
const isComplete = job.status === "complete"
@@ -81,129 +72,132 @@ export function JobCard({ job, onRefresh }: JobCardProps) {
isAutoProcessing(`${job.job_id}-audio`)
)
// Build review URL for awaiting_review status
const getReviewUrl = () => {
const backendUrl = process.env.NEXT_PUBLIC_API_URL || 'https://api.nomadkaraoke.com'
const reviewUiUrl = process.env.NEXT_PUBLIC_REVIEW_UI_URL || 'https://gen.nomadkaraoke.com/lyrics/'
const baseApiUrl = `${backendUrl}/api/review/${job.job_id}`
const encodedApiUrl = encodeURIComponent(baseApiUrl)
let url = `${reviewUiUrl}/?baseApiUrl=${encodedApiUrl}`
if (job.audio_hash) {
url += `&audioHash=${encodeURIComponent(job.audio_hash)}`
}
if (job.review_token) {
url += `&reviewToken=${encodeURIComponent(job.review_token)}`
}
return url
}
// Render primary action button based on status
const renderPrimaryAction = () => {
if (autoModeEnabled && isInteractive) {
return (
<div className="flex items-center gap-1 text-xs text-amber-400">
{isBeingAutoProcessed ? (
<>
<Loader2 className="w-3 h-3 animate-spin" />
Auto-processing...
</>
) : (
<>
<Zap className="w-3 h-3" />
Will auto-{job.status === "awaiting_review" || job.status === "in_review" ? "accept" :
job.status === "awaiting_instrumental_selection" ? "select clean" :
"select first"}
</>
)}
</div>
)
}
if (job.status === "awaiting_review" || job.status === "in_review") {
return (
<a
href={getReviewUrl()}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-xs px-3 py-1.5 rounded bg-blue-600 hover:bg-blue-500 text-white"
>
<ExternalLink className="w-3 h-3" />
Review Lyrics
</a>
)
}
if (job.status === "awaiting_audio_selection") {
return (
<Button
size="sm"
onClick={() => setShowAudioSearch(true)}
className="text-xs h-7 px-3 bg-blue-600 hover:bg-blue-500"
>
Select Audio
</Button>
)
}
if (job.status === "awaiting_instrumental_selection") {
return (
<Button
size="sm"
onClick={() => setShowInstrumentalSelector(true)}
className="text-xs h-7 px-3 bg-blue-600 hover:bg-blue-500"
>
Select Instrumental
</Button>
)
}
return null
}
return (
<div
className={`rounded-lg border p-3 transition-colors
${isInteractive ? "border-orange-500/50 bg-orange-500/5" : "border-slate-700 bg-slate-800/30"}
<div
className={`rounded-lg border p-3 transition-colors border-slate-700 bg-slate-800/30
${isComplete ? "border-green-500/30" : ""}
${isFailed ? "border-red-500/30" : ""}`}
>
<div
className="flex items-start justify-between gap-3 cursor-pointer"
onClick={() => setShowDetails(!showDetails)}
>
<div className="flex-1 min-w-0">
<p className="font-medium text-white truncate">
{job.artist || "Unknown"} - {job.title || "Unknown"}
</p>
<p className="text-xs text-slate-500 mt-1">{createdAt}</p>
{job.progress > 0 && job.progress < 100 && isProcessing && (
<div className="mt-2 h-1 rounded-full bg-slate-700 overflow-hidden">
<div
className="h-full bg-amber-500 transition-all duration-500"
style={{ width: `${job.progress}%` }}
/>
</div>
)}
{/* Header row with title */}
<p className="font-medium text-white truncate">
{job.artist || "Unknown"} - {job.title || "Unknown"}
</p>
{/* Meta row: ID, date, status */}
<p className="text-xs text-slate-500 mt-1">
<span className="text-slate-600">ID:</span> {job.job_id} <span className="text-slate-600">•</span> {createdAt} <span className="text-slate-600">•</span> <StatusText status={job.status} />
</p>
{/* Error message if any */}
{job.error_message && (
<div className="mt-2 text-xs text-red-400 bg-red-500/10 rounded p-2 break-words">
{job.error_message}
</div>
)}
{/* Output links for completed jobs */}
{isComplete && (
<div className="mt-2">
<OutputLinks jobId={job.job_id} />
</div>
)}
{/* Actions row: Cancel/secondary on left, primary action on right */}
<div className="mt-2 flex items-center justify-between">
<div className="flex items-center gap-2">
<StatusBadge status={job.status} />
{showDetails ? (
<ChevronUp className="w-4 h-4 text-slate-400" />
) : (
<ChevronDown className="w-4 h-4 text-slate-400" />
)}
</div>
</div>
{showDetails && (
<div className="mt-3 pt-3 border-t border-slate-700 space-y-3">
<p className="text-xs text-slate-400">
<span className="text-slate-500">Job ID:</span> {job.job_id}
</p>
{job.error_message && (
<div className="text-xs text-red-400 bg-red-500/10 rounded p-2 break-words">
{job.error_message}
</div>
)}
{isInteractive && (
<div className="flex flex-wrap gap-2">
{autoModeEnabled ? (
// Auto-mode indicator
<div className="flex items-center gap-2 text-xs text-amber-400 bg-amber-500/10 px-3 py-1.5 rounded">
{isBeingAutoProcessed ? (
<>
<Loader2 className="w-3 h-3 animate-spin" />
Auto-processing...
</>
) : (
<>
<Zap className="w-3 h-3" />
Will auto-{job.status === "awaiting_review" ? "accept" :
job.status === "awaiting_instrumental_selection" ? "select clean" :
"select first"}
</>
)}
</div>
) : (
<>
{job.status === "awaiting_review" && (
<a
href={`https://lyrics.nomadkaraoke.com/?job=${job.job_id}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-xs px-3 py-1.5 rounded bg-orange-600 hover:bg-orange-500 text-white"
onClick={(e) => e.stopPropagation()}
>
<ExternalLink className="w-3 h-3" />
Review Lyrics
</a>
)}
{job.status === "awaiting_audio_selection" && (
<Button
size="sm"
onClick={(e) => {
e.stopPropagation()
setShowAudioSearch(true)
}}
className="text-xs bg-blue-600 hover:bg-blue-500"
>
Select Audio Source
</Button>
)}
{job.status === "awaiting_instrumental_selection" && (
<Button
size="sm"
onClick={(e) => {
e.stopPropagation()
setShowInstrumentalSelector(true)
}}
className="text-xs bg-pink-600 hover:bg-pink-500"
>
Select Instrumental
</Button>
)}
</>
)}
</div>
)}
{isComplete && (
<OutputLinks jobId={job.job_id} />
)}
<JobActions
job={job}
onRefresh={onRefresh}
<JobActions
job={job}
onRefresh={onRefresh}
showLogs={showLogs}
onToggleLogs={() => setShowLogs(!showLogs)}
/>
</div>
{renderPrimaryAction()}
</div>
{showLogs && (
<JobLogs jobId={job.job_id} />
)}
{/* Expandable logs */}
{showLogs && (
<div className="mt-2">
<JobLogs jobId={job.job_id} />
</div>
)}
+63 -3
View File
@@ -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>
)}
+133
View File
@@ -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>
)
}
+7 -3
View File
@@ -3,6 +3,7 @@
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const Dialog = DialogPrimitive.Root
@@ -32,11 +33,14 @@ const DialogContent = React.forwardRef<
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className="fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg"
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<DialogPrimitive.Close className="absolute right-3 top-2.5 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
@@ -73,7 +77,7 @@ const DialogTitle = React.forwardRef<
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className="text-lg font-semibold leading-none tracking-tight"
className={cn("text-lg font-semibold leading-none tracking-tight", className)}
{...props}
/>
))
+118
View File
@@ -0,0 +1,118 @@
/**
* Example E2E test demonstrating the API fixture system
*
* This test shows how to use the fixture system to run tests against
* mock data instead of a real backend.
*
* Run in recording mode to capture new fixtures:
* RECORD_FIXTURES=true npm run test:e2e -- fixtures-example.spec.ts
*
* Then review and approve fixtures:
* npm run fixtures:review
*/
import { test, expect } from '@playwright/test';
import { setupApiFixtures, setupMocks, setAuthToken } from './fixtures';
test.describe('API Fixtures Example', () => {
test('shows empty state when no jobs exist', async ({ page }) => {
// Set up mock API responses (frontend uses /api/jobs, not /api/v1/jobs)
await setupMocks(page, [
{
method: 'GET',
path: '/api/jobs',
response: { body: [] },
},
]);
// Set auth token before navigating
await setAuthToken(page, 'test-token');
await page.goto('/');
// Verify the empty state message
await expect(page.getByText(/No jobs yet/i)).toBeVisible();
});
test('shows jobs when they exist', async ({ page }) => {
// Set up mock with sample job data (frontend uses /api/jobs)
await setupMocks(page, [
{
method: 'GET',
path: '/api/jobs',
response: {
body: [
{
job_id: 'job-123',
title: 'Test Song',
artist: 'Test Artist',
status: 'completed',
created_at: '2024-01-15T10:00:00Z',
updated_at: '2024-01-15T10:05:00Z',
},
],
},
},
]);
await setAuthToken(page, 'test-token');
await page.goto('/');
// Verify job is displayed
await expect(page.getByText('Test Song')).toBeVisible();
await expect(page.getByText('Test Artist')).toBeVisible();
});
test.skip('shows error when API fails', async ({ page }) => {
// NOTE: Currently the frontend doesn't display API errors visibly
// This test is skipped until error handling UI is added
await setupMocks(page, [
{
method: 'GET',
path: '/api/jobs',
response: {
status: 500,
body: { detail: 'Internal server error' },
},
},
]);
await setAuthToken(page, 'test-token');
await page.goto('/');
// This would require the frontend to display API errors
await expect(page.getByText(/error/i)).toBeVisible();
});
test('shows login prompt when not authenticated', async ({ page }) => {
// No mock needed - just don't set auth token
await page.goto('/');
// Verify login prompt is shown (actual UI text)
await expect(page.getByText(/Authentication Required/i)).toBeVisible();
});
test.skip('records real API responses when RECORD_FIXTURES=true', async ({ page }) => {
// This test only runs in recording mode
// It will capture actual API responses for review
const api = await setupApiFixtures(page, {
testFile: 'fixtures-example.spec.ts',
});
if (!api.isRecording) {
test.skip();
return;
}
await setAuthToken(page, process.env.TEST_ACCESS_TOKEN || 'your-token');
await page.goto('/');
// Perform actions that trigger API calls
await page.waitForLoadState('networkidle');
// Stop recording and show captured fixtures
const fixtures = api.stopRecording();
console.log(`Captured ${fixtures.length} API calls`);
});
});
+162
View File
@@ -0,0 +1,162 @@
# API Fixtures for E2E Testing
This module provides tools for recording and replaying API fixtures to enable deterministic E2E testing without requiring a running backend.
## Overview
The fixture system has two modes:
1. **Recording Mode**: Intercepts real API calls during test runs and saves them for review
2. **Mock Mode**: Replays approved fixtures instead of making real API calls
## Workflow
### Step 1: Record API Responses
Run E2E tests in recording mode to capture real API responses:
```bash
cd frontend
npm run test:e2e:record
```
This will:
- Run all E2E tests against the real backend
- Intercept and save all API calls to `e2e/fixtures/data/recordings/`
- Each session creates a new JSON file with all captured requests
### Step 2: Review and Approve Fixtures
Review each captured fixture before approving it:
```bash
npm run fixtures:review
```
The review CLI will:
- Show each captured request/response pair
- Let you approve, skip, or edit each fixture
- Save approved fixtures to `e2e/fixtures/data/approved/`
For each fixture, you can:
- **Approve (a)**: Save the fixture as-is
- **Edit (e)**: Add a description or notes before approving
- **Skip (s)**: Don't save this fixture
- **Quit (q)**: Exit the review session
### Step 3: Use Fixtures in Tests
Once you have approved fixtures, update your tests to use them:
```typescript
import { test, expect } from '@playwright/test';
import { setupApiFixtures } from './fixtures';
test('shows job list', async ({ page }) => {
// Set up mock server with approved fixtures
const api = await setupApiFixtures(page, {
useApprovedFixtures: true,
});
await page.goto('/');
// Test runs against mock data - no real backend needed
await expect(page.getByText('My Jobs')).toBeVisible();
// Verify all requests were handled
api.assertAllHandled();
});
```
## Test Helper API
### setupApiFixtures(page, options)
Main function for setting up API fixtures in a test.
**Options:**
- `fixtureSet?: string` - Load a named fixture set from `data/sets/`
- `useApprovedFixtures?: boolean` - Load all approved fixtures from `data/approved/`
- `mocks?: Array<{method, path, response}>` - Add inline mock responses
- `testFile?: string` - Test file name (used in recording mode)
**Returns:** `ApiTestContext` with:
- `isRecording: boolean` - Whether in recording mode
- `assertAllHandled()` - Throws if any requests weren't mocked
- `getUnmatchedRequests()` - Returns list of unhandled requests
- `stopRecording()` - Stop recording and return captured fixtures
### Convenience Functions
```typescript
// Quick inline mocks
await setupMocks(page, [
{ method: 'GET', path: '/api/v1/jobs', response: { body: [] } },
]);
// Pre-configured scenarios
await setupAuthenticatedUser(page);
await setupUnauthenticatedUser(page);
// Auth helpers
await setAuthToken(page, 'my-token');
await clearAuthToken(page);
```
## Directory Structure
```
e2e/fixtures/
├── data/
│ ├── recordings/ # Temporary recording sessions (gitignored content)
│ ├── approved/ # Approved fixtures (committed to repo)
│ └── sets/ # Named fixture sets for specific scenarios
├── types.ts # TypeScript interfaces
├── recorder.ts # Recording logic
├── mock-server.ts # Mock server logic
├── test-helper.ts # Test utilities
├── review-cli.ts # CLI for reviewing fixtures
└── index.ts # Module exports
```
## Fixture Format
Each approved fixture is a JSON file:
```json
{
"id": "get-api-v1-jobs",
"description": "GET /api/v1/jobs - List all jobs",
"capturedAt": "2024-01-15T10:30:00.000Z",
"request": {
"method": "GET",
"url": "http://localhost:8000/api/v1/jobs",
"path": "/api/v1/jobs",
"headers": { "authorization": "[REDACTED]" }
},
"response": {
"status": 200,
"statusText": "OK",
"body": []
},
"reviewed": true,
"reviewNotes": "Empty job list for new user"
}
```
## Best Practices
1. **Review every fixture**: Don't blindly approve all recordings. Check that responses are correct and don't contain sensitive data.
2. **Add descriptions**: Edit fixtures to add meaningful descriptions that explain what scenario the fixture represents.
3. **Keep fixtures minimal**: Only approve the fixtures you actually need for tests. Don't capture unnecessary API calls.
4. **Update fixtures when API changes**: If the backend API changes, re-record and review fixtures to ensure tests use correct data.
5. **Use fixture sets for scenarios**: Group related fixtures into sets for complex test scenarios (e.g., "user-with-jobs", "empty-state").
## Environment Variables
- `RECORD_FIXTURES=true` - Enable recording mode
- `NEXT_PUBLIC_API_URL` - Backend API URL (default: http://localhost:8000)
@@ -0,0 +1,3 @@
# This directory contains approved API fixtures
# Each fixture is a JSON file representing a single API request/response pair
# These fixtures are used by the mock server during E2E tests
@@ -0,0 +1,4 @@
# Ignore recording session files (temporary, should be reviewed and approved)
*.json
# But keep the gitkeep
!.gitkeep
@@ -0,0 +1,3 @@
# This directory contains temporary recording sessions
# Recordings are created when running tests with RECORD_FIXTURES=true
# After review, approved fixtures are moved to the 'approved' directory
+27
View File
@@ -0,0 +1,27 @@
/**
* API Fixtures Module
*
* This module provides tools for recording and replaying API fixtures
* to enable deterministic E2E testing without a real backend.
*
* @example Recording mode (capture real API responses):
* ```bash
* RECORD_FIXTURES=true npm run test:e2e
* npm run fixtures:review # Review and approve captured fixtures
* ```
*
* @example Mock mode (use approved fixtures):
* ```typescript
* import { setupApiFixtures } from './fixtures';
*
* test('my test', async ({ page }) => {
* await setupApiFixtures(page, { useApprovedFixtures: true });
* // Test runs against mock data
* });
* ```
*/
export * from './types';
export * from './recorder';
export * from './mock-server';
export * from './test-helper';
+246
View File
@@ -0,0 +1,246 @@
/**
* API Fixture Mock Server
*
* Uses Playwright route interception to replay recorded API fixtures.
* This provides deterministic test behavior without needing a real backend.
*/
import { Page, Route, Request } from '@playwright/test';
import * as fs from 'fs';
import * as path from 'path';
import { ApiFixture, FixtureSet } from './types';
const FIXTURES_DIR = path.join(__dirname, 'data');
// In E2E tests, API calls go through Next.js rewrites to /api/* on the same origin
// So we need to match **/api/** to intercept regardless of host
const API_PATH_PATTERN = '**/api/**';
/**
* Match a request URL path to a fixture pattern
* Supports simple wildcards like /api/v1/jobs/* matching /api/v1/jobs/123
*/
function matchPath(pattern: string, actualPath: string): boolean {
// Exact match
if (pattern === actualPath) return true;
// Wildcard match: /api/v1/jobs/* matches /api/v1/jobs/anything
if (pattern.endsWith('/*')) {
const prefix = pattern.slice(0, -2);
return actualPath.startsWith(prefix) && actualPath.split('/').length === pattern.split('/').length;
}
// Pattern with :param placeholders
const patternParts = pattern.split('/');
const actualParts = actualPath.split('/');
if (patternParts.length !== actualParts.length) return false;
return patternParts.every((part, i) => {
if (part.startsWith(':')) return true; // Matches any value
return part === actualParts[i];
});
}
/**
* Load a fixture set from disk
*/
export function loadFixtureSet(name: string): FixtureSet | null {
const filePath = path.join(FIXTURES_DIR, 'sets', `${name}.json`);
if (!fs.existsSync(filePath)) {
console.warn(`Fixture set not found: ${filePath}`);
return null;
}
const content = fs.readFileSync(filePath, 'utf-8');
return JSON.parse(content) as FixtureSet;
}
/**
* Load all approved fixtures from the approved directory
*/
export function loadApprovedFixtures(): Record<string, ApiFixture> {
const approvedDir = path.join(FIXTURES_DIR, 'approved');
const fixtures: Record<string, ApiFixture> = {};
if (!fs.existsSync(approvedDir)) {
console.warn(`Approved fixtures directory not found: ${approvedDir}`);
return fixtures;
}
const files = fs.readdirSync(approvedDir).filter(f => f.endsWith('.json'));
for (const file of files) {
const content = fs.readFileSync(path.join(approvedDir, file), 'utf-8');
const fixture = JSON.parse(content) as ApiFixture;
// Key by method + path for lookup
const key = `${fixture.request.method}:${fixture.request.path}`;
fixtures[key] = fixture;
}
return fixtures;
}
/**
* API Mock Server class for replaying fixtures in tests
*/
export class ApiMockServer {
private fixtures: Record<string, ApiFixture> = {};
private fixtureSet: FixtureSet | null = null;
private unmatchedRequests: Array<{ method: string; url: string }> = [];
/**
* Load fixtures from a named fixture set
*/
loadFixtureSet(name: string): this {
this.fixtureSet = loadFixtureSet(name);
if (this.fixtureSet) {
for (const [pattern, fixture] of Object.entries(this.fixtureSet.fixtures)) {
this.fixtures[pattern] = fixture;
}
console.log(`📦 Loaded fixture set: ${name} (${Object.keys(this.fixtureSet.fixtures).length} fixtures)`);
}
return this;
}
/**
* Load all approved fixtures
*/
loadApprovedFixtures(): this {
const approved = loadApprovedFixtures();
for (const [key, fixture] of Object.entries(approved)) {
this.fixtures[key] = fixture;
}
console.log(`✅ Loaded ${Object.keys(approved).length} approved fixtures`);
return this;
}
/**
* Add a single fixture manually
*/
addFixture(fixture: ApiFixture): this {
const key = `${fixture.request.method}:${fixture.request.path}`;
this.fixtures[key] = fixture;
return this;
}
/**
* Add an inline fixture for a specific route
*/
mockRoute(
method: string,
path: string,
response: { status?: number; body: any }
): this {
const fixture: ApiFixture = {
id: `inline-${method}-${path.replace(/\//g, '-')}`,
description: `Inline mock for ${method} ${path}`,
capturedAt: new Date().toISOString(),
request: { method, url: path, path },
response: {
status: response.status || 200,
statusText: response.status === 200 ? 'OK' : 'Error',
body: response.body,
},
reviewed: true,
};
this.addFixture(fixture);
return this;
}
/**
* Install the mock server on a Playwright page
*/
async install(page: Page): Promise<void> {
await page.route(API_PATH_PATTERN, async (route: Route, request: Request) => {
const url = request.url();
const method = request.method();
const urlObj = new URL(url);
const urlPath = urlObj.pathname;
// Try exact match first
let fixture = this.fixtures[`${method}:${urlPath}`];
// Then try pattern matching
if (!fixture) {
for (const [pattern, f] of Object.entries(this.fixtures)) {
const [fMethod, fPath] = pattern.includes(':')
? pattern.split(':')
: [f.request.method, pattern];
if (fMethod === method && matchPath(fPath, urlPath)) {
fixture = f;
break;
}
}
}
if (fixture) {
console.log(`🎭 [MOCK] ${method} ${urlPath} -> ${fixture.response.status}`);
await route.fulfill({
status: fixture.response.status,
contentType: 'application/json',
body: JSON.stringify(fixture.response.body),
});
} else {
console.warn(`⚠️ [MOCK] No fixture for ${method} ${urlPath}`);
this.unmatchedRequests.push({ method, url });
// Return a clear error response
await route.fulfill({
status: 501,
contentType: 'application/json',
body: JSON.stringify({
error: 'No fixture available',
message: `No mock fixture found for ${method} ${urlPath}`,
hint: 'Run tests with RECORD_FIXTURES=true to capture this endpoint',
}),
});
}
});
console.log(`🎭 Mock server installed with ${Object.keys(this.fixtures).length} fixtures`);
}
/**
* Get list of requests that had no matching fixture
*/
getUnmatchedRequests(): Array<{ method: string; url: string }> {
return this.unmatchedRequests;
}
/**
* Check if all requests were handled
*/
allRequestsHandled(): boolean {
return this.unmatchedRequests.length === 0;
}
}
/**
* Create a mock server with common test fixtures pre-loaded
*/
export function createMockServer(): ApiMockServer {
return new ApiMockServer();
}
/**
* Quick helper to mock common auth scenarios
*/
export function createAuthenticatedMock(): ApiMockServer {
return new ApiMockServer()
.mockRoute('GET', '/api/v1/me', {
body: { authenticated: true, user: { id: 'test-user' } },
})
.mockRoute('GET', '/api/v1/jobs', {
body: [],
});
}
/**
* Quick helper for unauthenticated scenario
*/
export function createUnauthenticatedMock(): ApiMockServer {
return new ApiMockServer()
.mockRoute('GET', '/api/v1/me', {
status: 401,
body: { detail: 'Not authenticated' },
});
}
+206
View File
@@ -0,0 +1,206 @@
/**
* API Fixture Recorder
*
* Intercepts API calls during E2E tests and records them for review.
* Run with RECORD_FIXTURES=true to capture new fixtures.
*/
import { Page, Route, Request } from '@playwright/test';
import * as fs from 'fs';
import * as path from 'path';
import { ApiFixture, RecordingSession } from './types';
const FIXTURES_DIR = path.join(__dirname, 'data');
// In E2E tests, API calls go through Next.js rewrites to /api/* on the same origin
const API_PATH_PATTERN = '**/api/**';
/**
* Generate a unique ID for a fixture based on method and path
*/
function generateFixtureId(method: string, urlPath: string): string {
const sanitizedPath = urlPath
.replace(/^\/api\/v1\//, '')
.replace(/\//g, '-')
.replace(/[^a-zA-Z0-9-]/g, '_');
return `${method.toLowerCase()}-${sanitizedPath}`;
}
/**
* Extract path and query from URL
*/
function parseUrl(url: string): { path: string; query: Record<string, string> } {
const urlObj = new URL(url);
const query: Record<string, string> = {};
urlObj.searchParams.forEach((value, key) => {
query[key] = value;
});
return {
path: urlObj.pathname,
query: Object.keys(query).length > 0 ? query : undefined as any,
};
}
/**
* Redact sensitive information from headers
*/
function redactHeaders(headers: Record<string, string>): Record<string, string> {
const redacted = { ...headers };
const sensitiveKeys = ['authorization', 'x-access-token', 'cookie', 'set-cookie'];
for (const key of sensitiveKeys) {
if (redacted[key]) {
redacted[key] = '[REDACTED]';
}
}
return redacted;
}
/**
* API Recorder class for capturing API calls during tests
*/
export class ApiRecorder {
private session: RecordingSession;
private isRecording: boolean = false;
private outputFile: string;
constructor(testFile?: string) {
this.session = {
sessionId: `session-${Date.now()}`,
startedAt: new Date().toISOString(),
testFile,
calls: [],
};
this.outputFile = path.join(
FIXTURES_DIR,
'recordings',
`${this.session.sessionId}.json`
);
}
/**
* Start recording API calls for a page
*/
async startRecording(page: Page): Promise<void> {
if (this.isRecording) {
console.warn('Recording already in progress');
return;
}
this.isRecording = true;
// Ensure recordings directory exists
const recordingsDir = path.dirname(this.outputFile);
if (!fs.existsSync(recordingsDir)) {
fs.mkdirSync(recordingsDir, { recursive: true });
}
// Intercept all API calls
await page.route(API_PATH_PATTERN, async (route: Route, request: Request) => {
const url = request.url();
const method = request.method();
const { path: urlPath, query } = parseUrl(url);
console.log(`📡 [RECORDING] ${method} ${urlPath}`);
// Let the request proceed and capture the response
const response = await route.fetch();
const status = response.status();
const statusText = response.statusText();
let body: any;
try {
const text = await response.text();
body = text ? JSON.parse(text) : null;
} catch {
body = await response.text();
}
// Create fixture entry
const fixture: ApiFixture = {
id: generateFixtureId(method, urlPath),
description: `${method} ${urlPath}`,
capturedAt: new Date().toISOString(),
request: {
method,
url,
path: urlPath,
query,
body: request.postDataJSON() || undefined,
headers: redactHeaders(request.headers()),
},
response: {
status,
statusText,
body,
},
reviewed: false,
};
this.session.calls.push(fixture);
// Save after each call for safety
this.saveSession();
// Fulfill with the actual response
await route.fulfill({
status,
headers: response.headers(),
body: typeof body === 'string' ? body : JSON.stringify(body),
});
});
console.log(`🎬 Started recording API calls to ${this.outputFile}`);
}
/**
* Stop recording and save the session
*/
stopRecording(): RecordingSession {
this.isRecording = false;
this.saveSession();
console.log(`🛑 Stopped recording. Captured ${this.session.calls.length} API calls.`);
console.log(`📁 Recording saved to: ${this.outputFile}`);
return this.session;
}
/**
* Save the current session to disk
*/
private saveSession(): void {
fs.writeFileSync(
this.outputFile,
JSON.stringify(this.session, null, 2),
'utf-8'
);
}
/**
* Get all recorded calls
*/
getCalls(): ApiFixture[] {
return this.session.calls;
}
/**
* Get the output file path
*/
getOutputFile(): string {
return this.outputFile;
}
}
/**
* Helper to check if we should record fixtures
*/
export function shouldRecordFixtures(): boolean {
return process.env.RECORD_FIXTURES === 'true';
}
/**
* Create a recorder if in recording mode, otherwise return null
*/
export function createRecorderIfNeeded(testFile?: string): ApiRecorder | null {
if (shouldRecordFixtures()) {
return new ApiRecorder(testFile);
}
return null;
}
+246
View File
@@ -0,0 +1,246 @@
#!/usr/bin/env npx ts-node
/**
* CLI tool for reviewing and approving recorded API fixtures
*
* Usage:
* npx ts-node e2e/fixtures/review-cli.ts
*
* Or add to package.json scripts:
* "fixtures:review": "ts-node e2e/fixtures/review-cli.ts"
*/
import * as fs from 'fs';
import * as path from 'path';
import * as readline from 'readline';
import { ApiFixture, RecordingSession } from './types';
const FIXTURES_DIR = path.join(__dirname, 'data');
const RECORDINGS_DIR = path.join(FIXTURES_DIR, 'recordings');
const APPROVED_DIR = path.join(FIXTURES_DIR, 'approved');
// Ensure directories exist
[FIXTURES_DIR, RECORDINGS_DIR, APPROVED_DIR].forEach((dir) => {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
});
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
function prompt(question: string): Promise<string> {
return new Promise((resolve) => {
rl.question(question, resolve);
});
}
function printFixture(fixture: ApiFixture, index: number, total: number): void {
console.log('\n' + '='.repeat(80));
console.log(`📋 Fixture ${index + 1}/${total}: ${fixture.id}`);
console.log('='.repeat(80));
console.log('\n📤 REQUEST:');
console.log(` Method: ${fixture.request.method}`);
console.log(` Path: ${fixture.request.path}`);
if (fixture.request.query && Object.keys(fixture.request.query).length > 0) {
console.log(` Query: ${JSON.stringify(fixture.request.query)}`);
}
if (fixture.request.body) {
console.log(` Body: ${JSON.stringify(fixture.request.body, null, 2).split('\n').join('\n ')}`);
}
console.log('\n📥 RESPONSE:');
console.log(` Status: ${fixture.response.status} ${fixture.response.statusText}`);
console.log(` Body:`);
const bodyStr = JSON.stringify(fixture.response.body, null, 2);
const lines = bodyStr.split('\n');
if (lines.length > 30) {
// Truncate long responses
console.log(lines.slice(0, 25).map((l) => ` ${l}`).join('\n'));
console.log(` ... (${lines.length - 25} more lines)`);
} else {
console.log(lines.map((l) => ` ${l}`).join('\n'));
}
console.log(`\n⏰ Captured: ${fixture.capturedAt}`);
}
async function reviewFixture(fixture: ApiFixture): Promise<'approve' | 'skip' | 'edit' | 'quit'> {
console.log('\nOptions:');
console.log(' [a] Approve - Save this fixture for use in tests');
console.log(' [s] Skip - Do not approve this fixture');
console.log(' [e] Edit - Add notes/description before approving');
console.log(' [q] Quit - Exit review session');
const answer = await prompt('\nYour choice (a/s/e/q): ');
switch (answer.toLowerCase().trim()) {
case 'a':
return 'approve';
case 's':
return 'skip';
case 'e':
return 'edit';
case 'q':
return 'quit';
default:
console.log('Invalid choice, please try again.');
return reviewFixture(fixture);
}
}
async function editFixture(fixture: ApiFixture): Promise<ApiFixture> {
console.log('\nEditing fixture...');
const description = await prompt(`Description (current: "${fixture.description}"): `);
if (description.trim()) {
fixture.description = description.trim();
}
const notes = await prompt('Review notes (optional): ');
if (notes.trim()) {
fixture.reviewNotes = notes.trim();
}
return fixture;
}
function saveApprovedFixture(fixture: ApiFixture): string {
fixture.reviewed = true;
// Generate filename from fixture ID
const filename = `${fixture.id}.json`;
const filepath = path.join(APPROVED_DIR, filename);
// Check for existing fixture with same ID
if (fs.existsSync(filepath)) {
const timestamp = Date.now();
const backupPath = path.join(APPROVED_DIR, `${fixture.id}.backup-${timestamp}.json`);
fs.renameSync(filepath, backupPath);
console.log(` ⚠️ Existing fixture backed up to: ${path.basename(backupPath)}`);
}
fs.writeFileSync(filepath, JSON.stringify(fixture, null, 2), 'utf-8');
return filepath;
}
async function reviewSession(sessionFile: string): Promise<void> {
const content = fs.readFileSync(sessionFile, 'utf-8');
const session: RecordingSession = JSON.parse(content);
console.log('\n' + '🎬'.repeat(40));
console.log(`\n📁 Reviewing recording session: ${session.sessionId}`);
console.log(` Started: ${session.startedAt}`);
console.log(` Test file: ${session.testFile || 'N/A'}`);
console.log(` Total API calls: ${session.calls.length}`);
console.log('\n' + '🎬'.repeat(40));
let approved = 0;
let skipped = 0;
for (let i = 0; i < session.calls.length; i++) {
let fixture = session.calls[i];
printFixture(fixture, i, session.calls.length);
const action = await reviewFixture(fixture);
switch (action) {
case 'approve':
const savedPath = saveApprovedFixture(fixture);
console.log(` ✅ Approved and saved: ${path.basename(savedPath)}`);
approved++;
break;
case 'edit':
fixture = await editFixture(fixture);
const editedPath = saveApprovedFixture(fixture);
console.log(` ✅ Approved and saved: ${path.basename(editedPath)}`);
approved++;
break;
case 'skip':
console.log(' ⏭️ Skipped');
skipped++;
break;
case 'quit':
console.log('\n👋 Exiting review session...');
console.log(` Approved: ${approved}, Skipped: ${skipped}, Remaining: ${session.calls.length - i}`);
rl.close();
return;
}
}
console.log('\n' + '='.repeat(80));
console.log('📊 Review Summary:');
console.log(` ✅ Approved: ${approved}`);
console.log(` ⏭️ Skipped: ${skipped}`);
console.log('='.repeat(80));
// Ask if user wants to delete the recording
const deleteRecording = await prompt('\nDelete the processed recording file? (y/n): ');
if (deleteRecording.toLowerCase().trim() === 'y') {
fs.unlinkSync(sessionFile);
console.log(' 🗑️ Recording file deleted');
}
rl.close();
}
async function listRecordings(): Promise<string[]> {
if (!fs.existsSync(RECORDINGS_DIR)) {
return [];
}
return fs.readdirSync(RECORDINGS_DIR)
.filter((f) => f.endsWith('.json'))
.map((f) => path.join(RECORDINGS_DIR, f));
}
async function main(): Promise<void> {
console.log('\n🔍 API Fixture Review Tool');
console.log('='.repeat(40));
const recordings = await listRecordings();
if (recordings.length === 0) {
console.log('\n📭 No recordings found to review.');
console.log('\nTo capture new recordings:');
console.log(' RECORD_FIXTURES=true npm run test:e2e');
rl.close();
return;
}
console.log(`\n📁 Found ${recordings.length} recording(s):\n`);
recordings.forEach((file, i) => {
const content = JSON.parse(fs.readFileSync(file, 'utf-8')) as RecordingSession;
console.log(` ${i + 1}. ${path.basename(file)}`);
console.log(` └─ ${content.calls.length} API calls, captured ${content.startedAt}`);
});
const choice = await prompt(`\nSelect recording to review (1-${recordings.length}), or 'q' to quit: `);
if (choice.toLowerCase() === 'q') {
console.log('\n👋 Goodbye!');
rl.close();
return;
}
const index = parseInt(choice, 10) - 1;
if (isNaN(index) || index < 0 || index >= recordings.length) {
console.log('Invalid selection.');
rl.close();
return;
}
await reviewSession(recordings[index]);
}
main().catch((err) => {
console.error('Error:', err);
rl.close();
process.exit(1);
});
+195
View File
@@ -0,0 +1,195 @@
/**
* Test Helper for API Fixtures
*
* Provides a unified interface for tests to work with API fixtures.
* Automatically switches between recording mode and mock mode based on environment.
*
* Usage in tests:
*
* ```typescript
* import { test } from '@playwright/test';
* import { setupApiFixtures } from './fixtures/test-helper';
*
* test('my test', async ({ page }) => {
* const api = await setupApiFixtures(page, {
* fixtureSet: 'authenticated-user', // or use inline mocks
* });
*
* // Test code here...
*
* // Optionally check for unhandled requests
* api.assertAllHandled();
* });
* ```
*/
import { Page } from '@playwright/test';
import { ApiRecorder, shouldRecordFixtures, createRecorderIfNeeded } from './recorder';
import { ApiMockServer, createMockServer } from './mock-server';
import { ApiFixture } from './types';
export interface SetupOptions {
/** Name of fixture set to load */
fixtureSet?: string;
/** Load all approved fixtures */
useApprovedFixtures?: boolean;
/** Additional inline mocks */
mocks?: Array<{
method: string;
path: string;
response: { status?: number; body: any };
}>;
/** Test file name (for recording mode) */
testFile?: string;
}
export interface ApiTestContext {
/** The mock server (if in mock mode) */
mockServer: ApiMockServer | null;
/** The recorder (if in recording mode) */
recorder: ApiRecorder | null;
/** Whether we're in recording mode */
isRecording: boolean;
/** Assert all API requests were handled (mock mode only) */
assertAllHandled: () => void;
/** Get unmatched requests (mock mode only) */
getUnmatchedRequests: () => Array<{ method: string; url: string }>;
/** Stop recording and get results (recording mode only) */
stopRecording: () => ApiFixture[];
}
/**
* Set up API fixtures for a test
*
* In recording mode (RECORD_FIXTURES=true):
* - Intercepts real API calls and records them
* - Saves recordings to fixtures/data/recordings/
*
* In mock mode (default):
* - Intercepts API calls and returns fixture data
* - No real backend requests are made
*/
export async function setupApiFixtures(
page: Page,
options: SetupOptions = {}
): Promise<ApiTestContext> {
const isRecording = shouldRecordFixtures();
if (isRecording) {
// Recording mode: capture real API responses
const recorder = new ApiRecorder(options.testFile);
await recorder.startRecording(page);
return {
mockServer: null,
recorder,
isRecording: true,
assertAllHandled: () => {
// No-op in recording mode
},
getUnmatchedRequests: () => [],
stopRecording: () => {
const session = recorder.stopRecording();
return session.calls;
},
};
}
// Mock mode: replay fixtures
const mockServer = createMockServer();
// Load fixture set if specified
if (options.fixtureSet) {
mockServer.loadFixtureSet(options.fixtureSet);
}
// Load approved fixtures if requested
if (options.useApprovedFixtures) {
mockServer.loadApprovedFixtures();
}
// Add inline mocks
if (options.mocks) {
for (const mock of options.mocks) {
mockServer.mockRoute(mock.method, mock.path, mock.response);
}
}
await mockServer.install(page);
return {
mockServer,
recorder: null,
isRecording: false,
assertAllHandled: () => {
const unmatched = mockServer.getUnmatchedRequests();
if (unmatched.length > 0) {
const details = unmatched
.map((r) => ` - ${r.method} ${r.url}`)
.join('\n');
throw new Error(
`Some API requests had no matching fixture:\n${details}\n\n` +
'Run with RECORD_FIXTURES=true to capture these endpoints.'
);
}
},
getUnmatchedRequests: () => mockServer.getUnmatchedRequests(),
stopRecording: () => [],
};
}
/**
* Convenience function for tests that only need simple inline mocks
*/
export async function setupMocks(
page: Page,
mocks: Array<{
method: string;
path: string;
response: { status?: number; body: any };
}>
): Promise<ApiTestContext> {
return setupApiFixtures(page, { mocks });
}
/**
* Convenience function for authenticated user scenario
*/
export async function setupAuthenticatedUser(page: Page): Promise<ApiTestContext> {
return setupApiFixtures(page, {
mocks: [
{
method: 'GET',
path: '/api/jobs',
response: { body: [] },
},
],
});
}
/**
* Convenience function for unauthenticated user scenario
* Note: The frontend checks localStorage for auth token before making API calls,
* so no mock is needed for the unauthenticated state.
*/
export async function setupUnauthenticatedUser(page: Page): Promise<ApiTestContext> {
return setupApiFixtures(page, { mocks: [] });
}
/**
* Helper to set authentication token in localStorage before page navigation
*/
export async function setAuthToken(page: Page, token: string): Promise<void> {
await page.addInitScript((t) => {
localStorage.setItem('karaoke_access_token', t);
}, token);
}
/**
* Helper to clear authentication token
*/
export async function clearAuthToken(page: Page): Promise<void> {
await page.addInitScript(() => {
localStorage.removeItem('karaoke_access_token');
});
}
+56
View File
@@ -0,0 +1,56 @@
/**
* Types for API fixture recording and playback
*/
export interface ApiFixture {
/** Unique identifier for this fixture */
id: string;
/** Human-readable description of what this fixture represents */
description: string;
/** When this fixture was captured */
capturedAt: string;
/** The request that was made */
request: {
method: string;
url: string;
/** URL path without query string */
path: string;
/** Query parameters */
query?: Record<string, string>;
/** Request body (for POST/PUT/PATCH) */
body?: any;
/** Relevant headers (auth token redacted) */
headers?: Record<string, string>;
};
/** The response received */
response: {
status: number;
statusText: string;
headers?: Record<string, string>;
body: any;
};
/** Optional notes from reviewer */
reviewNotes?: string;
/** Whether this fixture has been reviewed and approved */
reviewed: boolean;
}
export interface RecordingSession {
/** Session identifier */
sessionId: string;
/** When recording started */
startedAt: string;
/** Test file that generated this recording */
testFile?: string;
/** All API calls captured in this session */
calls: ApiFixture[];
}
export interface FixtureSet {
/** Name of this fixture set (e.g., "authenticated-user", "empty-jobs") */
name: string;
/** Description of the scenario this fixture set represents */
description: string;
/** Fixtures in this set, keyed by a route pattern */
fixtures: Record<string, ApiFixture>;
}
+8 -7
View File
@@ -181,9 +181,10 @@ test.describe('Karaoke Generation', () => {
await page.waitForTimeout(2000);
// Check for either success (job appears) or error message
const hasError = await page.locator('.text-red-400').isVisible();
const errorDiv = page.locator('div.text-red-400').first();
const hasError = await errorDiv.isVisible().catch(() => false);
if (hasError) {
const errorText = await page.locator('.text-red-400').textContent();
const errorText = await errorDiv.textContent();
console.log('Search error:', errorText);
}
@@ -232,8 +233,8 @@ test.describe('Karaoke Generation', () => {
await page.waitForTimeout(10000);
// Check for error
const errorLocator = page.locator('.text-red-400');
if (await errorLocator.isVisible()) {
const errorLocator = page.locator('div.text-red-400').first();
if (await errorLocator.isVisible().catch(() => false)) {
const errorText = await errorLocator.textContent();
console.log('Error:', errorText);
@@ -266,8 +267,8 @@ test.describe('Karaoke Generation', () => {
// Take a screenshot of current state
await page.screenshot({ path: 'test-results/job-expanded.png' });
// Look for the Select Audio Source button
const selectAudioBtn = page.getByRole('button', { name: /select audio source/i });
// Look for the Select Audio button
const selectAudioBtn = page.getByRole('button', { name: /select audio/i });
if (await selectAudioBtn.isVisible()) {
console.log('Opening audio selection dialog...');
@@ -318,7 +319,7 @@ test.describe('Karaoke Generation', () => {
console.log('Dialog did not open');
}
} else {
console.log('Select Audio Source button not visible');
console.log('Select Audio button not visible');
await page.screenshot({ path: 'test-results/no-select-button.png' });
}
} else {
@@ -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');
});
@@ -0,0 +1,296 @@
import { test, expect } from '@playwright/test';
/**
* Test to capture a screenshot of the Audio Search Dialog for visual review
*/
test.describe('Audio Search Dialog Screenshot', () => {
test.beforeEach(async ({ page }) => {
// Set the auth token before navigating
const token = process.env.KARAOKE_ACCESS_TOKEN;
if (!token) {
throw new Error('KARAOKE_ACCESS_TOKEN environment variable is required - set in .env.local');
}
// Navigate to the app first
await page.goto('/');
await page.waitForLoadState('networkidle');
// Wait a bit for any dialogs to appear
await page.waitForTimeout(1000);
// Check if auth dialog is visible - try multiple selectors
const authDialog = page.locator('[role="dialog"]').filter({ hasText: /authentication|access token/i });
const authDialogAlt = page.locator('text=Authentication Required').locator('xpath=ancestor::div[contains(@class, "fixed")]');
let authVisible = await authDialog.isVisible().catch(() => false);
if (!authVisible) {
authVisible = await authDialogAlt.isVisible().catch(() => false);
}
// Also check for auth input directly on page
const authInput = page.locator('input[placeholder*="token" i], input[placeholder*="access" i]').first();
if (!authVisible && await authInput.isVisible().catch(() => false)) {
authVisible = true;
}
console.log('Auth dialog visible:', authVisible);
if (authVisible) {
console.log('Auth dialog detected, filling token...');
// Find and fill the token input - try multiple strategies
let tokenInputField = page.locator('input[placeholder*="token" i], input[placeholder*="access" i]').first();
if (!await tokenInputField.isVisible().catch(() => false)) {
tokenInputField = page.locator('[role="dialog"] input').first();
}
if (!await tokenInputField.isVisible().catch(() => false)) {
tokenInputField = page.locator('input').first();
}
await tokenInputField.waitFor({ state: 'visible', timeout: 5000 });
await tokenInputField.click();
await tokenInputField.fill(token);
console.log('Token filled in input');
// Wait a moment for the button to become enabled
await page.waitForTimeout(500);
// Click the save/submit/authenticate button - look for any enabled button nearby
const saveButton = page.locator('button:not([disabled])').filter({ hasText: /save|submit|authenticate|connect/i }).first();
if (await saveButton.isVisible().catch(() => false)) {
console.log('Clicking save button');
await saveButton.click();
} else {
// Try clicking any enabled submit button
const anyButton = page.locator('button[type="submit"]:not([disabled]), button:not([disabled])').first();
console.log('Clicking any enabled button');
await anyButton.click();
}
// Wait for the auth form to disappear
await page.waitForTimeout(1000);
console.log('Auth completed');
} else {
console.log('No auth dialog, setting token in localStorage');
// Set the token in localStorage directly (must match key in lib/api.ts)
await page.evaluate((t) => {
localStorage.setItem('karaoke_access_token', t);
}, token);
await page.reload();
}
await page.waitForLoadState('networkidle');
});
test('capture audio search dialog screenshot', async ({ page }) => {
// Set a larger viewport to see full dialog
await page.setViewportSize({ width: 1920, height: 1080 });
// Wait for the page to fully load
await page.waitForLoadState('networkidle');
// Take screenshot of initial page state
await page.screenshot({
path: 'e2e/screenshots/01-initial-page.png',
fullPage: true
});
// Find a job that's in awaiting_audio_selection state
// First, let's check what jobs are visible
const jobCards = await page.locator('[class*="border"][class*="rounded"]').filter({
has: page.locator('text=/processing|pending|awaiting|completed|failed/i')
}).all();
console.log(`Found ${jobCards.length} job cards`);
// Look for a job with "Select Audio" button - wait a bit for the page to fully load
await page.waitForTimeout(2000);
// Take a debug screenshot
await page.screenshot({
path: 'e2e/screenshots/02-debug-before-button-search.png',
fullPage: true
});
// Log all buttons on the page
const allButtons = await page.locator('button').all();
console.log(`Found ${allButtons.length} buttons on page`);
for (let i = 0; i < Math.min(allButtons.length, 10); i++) {
const text = await allButtons[i].textContent().catch(() => 'N/A');
const visible = await allButtons[i].isVisible().catch(() => false);
console.log(`Button ${i}: "${text?.trim()}" visible=${visible}`);
}
// Try multiple selectors for the Select Audio button (cards are no longer collapsible)
const selectAudioButton = page.locator('button').filter({ hasText: /^Select Audio$/i }).first();
const selectAudioAlt = page.locator('button').filter({ hasText: /Select Audio/i }).first();
const selectByColor = page.locator('button.bg-blue-600, button[class*="blue-600"]').first();
let buttonFound = await selectAudioButton.isVisible().catch(() => false);
console.log('selectAudioButton visible:', buttonFound);
if (!buttonFound) {
buttonFound = await selectAudioAlt.isVisible().catch(() => false);
console.log('selectAudioAlt visible:', buttonFound);
}
if (!buttonFound) {
buttonFound = await selectByColor.isVisible().catch(() => false);
console.log('selectByColor visible:', buttonFound);
}
console.log('Select Audio button found:', buttonFound);
if (buttonFound) {
console.log('Found existing job with Select Audio button');
// Take screenshot before clicking
await page.screenshot({
path: 'e2e/screenshots/03-before-select-audio.png',
fullPage: true
});
// Click the Select Audio button directly (cards are no longer collapsible)
const clickTarget = await selectAudioButton.isVisible().catch(() => false)
? selectAudioButton
: selectAudioAlt;
console.log('Clicking Select Audio button');
await clickTarget.click();
// Wait for dialog to appear
await page.waitForSelector('[role="dialog"]', { timeout: 10000 });
// Wait a bit for results to load
await page.waitForTimeout(2000);
// Take screenshot of the dialog
await page.screenshot({
path: 'e2e/screenshots/04-audio-dialog-full-page.png',
fullPage: true
});
// Also capture just the dialog element
const dialog = page.locator('[role="dialog"]');
await dialog.screenshot({
path: 'e2e/screenshots/05-audio-dialog-element.png'
});
// Log dialog dimensions
const dialogBox = await dialog.boundingBox();
console.log('Dialog bounding box:', dialogBox);
// Log viewport size
const viewport = page.viewportSize();
console.log('Viewport size:', viewport);
// Check if dialog is clipped
if (dialogBox) {
const isClippedTop = dialogBox.y < 0;
const isClippedBottom = dialogBox.y + dialogBox.height > (viewport?.height || 0);
const isClippedLeft = dialogBox.x < 0;
const isClippedRight = dialogBox.x + dialogBox.width > (viewport?.width || 0);
console.log('Dialog clipping status:', {
clippedTop: isClippedTop,
clippedBottom: isClippedBottom,
clippedLeft: isClippedLeft,
clippedRight: isClippedRight,
dialogHeight: dialogBox.height,
dialogWidth: dialogBox.width,
viewportHeight: viewport?.height,
viewportWidth: viewport?.width
});
}
// Check scrollability of the dialog content
const scrollableContent = dialog.locator('[class*="overflow"]').first();
if (await scrollableContent.isVisible().catch(() => false)) {
const scrollInfo = await scrollableContent.evaluate((el) => ({
scrollHeight: el.scrollHeight,
clientHeight: el.clientHeight,
scrollTop: el.scrollTop,
isScrollable: el.scrollHeight > el.clientHeight
}));
console.log('Scroll info:', scrollInfo);
}
} else {
console.log('No Select Audio button found, creating a new job...');
// The form is already visible on the page (not in a dialog)
// Fill in the form - use a song that will return multiple results
const artistInput = page.locator('input').filter({ has: page.locator('..', { hasText: /artist/i }) }).first();
const titleInput = page.locator('input').filter({ has: page.locator('..', { hasText: /title/i }) }).first();
// Try different selectors for artist/title inputs
const artistField = page.locator('input[placeholder*="artist" i], input[name*="artist" i]').first();
const titleField = page.locator('input[placeholder*="title" i], input[name*="title" i]').first();
if (await artistField.isVisible().catch(() => false)) {
await artistField.fill('Radiohead');
await titleField.fill('Creep');
} else {
// Find by label
await page.getByLabel(/artist/i).fill('Radiohead');
await page.getByLabel(/title/i).fill('Creep');
}
await page.screenshot({
path: 'e2e/screenshots/02-filled-form.png',
fullPage: true
});
// Submit the job - look for the orange "Create Karaoke Video" button
await page.locator('button:has-text("Create Karaoke Video"), button:has-text("Create"), button[type="submit"]').first().click();
// Wait for job to be created and transition to audio selection
console.log('Waiting for job to start audio search...');
await page.waitForTimeout(5000);
await page.screenshot({
path: 'e2e/screenshots/03-after-submit.png',
fullPage: true
});
// Now look for Select Audio button - wait up to 60 seconds for audio search to complete
const newSelectButton = page.locator('button').filter({ hasText: /Select Audio/i }).first();
console.log('Waiting for Select Audio button...');
try {
await newSelectButton.waitFor({ state: 'visible', timeout: 60000 });
await page.screenshot({
path: 'e2e/screenshots/04-job-awaiting-selection.png',
fullPage: true
});
// Click it
await newSelectButton.click();
// Wait for dialog
await page.waitForSelector('[role="dialog"]', { timeout: 10000 });
await page.waitForTimeout(2000);
await page.screenshot({
path: 'e2e/screenshots/05-audio-dialog-full-page.png',
fullPage: true
});
const dialog = page.locator('[role="dialog"]');
await dialog.screenshot({
path: 'e2e/screenshots/06-audio-dialog-element.png'
});
const dialogBox = await dialog.boundingBox();
console.log('Dialog bounding box:', dialogBox);
} catch (err) {
console.log('Could not find Select Audio button within timeout');
await page.screenshot({
path: 'e2e/screenshots/05-timeout-state.png',
fullPage: true
});
throw err;
}
}
});
});
+4 -1
View File
@@ -14,7 +14,10 @@ const customJestConfig = {
},
testMatch: [
'**/__tests__/**/*.test.[jt]s?(x)',
'**/?(*.)+(spec|test).[jt]s?(x)'
],
testPathIgnorePatterns: [
'/node_modules/',
'/e2e/', // E2E tests run via Playwright, not Jest
],
collectCoverageFrom: [
'components/**/*.{js,jsx,ts,tsx}',
+59 -1
View File
@@ -2,7 +2,7 @@
* Tests for API client
*/
import { api, ApiError } from "../api"
import { api, ApiError, extractErrorMessage } from "../api"
// Mock fetch globally
global.fetch = jest.fn()
@@ -241,3 +241,61 @@ describe("API Client", () => {
})
})
})
describe("extractErrorMessage", () => {
const fallback = "Default error message"
it("should extract string detail field", () => {
expect(extractErrorMessage({ detail: "Error from detail" }, fallback)).toBe("Error from detail")
})
it("should extract string message field", () => {
expect(extractErrorMessage({ message: "Error from message" }, fallback)).toBe("Error from message")
})
it("should extract string error field", () => {
expect(extractErrorMessage({ error: "Error from error field" }, fallback)).toBe("Error from error field")
})
it("should prefer detail over message", () => {
expect(extractErrorMessage({ detail: "Detail", message: "Message" }, fallback)).toBe("Detail")
})
it("should extract nested detail.message", () => {
expect(extractErrorMessage({ detail: { message: "Nested message" } }, fallback)).toBe("Nested message")
})
it("should extract nested detail.error", () => {
expect(extractErrorMessage({ detail: { error: "Nested error" } }, fallback)).toBe("Nested error")
})
it("should stringify object detail", () => {
const objDetail = { code: "ERR_001", info: "More info" }
expect(extractErrorMessage({ detail: objDetail }, fallback)).toBe(JSON.stringify(objDetail))
})
it("should return fallback for null data", () => {
expect(extractErrorMessage(null, fallback)).toBe(fallback)
})
it("should return fallback for undefined data", () => {
expect(extractErrorMessage(undefined, fallback)).toBe(fallback)
})
it("should return fallback for empty object", () => {
expect(extractErrorMessage({}, fallback)).toBe(fallback)
})
it("should return fallback for numeric detail (not a string)", () => {
// Numbers are not extracted - only strings
expect(extractErrorMessage({ detail: 123 }, fallback)).toBe(fallback)
})
it("should handle [object Object] case that caused the original bug", () => {
// This is the case that caused [object Object] to be displayed
const problematicData = { detail: { some: "object" } }
const result = extractErrorMessage(problematicData, fallback)
expect(result).not.toBe("[object Object]")
expect(result).toBe('{"some":"object"}')
})
})
+96 -8
View File
@@ -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'
@@ -60,6 +62,8 @@ export interface Job {
progress?: number;
message?: string;
}>;
review_token?: string;
audio_hash?: string;
}
export interface UploadJobResponse {
@@ -143,6 +147,26 @@ class ApiError extends Error {
}
}
// Exported for testing
export function extractErrorMessage(data: any, fallback: string): string {
// Handle various error response formats
if (typeof data?.detail === 'string') return data.detail;
if (typeof data?.message === 'string') return data.message;
if (typeof data?.error === 'string') return data.error;
// Handle nested error objects
if (data?.detail?.message) return String(data.detail.message);
if (data?.detail?.error) return String(data.detail.error);
// If detail is an object, try to stringify it meaningfully
if (data?.detail && typeof data.detail === 'object') {
try {
return JSON.stringify(data.detail);
} catch {
return fallback;
}
}
return fallback;
}
async function handleResponse<T>(response: Response): Promise<T> {
if (!response.ok) {
let data;
@@ -152,7 +176,7 @@ async function handleResponse<T>(response: Response): Promise<T> {
data = { detail: response.statusText };
}
throw new ApiError(
data.detail || data.message || 'API request failed',
extractErrorMessage(data, `Request failed with status ${response.status}`),
response.status,
data
);
@@ -198,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));
}
@@ -217,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);
},
@@ -239,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 };
@@ -248,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: {
@@ -257,7 +293,7 @@ export const api = {
},
body: JSON.stringify(body),
});
return handleResponse(response);
},
@@ -365,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 };
@@ -372,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: {
@@ -381,7 +421,7 @@ export const api = {
},
body: JSON.stringify(body),
});
return handleResponse(response);
},
@@ -428,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 };
+55
View File
@@ -0,0 +1,55 @@
"use client"
import { useState, useEffect, useCallback } from "react"
const THEME_STORAGE_KEY = "nomad-karaoke-theme"
export type Theme = "dark" | "light"
export function useTheme() {
const [theme, setThemeState] = useState<Theme>("dark")
const [mounted, setMounted] = useState(false)
// Load theme from localStorage on mount
useEffect(() => {
setMounted(true)
const stored = localStorage.getItem(THEME_STORAGE_KEY) as Theme | null
if (stored === "light" || stored === "dark") {
setThemeState(stored)
applyTheme(stored)
} else {
// Apply default theme to DOM when no valid stored value exists
applyTheme("dark")
}
}, [])
const applyTheme = (newTheme: Theme) => {
const root = document.documentElement
if (newTheme === "light") {
root.classList.add("light")
} else {
root.classList.remove("light")
}
}
const setTheme = useCallback((newTheme: Theme) => {
setThemeState(newTheme)
localStorage.setItem(THEME_STORAGE_KEY, newTheme)
applyTheme(newTheme)
}, [])
const toggleTheme = useCallback(() => {
const newTheme = theme === "dark" ? "light" : "dark"
setTheme(newTheme)
}, [theme, setTheme])
const isDarkMode = theme === "dark"
return {
theme,
setTheme,
toggleTheme,
isDarkMode,
mounted,
}
}
+113
View File
@@ -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;
+21
View File
@@ -1,5 +1,26 @@
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
// Read version from root pyproject.toml (single source of truth)
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const pyprojectPath = path.join(__dirname, '..', 'pyproject.toml');
let appVersion = '0.0.0';
try {
const pyprojectContent = fs.readFileSync(pyprojectPath, 'utf-8');
const versionMatch = pyprojectContent.match(/^version\s*=\s*"([^"]+)"/m);
if (versionMatch) {
appVersion = versionMatch[1];
}
} catch (err) {
console.warn('Could not read version from pyproject.toml:', err.message);
}
/** @type {import('next').NextConfig} */
const nextConfig = {
env: {
NEXT_PUBLIC_APP_VERSION: appVersion,
},
// Only use static export for production builds (not dev)
output: process.env.NODE_ENV === 'production' ? 'export' : undefined,
trailingSlash: true,
+220
View File
@@ -72,10 +72,12 @@
"@types/node": "^22",
"@types/react": "^19",
"@types/react-dom": "^19",
"concurrently": "^9.2.1",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"postcss": "^8.5",
"tailwindcss": "^4.1.9",
"ts-node": "^10.9.2",
"tw-animate-css": "1.3.3",
"typescript": "^5"
}
@@ -625,6 +627,30 @@
"dev": true,
"license": "MIT"
},
"node_modules/@cspotcode/source-map-support": {
"version": "0.8.1",
"resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",
"integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/trace-mapping": "0.3.9"
},
"engines": {
"node": ">=12"
}
},
"node_modules/@cspotcode/source-map-support/node_modules/@jridgewell/trace-mapping": {
"version": "0.3.9",
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz",
"integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/resolve-uri": "^3.0.3",
"@jridgewell/sourcemap-codec": "^1.4.10"
}
},
"node_modules/@date-fns/tz": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@date-fns/tz/-/tz-1.2.0.tgz",
@@ -3434,6 +3460,34 @@
"node": ">= 10"
}
},
"node_modules/@tsconfig/node10": {
"version": "1.0.12",
"resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.12.tgz",
"integrity": "sha512-UCYBaeFvM11aU2y3YPZ//O5Rhj+xKyzy7mvcIoAjASbigy8mHMryP5cK7dgjlz2hWxh1g5pLw084E0a/wlUSFQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@tsconfig/node12": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz",
"integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==",
"dev": true,
"license": "MIT"
},
"node_modules/@tsconfig/node14": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz",
"integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==",
"dev": true,
"license": "MIT"
},
"node_modules/@tsconfig/node16": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz",
"integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/aria-query": {
"version": "5.0.4",
"resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
@@ -3850,6 +3904,13 @@
"node": ">= 8"
}
},
"node_modules/arg": {
"version": "4.1.3",
"resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz",
"integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==",
"dev": true,
"license": "MIT"
},
"node_modules/argparse": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",
@@ -4431,6 +4492,47 @@
"dev": true,
"license": "MIT"
},
"node_modules/concurrently": {
"version": "9.2.1",
"resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.2.1.tgz",
"integrity": "sha512-fsfrO0MxV64Znoy8/l1vVIjjHa29SZyyqPgQBwhiDcaW8wJc2W3XWVOGx4M3oJBnv/zdUZIIp1gDeS98GzP8Ng==",
"dev": true,
"license": "MIT",
"dependencies": {
"chalk": "4.1.2",
"rxjs": "7.8.2",
"shell-quote": "1.8.3",
"supports-color": "8.1.1",
"tree-kill": "1.2.2",
"yargs": "17.7.2"
},
"bin": {
"conc": "dist/bin/concurrently.js",
"concurrently": "dist/bin/concurrently.js"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/open-cli-tools/concurrently?sponsor=1"
}
},
"node_modules/concurrently/node_modules/supports-color": {
"version": "8.1.1",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",
"integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/supports-color?sponsor=1"
}
},
"node_modules/convert-source-map": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
@@ -4460,6 +4562,13 @@
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
"node_modules/create-require": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz",
"integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==",
"dev": true,
"license": "MIT"
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@@ -4828,6 +4937,16 @@
"integrity": "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==",
"license": "MIT"
},
"node_modules/diff": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz",
"integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.3.1"
}
},
"node_modules/diff-sequences": {
"version": "29.6.3",
"resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz",
@@ -7448,6 +7567,13 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/make-error": {
"version": "1.3.6",
"resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz",
"integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==",
"dev": true,
"license": "ISC"
},
"node_modules/makeerror": {
"version": "1.0.12",
"resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz",
@@ -8498,6 +8624,16 @@
"node": ">=10"
}
},
"node_modules/rxjs": {
"version": "7.8.2",
"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz",
"integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"tslib": "^2.1.0"
}
},
"node_modules/safe-regex-test": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.1.0.tgz",
@@ -8657,6 +8793,19 @@
"node": ">=8"
}
},
"node_modules/shell-quote": {
"version": "1.8.3",
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz",
"integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",
@@ -9085,6 +9234,60 @@
"node": ">=12"
}
},
"node_modules/tree-kill": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz",
"integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==",
"dev": true,
"license": "MIT",
"bin": {
"tree-kill": "cli.js"
}
},
"node_modules/ts-node": {
"version": "10.9.2",
"resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz",
"integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@cspotcode/source-map-support": "^0.8.0",
"@tsconfig/node10": "^1.0.7",
"@tsconfig/node12": "^1.0.7",
"@tsconfig/node14": "^1.0.0",
"@tsconfig/node16": "^1.0.2",
"acorn": "^8.4.1",
"acorn-walk": "^8.1.1",
"arg": "^4.1.0",
"create-require": "^1.1.0",
"diff": "^4.0.1",
"make-error": "^1.1.1",
"v8-compile-cache-lib": "^3.0.1",
"yn": "3.1.1"
},
"bin": {
"ts-node": "dist/bin.js",
"ts-node-cwd": "dist/bin-cwd.js",
"ts-node-esm": "dist/bin-esm.js",
"ts-node-script": "dist/bin-script.js",
"ts-node-transpile-only": "dist/bin-transpile.js",
"ts-script": "dist/bin-script-deprecated.js"
},
"peerDependencies": {
"@swc/core": ">=1.2.50",
"@swc/wasm": ">=1.2.50",
"@types/node": "*",
"typescript": ">=2.7"
},
"peerDependenciesMeta": {
"@swc/core": {
"optional": true
},
"@swc/wasm": {
"optional": true
}
}
},
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
@@ -9248,6 +9451,13 @@
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/v8-compile-cache-lib": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz",
"integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==",
"dev": true,
"license": "MIT"
},
"node_modules/v8-to-istanbul": {
"version": "9.3.0",
"resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.3.0.tgz",
@@ -9569,6 +9779,16 @@
"node": ">=12"
}
},
"node_modules/yn": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz",
"integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/yocto-queue": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
+12 -1
View File
@@ -5,15 +5,24 @@
"scripts": {
"build": "next build",
"dev": "next dev",
"dev:with-lyrics": "concurrently -n karaoke,lyrics -c blue,green \"npm run dev\" \"npm run dev:lyrics\"",
"dev:lyrics": "cd ../lyrics_transcriber_temp/lyrics_transcriber/frontend && npm run dev",
"lint": "eslint .",
"start": "next start",
"test": "jest --watch",
"test:unit": "jest --ci --maxWorkers=2",
"test:ci": "jest --ci --coverage --maxWorkers=2",
"test:coverage": "jest --coverage",
"test:e2e": "playwright test",
"test:e2e:ui": "playwright test --ui",
"test:e2e:debug": "playwright test --debug",
"test:e2e:headed": "playwright test --headed"
"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"
},
"dependencies": {
"@hookform/resolvers": "^3.10.0",
@@ -80,10 +89,12 @@
"@types/node": "^22",
"@types/react": "^19",
"@types/react-dom": "^19",
"concurrently": "^9.2.1",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"postcss": "^8.5",
"tailwindcss": "^4.1.9",
"ts-node": "^10.9.2",
"tw-animate-css": "1.3.3",
"typescript": "^5"
}
+93
View File
@@ -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
});
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 604 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 585 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 566 B

-26
View File
@@ -1,26 +0,0 @@
<svg width="180" height="180" viewBox="0 0 180 180" fill="none" xmlns="http://www.w3.org/2000/svg">
<style>
@media (prefers-color-scheme: light) {
.background { fill: black; }
.foreground { fill: white; }
}
@media (prefers-color-scheme: dark) {
.background { fill: white; }
.foreground { fill: black; }
}
</style>
<g clip-path="url(#clip0_7960_43945)">
<rect class="background" width="180" height="180" rx="37" />
<g style="transform: scale(95%); transform-origin: center">
<path class="foreground"
d="M101.141 53H136.632C151.023 53 162.689 64.6662 162.689 79.0573V112.904H148.112V79.0573C148.112 78.7105 148.098 78.3662 148.072 78.0251L112.581 112.898C112.701 112.902 112.821 112.904 112.941 112.904H148.112V126.672H112.941C98.5504 126.672 86.5638 114.891 86.5638 100.5V66.7434H101.141V100.5C101.141 101.15 101.191 101.792 101.289 102.422L137.56 66.7816C137.255 66.7563 136.945 66.7434 136.632 66.7434H101.141V53Z" />
<path class="foreground"
d="M65.2926 124.136L14 66.7372H34.6355L64.7495 100.436V66.7372H80.1365V118.47C80.1365 126.278 70.4953 129.958 65.2926 124.136Z" />
</g>
</g>
<defs>
<clipPath id="clip0_7960_43945">
<rect width="180" height="180" fill="white" />
</clipPath>
</defs>
</svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="45 60 255 135">
<g data-v-70b83f88="" fill="#ff7acc" class="basesvg" transform="translate(48.368003845214844,62.62239074707031)"><g fill-rule="" class="tp-name" transform="translate(0,0)"><g transform="scale(1.4000000000000004)"><g stroke="#ff7acc" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" paint-order="stroke" data-gra-attr="stroke" fill-opacity="0"><path d="M1.4-33.44L1.4 0C31.48 0 3.96 0 34.04 0L34.04-32.64 17.81-32.64 17.81-20.61 1.4-33.44ZM52.21-33.76C42.6-33.76 34.81-25.97 34.81-16.37 34.81-6.76 42.6 1.03 52.21 1.03 61.81 1.03 69.6-6.76 69.6-16.37 69.6-25.97 61.81-33.76 52.21-33.76ZM70.7 0L103.34 0 103.25-33.9 86.93-21.54 70.61-33.9 70.7 0ZM102.34 0C138.2 0 107.52 0 143.56 0L122.95-34.93 102.34 0ZM158.84 0.05C167.84 0.05 175.16-7.27 175.16-16.27 175.16-25.27 167.84-32.64 158.84-32.64L142.52-32.64C142.52 0.75 142.52-33.34 142.52 0.05L158.84 0.05Z" transform="translate(-1.399999976158142, 34.93000030517578)"></path></g><g transform="translate(0,38.959999084472656)"><g stroke="#ff7acc" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" paint-order="stroke" data-gra-attr="stroke" fill="#ff7acc" fill-opacity="0" transform="scale(1.02719)"><path d="M24.43 0L17.67 0 7.98-11.87 7.98 0 2.63 0 2.63-26.64 7.98-26.64 7.98-14.69 17.67-26.64 24.12-26.64 13.13-13.44 24.43 0ZM45.03 0L43.27-5.08 32.66-5.08 30.91 0 25.3 0 34.88-26.68 41.1-26.68 50.68 0 45.03 0ZM34.11-9.35L41.82-9.35 37.97-20.5 34.11-9.35ZM73.19 0L67.01 0 61.13-10.38 58.61-10.38 58.61 0 53.27 0 53.27-26.64 63.27-26.64Q66.36-26.64 68.53-25.55 70.71-24.47 71.8-22.61 72.89-20.76 72.89-18.47L72.89-18.47Q72.89-15.84 71.36-13.72 69.83-11.6 66.82-10.8L66.82-10.8 73.19 0ZM58.61-22.21L58.61-14.39 63.08-14.39Q65.25-14.39 66.32-15.44 67.39-16.49 67.39-18.36L67.39-18.36Q67.39-20.19 66.32-21.2 65.25-22.21 63.08-22.21L63.08-22.21 58.61-22.21ZM94.82 0L93.07-5.08 82.46-5.08 80.7 0 75.09 0 84.67-26.68 90.89-26.68 100.47 0 94.82 0ZM83.91-9.35L91.62-9.35 87.76-20.5 83.91-9.35ZM115.43 0.27Q111.69 0.27 108.56-1.49 105.43-3.24 103.6-6.35 101.76-9.47 101.76-13.4L101.76-13.4Q101.76-17.29 103.6-20.4 105.43-23.51 108.56-25.27 111.69-27.02 115.43-27.02L115.43-27.02Q119.21-27.02 122.32-25.27 125.43-23.51 127.24-20.4 129.05-17.29 129.05-13.4L129.05-13.4Q129.05-9.47 127.24-6.35 125.43-3.24 122.3-1.49 119.17 0.27 115.43 0.27L115.43 0.27ZM115.43-4.5Q117.83-4.5 119.66-5.59 121.5-6.68 122.53-8.7 123.56-10.73 123.56-13.4L123.56-13.4Q123.56-16.07 122.53-18.07 121.5-20.08 119.66-21.15 117.83-22.21 115.43-22.21L115.43-22.21Q113.02-22.21 111.17-21.15 109.32-20.08 108.29-18.07 107.26-16.07 107.26-13.4L107.26-13.4Q107.26-10.73 108.29-8.7 109.32-6.68 111.17-5.59 113.02-4.5 115.43-4.5L115.43-4.5ZM153.82 0L147.06 0 137.37-11.87 137.37 0 132.02 0 132.02-26.64 137.37-26.64 137.37-14.69 147.06-26.64 153.51-26.64 142.52-13.44 153.82 0ZM171.79-22.33L161.67-22.33 161.67-15.65 170.64-15.65 170.64-11.41 161.67-11.41 161.67-4.35 171.79-4.35 171.79 0 156.33 0 156.33-26.68 171.79-26.68 171.79-22.33Z" transform="translate(-2.630000114440918, 27.020000457763672)"></path></g></g></g></g> <g data-gra="path-slogan" fill-rule="" class="tp-slogan" fill="#ffdf6b" transform="translate(5,111.788818359375)"><rect x="0" height="1" y="5.9832000732421875" width="14.278396606445312"></rect> <rect height="1" y="5.9832000732421875" width="14.278396606445312" x="218.985595703125"></rect> <g transform="translate(17.278396606445312,0)"><g transform="scale(1.2800000000000002)"><path d="M10.21-8.38L12.02-8.38L9.68 0L7.70 0L6.13-5.96L4.49 0L2.52 0.01L0.26-8.38L2.06-8.38L3.54-1.87L5.24-8.38L7.12-8.38L8.72-1.91L10.21-8.38ZM18.38-8.38L20.06-8.38L20.06 0L18.38 0L18.38-3.56L14.80-3.56L14.80 0L13.12 0L13.12-8.38L14.80-8.38L14.80-4.93L18.38-4.93L18.38-8.38ZM26.58-7.02L23.40-7.02L23.40-4.92L26.22-4.92L26.22-3.59L23.40-3.59L23.40-1.37L26.58-1.37L26.58 0L21.72 0L21.72-8.39L26.58-8.39L26.58-7.02ZM34.37 0L32.42 0L30.58-3.26L29.78-3.26L29.78 0L28.10 0L28.10-8.38L31.25-8.38Q32.22-8.38 32.90-8.03Q33.59-7.69 33.93-7.11Q34.27-6.53 34.27-5.81L34.27-5.81Q34.27-4.98 33.79-4.31Q33.31-3.65 32.36-3.40L32.36-3.40L34.37 0ZM29.78-6.98L29.78-4.52L31.19-4.52Q31.87-4.52 32.21-4.85Q32.54-5.18 32.54-5.77L32.54-5.77Q32.54-6.35 32.21-6.67Q31.87-6.98 31.19-6.98L31.19-6.98L29.78-6.98ZM40.66-7.02L37.48-7.02L37.48-4.92L40.30-4.92L40.30-3.59L37.48-3.59L37.48-1.37L40.66-1.37L40.66 0L35.80 0L35.80-8.39L40.66-8.39L40.66-7.02ZM47.92-8.38L49.70-8.38L46.63 0L44.59 0L41.52-8.38L43.32-8.38L45.62-1.72L47.92-8.38ZM55.57-7.02L52.39-7.02L52.39-4.92L55.21-4.92L55.21-3.59L52.39-3.59L52.39-1.37L55.57-1.37L55.57 0L50.71 0L50.71-8.39L55.57-8.39L55.57-7.02ZM63.36 0L61.42 0L59.57-3.26L58.78-3.26L58.78 0L57.10 0L57.10-8.38L60.24-8.38Q61.21-8.38 61.90-8.03Q62.58-7.69 62.92-7.11Q63.26-6.53 63.26-5.81L63.26-5.81Q63.26-4.98 62.78-4.31Q62.30-3.65 61.36-3.40L61.36-3.40L63.36 0ZM58.78-6.98L58.78-4.52L60.18-4.52Q60.86-4.52 61.20-4.85Q61.54-5.18 61.54-5.77L61.54-5.77Q61.54-6.35 61.20-6.67Q60.86-6.98 60.18-6.98L60.18-6.98L58.78-6.98ZM72.43-8.38L74.30-8.38L71.47-2.92L71.47 0L69.Line truncated
</svg>

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 568 B

-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="215" height="48" fill="none"><path fill="#000" d="M57.588 9.6h6L73.828 38h-5.2l-2.36-6.88h-11.36L52.548 38h-5.2l10.24-28.4Zm7.16 17.16-4.16-12.16-4.16 12.16h8.32Zm23.694-2.24c-.186-1.307-.706-2.32-1.56-3.04-.853-.72-1.866-1.08-3.04-1.08-1.68 0-2.986.613-3.92 1.84-.906 1.227-1.36 2.947-1.36 5.16s.454 3.933 1.36 5.16c.934 1.227 2.24 1.84 3.92 1.84 1.254 0 2.307-.373 3.16-1.12.854-.773 1.387-1.867 1.6-3.28l5.12.24c-.186 1.68-.733 3.147-1.64 4.4-.906 1.227-2.08 2.173-3.52 2.84-1.413.667-2.986 1-4.72 1-2.08 0-3.906-.453-5.48-1.36-1.546-.907-2.76-2.2-3.64-3.88-.853-1.68-1.28-3.627-1.28-5.84 0-2.24.427-4.187 1.28-5.84.88-1.68 2.094-2.973 3.64-3.88 1.574-.907 3.4-1.36 5.48-1.36 1.68 0 3.227.32 4.64.96 1.414.64 2.56 1.56 3.44 2.76.907 1.2 1.454 2.6 1.64 4.2l-5.12.28Zm11.486-7.72.12 3.4c.534-1.227 1.307-2.173 2.32-2.84 1.04-.693 2.267-1.04 3.68-1.04 1.494 0 2.76.387 3.8 1.16 1.067.747 1.827 1.813 2.28 3.2.507-1.44 1.294-2.52 2.36-3.24 1.094-.747 2.414-1.12 3.96-1.12 1.414 0 2.64.307 3.68.92s1.84 1.52 2.4 2.72c.56 1.2.84 2.667.84 4.4V38h-4.96V25.92c0-1.813-.293-3.187-.88-4.12-.56-.96-1.413-1.44-2.56-1.44-.906 0-1.68.213-2.32.64-.64.427-1.133 1.053-1.48 1.88-.32.827-.48 1.84-.48 3.04V38h-4.56V25.92c0-1.2-.133-2.213-.4-3.04-.24-.827-.626-1.453-1.16-1.88-.506-.427-1.133-.64-1.88-.64-.906 0-1.68.227-2.32.68-.64.427-1.133 1.053-1.48 1.88-.32.827-.48 1.827-.48 3V38h-4.96V16.8h4.48Zm26.723 10.6c0-2.24.427-4.187 1.28-5.84.854-1.68 2.067-2.973 3.64-3.88 1.574-.907 3.4-1.36 5.48-1.36 1.84 0 3.494.413 4.96 1.24 1.467.827 2.64 2.08 3.52 3.76.88 1.653 1.347 3.693 1.4 6.12v1.32h-15.08c.107 1.813.614 3.227 1.52 4.24.907.987 2.134 1.48 3.68 1.48.987 0 1.88-.253 2.68-.76a4.803 4.803 0 0 0 1.84-2.2l5.08.36c-.64 2.027-1.84 3.64-3.6 4.84-1.733 1.173-3.733 1.76-6 1.76-2.08 0-3.906-.453-5.48-1.36-1.573-.907-2.786-2.2-3.64-3.88-.853-1.68-1.28-3.627-1.28-5.84Zm15.16-2.04c-.213-1.733-.76-3.013-1.64-3.84-.853-.827-1.893-1.24-3.12-1.24-1.44 0-2.6.453-3.48 1.36-.88.88-1.44 2.12-1.68 3.72h9.92ZM163.139 9.6V38h-5.04V9.6h5.04Zm8.322 7.2.24 5.88-.64-.36c.32-2.053 1.094-3.56 2.32-4.52 1.254-.987 2.787-1.48 4.6-1.48 2.32 0 4.107.733 5.36 2.2 1.254 1.44 1.88 3.387 1.88 5.84V38h-4.96V25.92c0-1.253-.12-2.28-.36-3.08-.24-.8-.64-1.413-1.2-1.84-.533-.427-1.253-.64-2.16-.64-1.44 0-2.573.48-3.4 1.44-.8.933-1.2 2.307-1.2 4.12V38h-4.96V16.8h4.48Zm30.003 7.72c-.186-1.307-.706-2.32-1.56-3.04-.853-.72-1.866-1.08-3.04-1.08-1.68 0-2.986.613-3.92 1.84-.906 1.227-1.36 2.947-1.36 5.16s.454 3.933 1.36 5.16c.934 1.227 2.24 1.84 3.92 1.84 1.254 0 2.307-.373 3.16-1.12.854-.773 1.387-1.867 1.6-3.28l5.12.24c-.186 1.68-.733 3.147-1.64 4.4-.906 1.227-2.08 2.173-3.52 2.84-1.413.667-2.986 1-4.72 1-2.08 0-3.906-.453-5.48-1.36-1.546-.907-2.76-2.2-3.64-3.88-.853-1.68-1.28-3.627-1.28-5.84 0-2.24.427-4.187 1.28-5.84.88-1.68 2.094-2.973 3.64-3.88 1.574-.907 3.4-1.36 5.48-1.36 1.68 0 3.227.32 4.64.96 1.414.64 2.56 1.56 3.44 2.76.907 1.2 1.454 2.6 1.64 4.2l-5.12.28Zm11.443 8.16V38h-5.6v-5.32h5.6Z"/><path fill="#171717" fill-rule="evenodd" d="m7.839 40.783 16.03-28.054L20 6 0 40.783h7.839Zm8.214 0H40L27.99 19.894l-4.02 7.032 3.976 6.914H20.02l-3.967 6.943Z" clip-rule="evenodd"/></svg>

Before

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="1200" fill="none"><rect width="1200" height="1200" fill="#EAEAEA" rx="3"/><g opacity=".5"><g opacity=".5"><path fill="#FAFAFA" d="M600.709 736.5c-75.454 0-136.621-61.167-136.621-136.62 0-75.454 61.167-136.621 136.621-136.621 75.453 0 136.62 61.167 136.62 136.621 0 75.453-61.167 136.62-136.62 136.62Z"/><path stroke="#C9C9C9" stroke-width="2.418" d="M600.709 736.5c-75.454 0-136.621-61.167-136.621-136.62 0-75.454 61.167-136.621 136.621-136.621 75.453 0 136.62 61.167 136.62 136.621 0 75.453-61.167 136.62-136.62 136.62Z"/></g><path stroke="url(#a)" stroke-width="2.418" d="M0-1.209h553.581" transform="scale(1 -1) rotate(45 1163.11 91.165)"/><path stroke="url(#b)" stroke-width="2.418" d="M404.846 598.671h391.726"/><path stroke="url(#c)" stroke-width="2.418" d="M599.5 795.742V404.017"/><path stroke="url(#d)" stroke-width="2.418" d="m795.717 796.597-391.441-391.44"/><path fill="#fff" d="M600.709 656.704c-31.384 0-56.825-25.441-56.825-56.824 0-31.384 25.441-56.825 56.825-56.825 31.383 0 56.824 25.441 56.824 56.825 0 31.383-25.441 56.824-56.824 56.824Z"/><g clip-path="url(#e)"><path fill="#666" fill-rule="evenodd" d="M616.426 586.58h-31.434v16.176l3.553-3.554.531-.531h9.068l.074-.074 8.463-8.463h2.565l7.18 7.181V586.58Zm-15.715 14.654 3.698 3.699 1.283 1.282-2.565 2.565-1.282-1.283-5.2-5.199h-6.066l-5.514 5.514-.073.073v2.876a2.418 2.418 0 0 0 2.418 2.418h26.598a2.418 2.418 0 0 0 2.418-2.418v-8.317l-8.463-8.463-7.181 7.181-.071.072Zm-19.347 5.442v4.085a6.045 6.045 0 0 0 6.046 6.045h26.598a6.044 6.044 0 0 0 6.045-6.045v-7.108l1.356-1.355-1.282-1.283-.074-.073v-17.989h-38.689v23.43l-.146.146.146.147Z" clip-rule="evenodd"/></g><path stroke="#C9C9C9" stroke-width="2.418" d="M600.709 656.704c-31.384 0-56.825-25.441-56.825-56.824 0-31.384 25.441-56.825 56.825-56.825 31.383 0 56.824 25.441 56.824 56.825 0 31.383-25.441 56.824-56.824 56.824Z"/></g><defs><linearGradient id="a" x1="554.061" x2="-.48" y1=".083" y2=".087" gradientUnits="userSpaceOnUse"><stop stop-color="#C9C9C9" stop-opacity="0"/><stop offset=".208" stop-color="#C9C9C9"/><stop offset=".792" stop-color="#C9C9C9"/><stop offset="1" stop-color="#C9C9C9" stop-opacity="0"/></linearGradient><linearGradient id="b" x1="796.912" x2="404.507" y1="599.963" y2="599.965" gradientUnits="userSpaceOnUse"><stop stop-color="#C9C9C9" stop-opacity="0"/><stop offset=".208" stop-color="#C9C9C9"/><stop offset=".792" stop-color="#C9C9C9"/><stop offset="1" stop-color="#C9C9C9" stop-opacity="0"/></linearGradient><linearGradient id="c" x1="600.792" x2="600.794" y1="403.677" y2="796.082" gradientUnits="userSpaceOnUse"><stop stop-color="#C9C9C9" stop-opacity="0"/><stop offset=".208" stop-color="#C9C9C9"/><stop offset=".792" stop-color="#C9C9C9"/><stop offset="1" stop-color="#C9C9C9" stop-opacity="0"/></linearGradient><linearGradient id="d" x1="404.85" x2="796.972" y1="403.903" y2="796.02" gradientUnits="userSpaceOnUse"><stop stop-color="#C9C9C9" stop-opacity="0"/><stop offset=".208" stop-color="#C9C9C9"/><stop offset=".792" stop-color="#C9C9C9"/><stop offset="1" stop-color="#C9C9C9" stop-opacity="0"/></linearGradient><clipPath id="e"><path fill="#fff" d="M581.364 580.535h38.689v38.689h-38.689z"/></clipPath></defs></svg>

Before

Width:  |  Height:  |  Size: 3.2 KiB

+84
View File
@@ -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)
+112
View File
@@ -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 ===")
+14 -25
View File
@@ -364,41 +364,30 @@ 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")
# 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,
generate_plain_text=True,
generate_lrc=True,
generate_cdg=False, # Also defer CDG generation to Phase 2
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=False, # Always defer - caller handles countdown after review
)
# Add this log entry to debug the OutputConfig
+9 -1
View File
@@ -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",
+1 -1
View File
@@ -320,7 +320,7 @@ async def async_main():
# Check if user provided a custom value (not the default hosted URL)
default_hosted_urls = [
'https://gen.nomadkaraoke.com/lyrics',
'https://lyrics.nomadkaraoke.com'
'https://gen.nomadkaraoke.com/lyrics/'
]
if args.review_ui_url.rstrip('/') not in [url.rstrip('/') for url in default_hosted_urls]:
# User explicitly wants a specific URL (e.g., Vite dev server)
+33 -6
View File
@@ -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', [])
@@ -2,6 +2,10 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<!-- Load Inter font to match karaoke-gen styling -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
@@ -9,7 +13,7 @@
<link rel="icon" type="image/png" sizes="192x192" href="/android-chrome-192x192.png" />
<link rel="icon" type="image/png" sizes="512x512" href="/android-chrome-512x512.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Nomad Karaoke: Lyrics Review</title>
<title>Nomad Karaoke: Lyrics Transcription Review</title>
</head>
<body>
<div id="root"></div>
File diff suppressed because it is too large. Load diff
@@ -19,6 +19,7 @@
"@mui/icons-material": "^6.3.0",
"@mui/material": "^6.3.0",
"@mui/system": "^6.4.3",
"lucide-react": "^0.562.0",
"nanoid": "^5.0.9",
"react": "^18.3.1",
"react-dom": "^18.3.1",
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="45 60 255 135">
<g data-v-70b83f88="" fill="#ff7acc" class="basesvg" transform="translate(48.368003845214844,62.62239074707031)"><g fill-rule="" class="tp-name" transform="translate(0,0)"><g transform="scale(1.4000000000000004)"><g stroke="#ff7acc" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" paint-order="stroke" data-gra-attr="stroke" fill-opacity="0"><path d="M1.4-33.44L1.4 0C31.48 0 3.96 0 34.04 0L34.04-32.64 17.81-32.64 17.81-20.61 1.4-33.44ZM52.21-33.76C42.6-33.76 34.81-25.97 34.81-16.37 34.81-6.76 42.6 1.03 52.21 1.03 61.81 1.03 69.6-6.76 69.6-16.37 69.6-25.97 61.81-33.76 52.21-33.76ZM70.7 0L103.34 0 103.25-33.9 86.93-21.54 70.61-33.9 70.7 0ZM102.34 0C138.2 0 107.52 0 143.56 0L122.95-34.93 102.34 0ZM158.84 0.05C167.84 0.05 175.16-7.27 175.16-16.27 175.16-25.27 167.84-32.64 158.84-32.64L142.52-32.64C142.52 0.75 142.52-33.34 142.52 0.05L158.84 0.05Z" transform="translate(-1.399999976158142, 34.93000030517578)"></path></g><g transform="translate(0,38.959999084472656)"><g stroke="#ff7acc" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" paint-order="stroke" data-gra-attr="stroke" fill="#ff7acc" fill-opacity="0" transform="scale(1.02719)"><path d="M24.43 0L17.67 0 7.98-11.87 7.98 0 2.63 0 2.63-26.64 7.98-26.64 7.98-14.69 17.67-26.64 24.12-26.64 13.13-13.44 24.43 0ZM45.03 0L43.27-5.08 32.66-5.08 30.91 0 25.3 0 34.88-26.68 41.1-26.68 50.68 0 45.03 0ZM34.11-9.35L41.82-9.35 37.97-20.5 34.11-9.35ZM73.19 0L67.01 0 61.13-10.38 58.61-10.38 58.61 0 53.27 0 53.27-26.64 63.27-26.64Q66.36-26.64 68.53-25.55 70.71-24.47 71.8-22.61 72.89-20.76 72.89-18.47L72.89-18.47Q72.89-15.84 71.36-13.72 69.83-11.6 66.82-10.8L66.82-10.8 73.19 0ZM58.61-22.21L58.61-14.39 63.08-14.39Q65.25-14.39 66.32-15.44 67.39-16.49 67.39-18.36L67.39-18.36Q67.39-20.19 66.32-21.2 65.25-22.21 63.08-22.21L63.08-22.21 58.61-22.21ZM94.82 0L93.07-5.08 82.46-5.08 80.7 0 75.09 0 84.67-26.68 90.89-26.68 100.47 0 94.82 0ZM83.91-9.35L91.62-9.35 87.76-20.5 83.91-9.35ZM115.43 0.27Q111.69 0.27 108.56-1.49 105.43-3.24 103.6-6.35 101.76-9.47 101.76-13.4L101.76-13.4Q101.76-17.29 103.6-20.4 105.43-23.51 108.56-25.27 111.69-27.02 115.43-27.02L115.43-27.02Q119.21-27.02 122.32-25.27 125.43-23.51 127.24-20.4 129.05-17.29 129.05-13.4L129.05-13.4Q129.05-9.47 127.24-6.35 125.43-3.24 122.3-1.49 119.17 0.27 115.43 0.27L115.43 0.27ZM115.43-4.5Q117.83-4.5 119.66-5.59 121.5-6.68 122.53-8.7 123.56-10.73 123.56-13.4L123.56-13.4Q123.56-16.07 122.53-18.07 121.5-20.08 119.66-21.15 117.83-22.21 115.43-22.21L115.43-22.21Q113.02-22.21 111.17-21.15 109.32-20.08 108.29-18.07 107.26-16.07 107.26-13.4L107.26-13.4Q107.26-10.73 108.29-8.7 109.32-6.68 111.17-5.59 113.02-4.5 115.43-4.5L115.43-4.5ZM153.82 0L147.06 0 137.37-11.87 137.37 0 132.02 0 132.02-26.64 137.37-26.64 137.37-14.69 147.06-26.64 153.51-26.64 142.52-13.44 153.82 0ZM171.79-22.33L161.67-22.33 161.67-15.65 170.64-15.65 170.64-11.41 161.67-11.41 161.67-4.35 171.79-4.35 171.79 0 156.33 0 156.33-26.68 171.79-26.68 171.79-22.33Z" transform="translate(-2.630000114440918, 27.020000457763672)"></path></g></g></g></g> <g data-gra="path-slogan" fill-rule="" class="tp-slogan" fill="#ffdf6b" transform="translate(5,111.788818359375)"><rect x="0" height="1" y="5.9832000732421875" width="14.278396606445312"></rect> <rect height="1" y="5.9832000732421875" width="14.278396606445312" x="218.985595703125"></rect> <g transform="translate(17.278396606445312,0)"><g transform="scale(1.2800000000000002)"><path d="M10.21-8.38L12.02-8.38L9.68 0L7.70 0L6.13-5.96L4.49 0L2.52 0.01L0.26-8.38L2.06-8.38L3.54-1.87L5.24-8.38L7.12-8.38L8.72-1.91L10.21-8.38ZM18.38-8.38L20.06-8.38L20.06 0L18.38 0L18.38-3.56L14.80-3.56L14.80 0L13.12 0L13.12-8.38L14.80-8.38L14.80-4.93L18.38-4.93L18.38-8.38ZM26.58-7.02L23.40-7.02L23.40-4.92L26.22-4.92L26.22-3.59L23.40-3.59L23.40-1.37L26.58-1.37L26.58 0L21.72 0L21.72-8.39L26.58-8.39L26.58-7.02ZM34.37 0L32.42 0L30.58-3.26L29.78-3.26L29.78 0L28.10 0L28.10-8.38L31.25-8.38Q32.22-8.38 32.90-8.03Q33.59-7.69 33.93-7.11Q34.27-6.53 34.27-5.81L34.27-5.81Q34.27-4.98 33.79-4.31Q33.31-3.65 32.36-3.40L32.36-3.40L34.37 0ZM29.78-6.98L29.78-4.52L31.19-4.52Q31.87-4.52 32.21-4.85Q32.54-5.18 32.54-5.77L32.54-5.77Q32.54-6.35 32.21-6.67Q31.87-6.98 31.19-6.98L31.19-6.98L29.78-6.98ZM40.66-7.02L37.48-7.02L37.48-4.92L40.30-4.92L40.30-3.59L37.48-3.59L37.48-1.37L40.66-1.37L40.66 0L35.80 0L35.80-8.39L40.66-8.39L40.66-7.02ZM47.92-8.38L49.70-8.38L46.63 0L44.59 0L41.52-8.38L43.32-8.38L45.62-1.72L47.92-8.38ZM55.57-7.02L52.39-7.02L52.39-4.92L55.21-4.92L55.21-3.59L52.39-3.59L52.39-1.37L55.57-1.37L55.57 0L50.71 0L50.71-8.39L55.57-8.39L55.57-7.02ZM63.36 0L61.42 0L59.57-3.26L58.78-3.26L58.78 0L57.10 0L57.10-8.38L60.24-8.38Q61.21-8.38 61.90-8.03Q62.58-7.69 62.92-7.11Q63.26-6.53 63.26-5.81L63.26-5.81Q63.26-4.98 62.78-4.31Q62.30-3.65 61.36-3.40L61.36-3.40L63.36 0ZM58.78-6.98L58.78-4.52L60.18-4.52Q60.86-4.52 61.20-4.85Q61.54-5.18 61.54-5.77L61.54-5.77Q61.54-6.35 61.20-6.67Q60.86-6.98 60.18-6.98L60.18-6.98L58.78-6.98ZM72.43-8.38L74.30-8.38L71.47-2.92L71.47 0L69.Line truncated
</svg>

After

Width:  |  Height:  |  Size: 9.0 KiB

@@ -1,12 +1,23 @@
import UploadFileIcon from '@mui/icons-material/UploadFile'
import { Alert, Box, Button, Modal, Typography } from '@mui/material'
import { useEffect, useState } from 'react'
import { ThemeProvider } from '@mui/material/styles'
import CssBaseline from '@mui/material/CssBaseline'
import { useEffect, useState, useMemo } from 'react'
import { ApiClient, FileOnlyClient, LiveApiClient } from './api'
import CorrectionMetrics from './components/CorrectionMetrics'
import LyricsAnalyzer from './components/LyricsAnalyzer'
import AppHeader from './components/AppHeader'
import { CorrectionData } from './types'
import { createAppTheme } from './theme'
const THEME_STORAGE_KEY = 'nomad-karaoke-lyrics-theme'
export default function App() {
const [isDarkMode, setIsDarkMode] = useState(() => {
// Initialize from localStorage
const stored = localStorage.getItem(THEME_STORAGE_KEY)
return stored !== 'light' // Default to dark
})
const [data, setData] = useState<CorrectionData | null>(null)
const [showMetadata, setShowMetadata] = useState(false)
const [error, setError] = useState<string | null>(null)
@@ -14,6 +25,16 @@ export default function App() {
const [isReadOnly, setIsReadOnly] = useState(true)
const [audioHash, setAudioHash] = useState<string>('')
// Create theme based on mode
const theme = useMemo(() => createAppTheme(isDarkMode ? 'dark' : 'light'), [isDarkMode])
// Handle theme toggle
const handleToggleTheme = () => {
const newIsDark = !isDarkMode
setIsDarkMode(newIsDark)
localStorage.setItem(THEME_STORAGE_KEY, newIsDark ? 'dark' : 'light')
}
useEffect(() => {
// Parse query parameters
const params = new URLSearchParams(window.location.search)
@@ -145,70 +166,78 @@ export default function App() {
if (!data) {
return (
<Box sx={{ p: 3 }}>
{error && (
<Alert severity="error" sx={{ mb: 2 }} onClose={() => setError(null)}>
{error}
</Alert>
)}
{isReadOnly ? (
<>
<Alert severity="info" sx={{ mb: 2 }}>
Running in read-only mode. Connect to an API to enable editing.
<ThemeProvider theme={theme}>
<CssBaseline />
<AppHeader isDarkMode={isDarkMode} onToggleTheme={handleToggleTheme} />
<Box sx={{ p: 3 }}>
{error && (
<Alert severity="error" sx={{ mb: 2 }} onClose={() => setError(null)}>
{error}
</Alert>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
<Typography variant="h4">
Lyrics Correction Review
)}
{isReadOnly ? (
<>
<Alert severity="info" sx={{ mb: 2 }}>
Running in read-only mode. Connect to an API to enable editing.
</Alert>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
<Typography variant="h4">
Lyrics Correction Review
</Typography>
<Button
variant="outlined"
startIcon={<UploadFileIcon />}
onClick={handleFileLoad}
>
Load File
</Button>
</Box>
<Box sx={{ mb: 3 }}>
<CorrectionMetrics />
</Box>
</>
) : (
<Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '50vh' }}>
<Typography variant="h6" color="text.secondary">
Loading Lyrics Transcription Review...
</Typography>
<Button
variant="outlined"
startIcon={<UploadFileIcon />}
onClick={handleFileLoad}
>
Load File
</Button>
</Box>
<Box sx={{ mb: 3 }}>
<CorrectionMetrics />
</Box>
</>
) : (
<Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '50vh' }}>
<Typography variant="h6" color="text.secondary">
Loading Lyrics Correction Review...
</Typography>
</Box>
)}
</Box>
)}
</Box>
</ThemeProvider>
)
}
return (
<Box sx={{
p: 1.5,
pb: 3,
maxWidth: '100%',
overflowX: 'hidden'
}}>
{error && (
<Alert severity="error" sx={{ mb: 1 }} onClose={() => setError(null)}>
{error}
</Alert>
)}
{isReadOnly && (
<Alert severity="info" sx={{ mb: 1 }}>
Running in read-only mode. Connect to an API to enable editing.
</Alert>
)}
<LyricsAnalyzer
data={data}
onFileLoad={handleFileLoad}
onShowMetadata={() => setShowMetadata(true)}
apiClient={apiClient}
isReadOnly={isReadOnly}
audioHash={audioHash}
/>
{renderMetadataModal()}
</Box>
<ThemeProvider theme={theme}>
<CssBaseline />
<AppHeader isDarkMode={isDarkMode} onToggleTheme={handleToggleTheme} />
<Box sx={{
p: 1.5,
pb: 3,
maxWidth: '100%',
overflowX: 'hidden'
}}>
{error && (
<Alert severity="error" sx={{ mb: 1 }} onClose={() => setError(null)}>
{error}
</Alert>
)}
{isReadOnly && (
<Alert severity="info" sx={{ mb: 1 }}>
Running in read-only mode. Connect to an API to enable editing.
</Alert>
)}
<LyricsAnalyzer
data={data}
onFileLoad={handleFileLoad}
onShowMetadata={() => setShowMetadata(true)}
apiClient={apiClient}
isReadOnly={isReadOnly}
audioHash={audioHash}
/>
{renderMetadataModal()}
</Box>
</ThemeProvider>
)
}
@@ -1,4 +1,4 @@
import React from "react";
import React, { useEffect, useRef } from "react";
type Props = {
isOpen: boolean;
@@ -12,22 +12,57 @@ export const AIFeedbackModal: React.FC<Props> = ({ isOpen, onClose, onSubmit, su
const [finalText, setFinalText] = React.useState("");
const [reasonCategory, setReason] = React.useState("AI_CORRECT");
const [reasonDetail, setDetail] = React.useState("");
const modalRef = useRef<HTMLDivElement>(null);
// Handle Escape key to close modal
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape' && isOpen) {
onClose();
}
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [isOpen, onClose]);
// Focus modal on open
useEffect(() => {
if (isOpen && modalRef.current) {
modalRef.current.focus();
}
}, [isOpen]);
if (!isOpen) return null;
// Dark theme colors matching karaoke-gen
const colors = {
background: '#1a1a1a', // slate-800
text: '#f8fafc', // slate-50
textSecondary: '#888888', // slate-400
border: '#2a2a2a', // slate-700
inputBg: '#0f0f0f', // slate-900
};
return (
<div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.5)", display: "flex", alignItems: "center", justifyContent: "center" }}>
<div style={{ background: "#fff", padding: 16, width: 480, borderRadius: 8 }}>
<h3>AI Suggestion</h3>
<p style={{ marginTop: 8 }}>
<div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.7)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 1300 }}>
<div
ref={modalRef}
role="dialog"
aria-modal="true"
aria-labelledby="ai-feedback-title"
tabIndex={-1}
style={{ background: colors.background, padding: 16, width: 480, borderRadius: 8, border: `1px solid ${colors.border}`, color: colors.text, outline: 'none' }}
>
<h3 id="ai-feedback-title" style={{ color: colors.text, margin: 0 }}>AI Suggestion</h3>
<p style={{ marginTop: 8, color: colors.text }}>
{suggestion?.text ?? "No suggestion"}
{suggestion?.confidence != null ? ` (confidence ${Math.round((suggestion.confidence || 0) * 100)}%)` : null}
</p>
{suggestion?.reasoning ? <small>{suggestion.reasoning}</small> : null}
{suggestion?.reasoning ? <small style={{ color: colors.textSecondary }}>{suggestion.reasoning}</small> : null}
<div style={{ marginTop: 12 }}>
<label>Action</label>
<select value={reviewerAction} onChange={(e) => setAction(e.target.value)} style={{ marginLeft: 8 }}>
<div style={{ marginTop: 12, display: 'flex', alignItems: 'center', gap: 8 }}>
<label htmlFor="ai-action-select" style={{ color: colors.text }}>Action</label>
<select id="ai-action-select" value={reviewerAction} onChange={(e) => setAction(e.target.value)} style={{ background: colors.inputBg, color: colors.text, border: `1px solid ${colors.border}`, borderRadius: 4, padding: '4px 8px' }}>
<option value="ACCEPT">Accept</option>
<option value="REJECT">Reject</option>
<option value="MODIFY">Modify</option>
@@ -35,15 +70,15 @@ export const AIFeedbackModal: React.FC<Props> = ({ isOpen, onClose, onSubmit, su
</div>
{reviewerAction === "MODIFY" ? (
<div style={{ marginTop: 12 }}>
<label>Final Text</label>
<input value={finalText} onChange={(e) => setFinalText(e.target.value)} style={{ marginLeft: 8, width: "100%" }} />
<div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 4 }}>
<label htmlFor="ai-final-text" style={{ color: colors.text }}>Final Text</label>
<input id="ai-final-text" value={finalText} onChange={(e) => setFinalText(e.target.value)} style={{ width: "100%", background: colors.inputBg, color: colors.text, border: `1px solid ${colors.border}`, borderRadius: 4, padding: '4px 8px', boxSizing: 'border-box' }} />
</div>
) : null}
<div style={{ marginTop: 12 }}>
<label>Reason</label>
<select value={reasonCategory} onChange={(e) => setReason(e.target.value)} style={{ marginLeft: 8 }}>
<div style={{ marginTop: 12, display: 'flex', alignItems: 'center', gap: 8 }}>
<label htmlFor="ai-reason-select" style={{ color: colors.text }}>Reason</label>
<select id="ai-reason-select" value={reasonCategory} onChange={(e) => setReason(e.target.value)} style={{ background: colors.inputBg, color: colors.text, border: `1px solid ${colors.border}`, borderRadius: 4, padding: '4px 8px' }}>
<option value="AI_CORRECT">AI_CORRECT</option>
<option value="AI_INCORRECT">AI_INCORRECT</option>
<option value="AI_SUBOPTIMAL">AI_SUBOPTIMAL</option>
@@ -52,17 +87,18 @@ export const AIFeedbackModal: React.FC<Props> = ({ isOpen, onClose, onSubmit, su
</select>
</div>
<div style={{ marginTop: 12 }}>
<label>Details</label>
<textarea value={reasonDetail} onChange={(e) => setDetail(e.target.value)} style={{ marginLeft: 8, width: "100%" }} />
<div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 4 }}>
<label htmlFor="ai-details-textarea" style={{ color: colors.text }}>Details</label>
<textarea id="ai-details-textarea" value={reasonDetail} onChange={(e) => setDetail(e.target.value)} style={{ width: "100%", background: colors.inputBg, color: colors.text, border: `1px solid ${colors.border}`, borderRadius: 4, padding: '4px 8px', boxSizing: 'border-box' }} />
</div>
<div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 16 }}>
<button onClick={onClose}>Cancel</button>
<button onClick={onClose} style={{ background: colors.border, color: colors.text, border: 'none', borderRadius: 4, padding: '6px 12px', cursor: 'pointer' }}>Cancel</button>
<button
onClick={() =>
onSubmit({ reviewerAction, finalText: finalText || undefined, reasonCategory, reasonDetail: reasonDetail || undefined })
}
style={{ background: '#f97316', color: '#fff', border: 'none', borderRadius: 4, padding: '6px 12px', cursor: 'pointer' }}
>
Submit
</button>
@@ -73,5 +109,3 @@ export const AIFeedbackModal: React.FC<Props> = ({ isOpen, onClose, onSubmit, su
};
export default AIFeedbackModal;
@@ -0,0 +1,65 @@
import { Box, IconButton, Tooltip, Typography, useTheme } from '@mui/material'
import { Sun, Moon } from 'lucide-react'
interface AppHeaderProps {
isDarkMode?: boolean
onToggleTheme?: () => void
}
export default function AppHeader({ isDarkMode = true, onToggleTheme }: AppHeaderProps) {
const theme = useTheme()
return (
<Box
component="header"
sx={{
borderBottom: `1px solid ${theme.palette.divider}`,
backgroundColor: theme.palette.background.paper,
backdropFilter: 'blur(8px)',
position: 'sticky',
top: 0,
zIndex: 1100,
px: 2,
py: 1.5,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
<img src="/nomad-karaoke-logo.svg" alt="Nomad Karaoke" style={{ height: 40 }} />
<Typography
variant="h6"
sx={{
fontWeight: 'bold',
color: theme.palette.text.primary,
fontSize: '1.1rem',
lineHeight: 1,
m: 0,
}}
>
Lyrics Transcription Review
</Typography>
</Box>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
{onToggleTheme && (
<Tooltip title={isDarkMode ? 'Switch to light mode' : 'Switch to dark mode'}>
<IconButton
onClick={onToggleTheme}
sx={{
color: theme.palette.text.secondary,
'&:hover': {
color: theme.palette.text.primary,
backgroundColor: theme.palette.action.hover,
},
}}
>
{isDarkMode ? <Sun className="w-5 h-5" /> : <Moon className="w-5 h-5" />}
</IconButton>
</Tooltip>
)}
</Box>
</Box>
)
}
@@ -42,7 +42,7 @@ const WordContainer = styled(Box, {
'50%': { opacity: 0.5 }
},
'&:hover': {
backgroundColor: '#c8e6c9'
backgroundColor: 'rgba(34, 197, 94, 0.35)' // green tint hover for dark mode
}
}))
@@ -51,7 +51,7 @@ const OriginalWordLabel = styled(Box)({
top: '-14px',
left: '0',
fontSize: '0.6rem',
color: '#666',
color: '#888888', // slate-400 for dark mode
textDecoration: 'line-through',
opacity: 0.7,
whiteSpace: 'nowrap',
@@ -71,10 +71,10 @@ const ActionButton = styled(IconButton)(({ theme }) => ({
minHeight: '20px',
width: '20px',
height: '20px',
backgroundColor: 'rgba(255, 255, 255, 0.9)',
border: '1px solid rgba(0, 0, 0, 0.1)',
backgroundColor: 'rgba(30, 41, 59, 0.9)', // slate-800 with opacity for dark mode
border: '1px solid rgba(248, 250, 252, 0.1)', // light border for dark mode
'&:hover': {
backgroundColor: 'rgba(255, 255, 255, 1)',
backgroundColor: 'rgba(51, 65, 85, 1)', // slate-700 for dark mode
transform: 'scale(1.1)'
},
'& .MuiSvgIcon-root': {
@@ -30,7 +30,7 @@ const SegmentTimeline = styled(Box)({
const TimelineRuler = styled(Box)({
position: 'relative',
height: '20px',
borderBottom: '1px solid #ccc',
borderBottom: '1px solid #2a2a2a', // slate-700 for dark mode
marginBottom: '4px'
})
@@ -38,14 +38,14 @@ const TimelineMark = styled(Box)({
position: 'absolute',
width: '1px',
height: '8px',
backgroundColor: '#999',
backgroundColor: '#666666', // slate-500 for dark mode
bottom: 0
})
const TimelineLabel = styled(Typography)({
position: 'absolute',
fontSize: '0.65rem',
color: '#666',
color: '#888888', // slate-400 for dark mode
bottom: '10px',
transform: 'translateX(-50%)',
whiteSpace: 'nowrap'
@@ -58,7 +58,7 @@ const WordsBar = styled(Box)({
alignItems: 'stretch',
minWidth: '100%',
touchAction: 'pan-y', // Better mobile scrolling
backgroundColor: '#f5f5f5',
backgroundColor: '#0f0f0f', // slate-900 for dark mode
borderRadius: '4px',
marginBottom: '8px'
})
@@ -84,7 +84,7 @@ const WordBar = styled(Box, {
? COLORS.corrected
: isGap
? COLORS.uncorrectedGap
: '#e0e0e0',
: '#2a2a2a', // slate-700 for dark mode default
border: isLong ? '2px solid #f44336' : 'none',
boxShadow: isLong ? '0 0 4px rgba(244, 67, 54, 0.5)' : 'none',
'&:hover': {
@@ -101,13 +101,13 @@ const WordBar = styled(Box, {
const OriginalWordLabel = styled(Typography)({
fontSize: '0.65rem',
color: '#888',
color: '#888888', // slate-400 for dark mode
lineHeight: 1.1,
marginBottom: '3px',
textDecoration: 'line-through',
opacity: 0.85,
fontWeight: 500,
backgroundColor: 'rgba(255, 255, 255, 0.8)',
backgroundColor: 'rgba(15, 23, 42, 0.8)', // slate-900 with opacity for dark mode
padding: '1px 3px',
borderRadius: '2px'
})
@@ -226,7 +226,7 @@ export default function DurationTimelineView({
whiteSpace: 'nowrap',
width: '100%',
textAlign: 'center',
color: correction ? '#1b5e20' : 'inherit'
color: correction ? '#4ade80' : '#e5e5e5' // green-400 or slate-50 for dark mode
}}
>
{word.text}
@@ -235,7 +235,7 @@ export default function DurationTimelineView({
<Typography
sx={{
fontSize: '0.6rem',
color: 'rgba(0,0,0,0.6)',
color: 'rgba(248, 250, 252, 0.6)', // slate-50 with opacity for dark mode
lineHeight: 1,
marginTop: '3px',
fontWeight: 600
@@ -624,7 +624,7 @@ export default function EditModal({
position: 'absolute',
top: 0,
left: 0,
backgroundColor: 'rgba(255, 255, 255, 0.9)',
backgroundColor: 'rgba(30, 41, 59, 0.95)', // slate-800 with opacity for dark mode
zIndex: 10
}}>
<CircularProgress size={60} thickness={4} />
@@ -312,7 +312,7 @@ export default function EditWordList({
width: '8px',
},
'&::-webkit-scrollbar-thumb': {
backgroundColor: 'rgba(0,0,0,0.2)',
backgroundColor: 'rgba(248, 250, 252, 0.2)', // slate-50 for dark mode
borderRadius: '4px',
},
scrollbarWidth: 'thin',
@@ -1,4 +1,4 @@
import { Box, Button, Typography, useMediaQuery, useTheme, Switch, FormControlLabel, Tooltip, Paper, IconButton, Chip } from '@mui/material'
import { Box, Button, Typography, useMediaQuery, useTheme, Switch, FormControlLabel, Tooltip, Paper, IconButton } from '@mui/material'
import LockIcon from '@mui/icons-material/Lock'
import UploadFileIcon from '@mui/icons-material/UploadFile'
import FindReplaceIcon from '@mui/icons-material/FindReplace'
@@ -129,50 +129,19 @@ export default function Header({
</Box>
)}
<Box sx={{
display: 'flex',
flexDirection: isMobile ? 'column' : 'row',
gap: 1,
justifyContent: 'space-between',
alignItems: isMobile ? 'stretch' : 'center',
mb: 1
}}>
<Typography variant="h4" sx={{ fontSize: isMobile ? '1.3rem' : '1.5rem' }}>
Nomad Karaoke: Lyrics Transcription Review
</Typography>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
{!isReadOnly && onAnnotationsToggle && (
<Tooltip title={annotationsEnabled
? "Click to disable annotation prompts when editing"
: "Click to enable annotation prompts when editing"
}>
<Chip
icon={<RateReviewIcon />}
label={annotationsEnabled ? "Feedback On" : "Feedback Off"}
onClick={() => onAnnotationsToggle(!annotationsEnabled)}
color={annotationsEnabled ? "primary" : "default"}
variant={annotationsEnabled ? "filled" : "outlined"}
size="small"
sx={{
cursor: 'pointer',
'& .MuiChip-icon': { fontSize: '1rem' }
}}
/>
</Tooltip>
)}
{isReadOnly && (
<Button
variant="outlined"
size="small"
startIcon={<UploadFileIcon />}
onClick={onFileLoad}
fullWidth={isMobile}
>
Load File
</Button>
)}
{isReadOnly && (
<Box sx={{ display: 'flex', justifyContent: 'flex-end', mb: 1 }}>
<Button
variant="outlined"
size="small"
startIcon={<UploadFileIcon />}
onClick={onFileLoad}
fullWidth={isMobile}
>
Load File
</Button>
</Box>
</Box>
)}
<Box sx={{
display: 'flex',
@@ -387,10 +356,10 @@ export default function Header({
Timing Offset
</Button>
{timingOffsetMs !== 0 && (
<Typography
variant="body2"
sx={{
ml: 1,
<Typography
variant="body2"
sx={{
ml: 1,
fontWeight: 'bold',
color: theme.palette.secondary.main
}}
@@ -400,6 +369,23 @@ export default function Header({
)}
</Box>
)}
{!isReadOnly && onAnnotationsToggle && (
<Tooltip title={annotationsEnabled
? "Click to disable annotation prompts when editing"
: "Click to enable annotation prompts when editing"
}>
<Button
variant="outlined"
size="small"
onClick={() => onAnnotationsToggle(!annotationsEnabled)}
startIcon={<RateReviewIcon />}
color={annotationsEnabled ? "primary" : "inherit"}
sx={{ minWidth: 'fit-content', height: '32px' }}
>
{annotationsEnabled ? "Feedback On" : "Feedback Off"}
</Button>
</Tooltip>
)}
<AudioPlayer
apiClient={apiClient}
onTimeUpdate={onTimeUpdate}
@@ -33,16 +33,17 @@ const CANVAS_PADDING = 8
const TEXT_ABOVE_BLOCK = 14
const RESIZE_HANDLE_SIZE = 8
const RESIZE_HANDLE_HITAREA = 12
const PLAYHEAD_COLOR = '#ffffff'
const WORD_BLOCK_COLOR = '#d32f2f'
const WORD_BLOCK_SELECTED_COLOR = '#b71c1c'
const WORD_BLOCK_CURRENT_COLOR = '#f44336'
const WORD_TEXT_CURRENT_COLOR = '#d32f2f'
const UPCOMING_WORD_BG = '#fff9c4'
const UPCOMING_WORD_TEXT = '#000000'
const TIME_BAR_BG = '#f5f5f5'
const TIME_BAR_TEXT = '#666666'
const TIMELINE_BG = '#e0e0e0'
// Dark theme colors matching karaoke-gen
const PLAYHEAD_COLOR = '#f97316' // orange-500 for better visibility
const WORD_BLOCK_COLOR = '#dc2626' // red-600 for dark mode
const WORD_BLOCK_SELECTED_COLOR = '#b91c1c' // red-700 for dark mode
const WORD_BLOCK_CURRENT_COLOR = '#ef4444' // red-500 for dark mode
const WORD_TEXT_CURRENT_COLOR = '#fca5a5' // red-300 for dark mode
const UPCOMING_WORD_BG = '#2a2a2a' // slate-700 for dark mode
const UPCOMING_WORD_TEXT = '#e5e5e5' // slate-50 for dark mode
const TIME_BAR_BG = '#1a1a1a' // slate-800 for dark mode
const TIME_BAR_TEXT = '#888888' // slate-400 for dark mode
const TIMELINE_BG = '#0f0f0f' // slate-900 for dark mode
// Drag modes
type DragMode = 'none' | 'selection' | 'resize' | 'move'
@@ -268,7 +269,7 @@ const TimelineCanvas = memo(function TimelineCanvas({
const x = timeToX(t)
ctx.beginPath()
ctx.strokeStyle = '#999999'
ctx.strokeStyle = '#64748b' // slate-500 for dark mode
ctx.lineWidth = 1
ctx.moveTo(x, TIME_BAR_HEIGHT - 6)
ctx.lineTo(x, TIME_BAR_HEIGHT)
@@ -280,7 +281,7 @@ const TimelineCanvas = memo(function TimelineCanvas({
}
ctx.beginPath()
ctx.strokeStyle = '#cccccc'
ctx.strokeStyle = '#2a2a2a' // slate-700 for dark mode
ctx.lineWidth = 1
ctx.moveTo(0, TIME_BAR_HEIGHT)
ctx.lineTo(canvasWidth, TIME_BAR_HEIGHT)
@@ -314,20 +315,20 @@ const TimelineCanvas = memo(function TimelineCanvas({
// Draw selection border
if (isSelected) {
ctx.strokeStyle = '#ffffff'
ctx.strokeStyle = '#f97316' // orange-500 for dark mode selection
ctx.lineWidth = 2
ctx.strokeRect(bounds.startX, bounds.y, bounds.blockWidth, WORD_BLOCK_HEIGHT)
// Draw resize handle (white dot on right edge) for selected words when hovered
// Draw resize handle (orange dot on right edge) for selected words when hovered
if (isHovered || selectedWordIds.size === 1) {
const handleX = bounds.startX + bounds.blockWidth - RESIZE_HANDLE_SIZE / 2
const handleY = bounds.y + WORD_BLOCK_HEIGHT / 2
ctx.beginPath()
ctx.fillStyle = '#ffffff'
ctx.fillStyle = '#f97316' // orange-500 for dark mode
ctx.arc(handleX, handleY, RESIZE_HANDLE_SIZE / 2, 0, Math.PI * 2)
ctx.fill()
ctx.strokeStyle = '#666666'
ctx.strokeStyle = '#0f0f0f' // slate-900 for dark mode
ctx.lineWidth = 1
ctx.stroke()
}
@@ -368,7 +369,7 @@ const TimelineCanvas = memo(function TimelineCanvas({
if (textStartX < canvasWidth - 10) {
const isCurrent = word.id === currentWordId
ctx.fillStyle = isCurrent ? WORD_TEXT_CURRENT_COLOR : '#333333'
ctx.fillStyle = isCurrent ? WORD_TEXT_CURRENT_COLOR : '#f8fafc' // slate-50 for dark mode
ctx.fillText(word.text, textStartX, textY)
rightmostTextEnd = textStartX + textWidth
}
@@ -405,7 +406,7 @@ const TimelineCanvas = memo(function TimelineCanvas({
ctx.beginPath()
ctx.fillStyle = PLAYHEAD_COLOR
ctx.strokeStyle = '#333333'
ctx.strokeStyle = '#0f0f0f' // slate-900 for dark mode
ctx.lineWidth = 1
ctx.moveTo(playheadX - 6, 2)
ctx.lineTo(playheadX + 6, 2)
@@ -422,7 +423,7 @@ const TimelineCanvas = memo(function TimelineCanvas({
ctx.stroke()
ctx.beginPath()
ctx.strokeStyle = 'rgba(0,0,0,0.4)'
ctx.strokeStyle = 'rgba(0,0,0,0.6)' // Darker shadow for dark mode visibility
ctx.lineWidth = 1
ctx.moveTo(playheadX + 1, TIME_BAR_HEIGHT)
ctx.lineTo(playheadX + 1, height)
@@ -221,7 +221,7 @@ export default function ReferenceView({
width: '100%',
mb: 0,
'&:hover': {
backgroundColor: 'rgba(0, 0, 0, 0.03)'
backgroundColor: 'rgba(248, 250, 252, 0.04)' // slate-50 hover for dark mode
}
}}
>
@@ -182,7 +182,7 @@ export default function TranscriptionView({
width: '100%',
mb: 0,
'&:hover': {
backgroundColor: 'rgba(0, 0, 0, 0.03)'
backgroundColor: 'rgba(248, 250, 252, 0.04)' // slate-50 hover for dark mode
}
}}>
<SegmentControls>
@@ -18,7 +18,7 @@ interface WordDividerProps {
}
const buttonTextStyle = {
color: 'rgba(0, 0, 0, 0.6)',
color: 'rgba(248, 250, 252, 0.8)', // slate-50 with opacity for dark mode
fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
fontWeight: 400,
fontSize: '0.7rem',
@@ -58,7 +58,7 @@ export default function WordDivider({
height: '20px',
my: -0.5,
width: '50%',
backgroundColor: '#fff',
backgroundColor: '#1a1a1a', // slate-800 for dark mode
...sx
}}
>
@@ -66,7 +66,7 @@ export default function WordDivider({
display: 'flex',
alignItems: 'center',
gap: 1,
backgroundColor: '#fff',
backgroundColor: '#1a1a1a', // slate-800 for dark mode
padding: '0 8px',
zIndex: 1
}}>
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff. Show more