Compare commits

...
Author SHA1 Message Date
Andrew BeveridgeandClaude Opus 4.5 56052a4bd1 Fix TypeScript type errors across frontend
- Add jest.setup.d.ts for @testing-library/jest-dom types
- Add columns prop to StatsGrid and valueClassName to StatsCard
- Add showCloseButton prop to DialogContent component
- Fix rate-limits test mocks (use undefined instead of null, add message)
- Fix AuthStatus.test.tsx mock typing (cast through unknown)
- Fix E2E test implicit any type in evaluate callback

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 17:12:59 -08:00
Andrew BeveridgeandClaude Opus 4.5 abd13265df Add missing Job type properties for admin page
Add typed properties to Job interface:
- audio_search_artist, audio_search_title (audio search)
- theme_id, brand_prefix (theming)
- customer_email (made-for-you orders)
- error_details, request_metadata (debugging)

Removes `as any` casts from admin page now that properties are typed.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 17:12:59 -08:00
Andrew BeveridgeandClaude Opus 4.5 3a8c8c0637 Fix hash-based navigation not triggering hashchange event
Use regular <a> tags instead of Next.js Link for hash-based URLs.
Next.js Link uses history.pushState which doesn't fire hashchange,
so the client.tsx component's hash state wasn't updating on navigation.

With <a> tags, clicking the link triggers browser's native hash handling
which fires hashchange and updates the routing state correctly.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 17:12:59 -08:00
Andrew Beveridge ☄️andClaude Opus 4.5 a1f9da2fb5 Implement hash-based routing for job review/instrumental pages (#311)
## Summary
- Switch from path-based routing (`/app/jobs/{id}/review`) to hash-based
routing (`/app/jobs#/{id}/review`)
- Eliminates the need for SPA redirect workarounds on static hosts
- URLs now correctly reflect the current view and survive page reload

## Benefits
- **Clean URLs**: URL always shows which job is being viewed
- **Reload works**: Browser hash is preserved, no sessionStorage needed
- **Simpler code**: Removed 100+ lines of SPA redirect logic
- **Universal compatibility**: Works on any static host

## Changes
**Frontend:**
- `client.tsx`: Parse route from URL hash instead of path/sessionStorage
- `JobCard.tsx`: Update link hrefs to hash-based format
- Remove SPA redirect script injection
- Remove Cloudflare rewrite rules (no longer needed)

**Backend:**
- `job_notification_service.py`: Update email URLs to new format
- Updated tests

## URL Format
- Old: `https://gen.nomadkaraoke.com/app/jobs/26391a79/review`
- New: `https://gen.nomadkaraoke.com/app/jobs#/26391a79/review`

Note: Local mode still uses path-based routing for compatibility with
dev server.

## Test plan
- [x] Frontend build passes
- [x] Frontend tests pass (JobCard)
- [x] Backend tests pass (job_notification_service)
- [ ] Manual: Click "Review Lyrics" button - navigates to hash URL
- [ ] Manual: Reload page - stays on same view
- [ ] Manual: Email link works with new format

@coderabbitai ignore

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 16:36:26 -08:00
Andrew Beveridge ☄️andClaude Opus 4.5 6394b33fbb Fix auth flash and card padding (#310)
## Summary
- Fix "Sign in required" flash during SPA redirect by waiting for
zustand hydration
- Add vertical padding to Card component for better spacing

## Changes
- **auth.ts**: Add `hasHydrated` flag and `onRehydrateStorage` handler
- **client.tsx**: Wait for `hasHydrated` before showing
"not_authenticated"
- **card.tsx**: Add `py-6` to Card component

## Test plan
- [x] Build passes
- [ ] Navigate to lyrics review - no more "Sign in required" flash
- [ ] Dashboard cards have proper vertical padding

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 16:08:41 -08:00
Andrew Beveridge ☄️andClaude Opus 4.5 b2befccd5b Fix page reload on lyrics review (#309)
## Summary
Fixes the page reload issue on the lyrics review page by preserving
sessionStorage across refreshes.

## Problem
After PR #308, the lyrics review page worked on initial navigation but
page reload showed "Page not found". This happened because:
1. `history.replaceState()` was used to update the URL to
`/app/jobs/{id}/review/`
2. But Next.js internal router reverted this back to `/app/jobs/`
3. The sessionStorage was cleared immediately on read, so reload had no
stored path to restore

## Solution
- Keep sessionStorage value across reloads (don't clear it on read)
- On page reload: browser requests `/app/jobs/`, 404.html redirects
back, and we re-read the stored path from sessionStorage
- Clear sessionStorage only when navigating to a different job (prevents
stale redirects)

## Test plan
- [x] Build succeeds
- [ ] Navigate to lyrics review page (initial load works)
- [ ] Reload the page (should still show lyrics review)
- [ ] Navigate to a different job's review (should load new job, not old
one)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 15:38:19 -08:00
Andrew Beveridge ☄️andClaude Opus 4.5 bf7653773a Fix lyrics review: logo path, API endpoints, and SPA routing (#308)
## Summary
Comprehensive fix for the lyrics review page that addresses three
categories of issues:

### 1. Logo 404 Fix
- Changed logo src from `/static/nomad-karaoke-logo.svg` to
`/nomad-karaoke-logo.svg`

### 2. API Endpoint Fixes (causing audio/video 404s)
The frontend was calling wrong API paths after the backend migration to
`/api/review/` prefix:

| Endpoint | Before (broken) | After (fixed) |
|----------|-----------------|---------------|
| Audio URL | `/api/audio/{hash}` | `/api/review/{jobId}/audio/{hash}` |
| Generate preview | `/api/jobs/{jobId}/preview-video` |
`/api/review/{jobId}/preview-video` |
| Preview video URL | `/api/preview-video/{hash}` |
`/api/review/{jobId}/preview-video/{hash}` |

### 3. SPA Routing Fix (enabling page reload)
- Added `history.replaceState()` call after restoring the redirect path
from sessionStorage
- This updates the browser's URL bar to show the actual route (e.g.,
`/app/jobs/abc123/review/`)
- Enables page reload to work correctly - browser re-requests the
correct URL which triggers the SPA redirect flow again

## Test plan
- [x] Build succeeds
- [ ] Logo displays on lyrics review page
- [ ] Audio loads and plays in lyrics review
- [ ] Preview video generation works
- [ ] Page reload works on lyrics review page
- [ ] Direct navigation to `/app/jobs/{id}/review/` works

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 15:20:01 -08:00
Andrew Beveridge ☄️andClaude Opus 4.5 a7de863121 Fix frontend SPA routing and lyrics review API endpoint (#307)
## Summary
- Fixed GitHub Pages SPA routing for dynamic routes like
`/app/jobs/{jobId}/review`
- Fixed API endpoint for lyrics review - was calling wrong endpoint (GET
on POST-only route)

## Changes
1. **SPA redirect mechanism** - `404.html` stores the path in
sessionStorage and redirects to `/app/jobs/` where the client component
restores the route
2. **API endpoint fix** - Changed `getCorrectionData()` from
`/api/jobs/{jobId}/corrections` (POST-only) to
`/api/review/{jobId}/correction-data` (correct GET endpoint)

## Testing
- Verified SPA redirect flow works in production
- Verified lyrics review page loads correctly when authenticated

## Test plan
- [x] Build succeeds
- [ ] CI passes
- [ ] Click "Review Lyrics" button on job 26391a79 loads lyrics review
page

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 14:42:24 -08:00
Andrew Beveridge ☄️andClaude Opus 4.5 63a14ce920 fix(frontend): Parse route from stored path instead of updating URL (#306)
@coderabbitai ignore

## Summary
- Fixes SPA redirect restoration where Next.js was reverting
`history.replaceState()` calls
- Instead of updating the URL bar (which gets reverted), we now parse
the route directly from the stored sessionStorage path
- The URL will stay at `/app/jobs/` after redirect restoration, but the
correct content renders

## Why
Previous fix (#305) used `history.replaceState()` to update the URL
after SPA redirect restoration, but Next.js reverts any replaceState
calls that don't match its internal router state. This caused the URL to
flash back to `/app/jobs/` and show "Page not found".

## Test plan
- Navigate to `https://gen.nomadkaraoke.com/app/jobs/26391a79/review/`
- Should redirect via 404.html → /app/jobs/ but render the lyrics review
UI
- URL will show `/app/jobs/` but content should be correct

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

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 13:47:18 -08:00
Andrew Beveridge ☄️andClaude Opus 4.5 c17d10cff0 fix(frontend): Fix race condition in SPA redirect restoration (#305)
## Summary
Fixes the race condition that was causing the "Page not found" error
when accessing dynamic job URLs.

## Problem
Discovered via Playwright debugging that React on 404.html was executing
`checkAndRestoreRedirect()` **before** the `window.location.replace()`
redirect completed. This cleared sessionStorage prematurely, so when the
new page loaded at `/app/jobs/`, the redirect path was already gone.

Debug trace:
```
[SessionStorage] SET: spa-redirect-path = /app/jobs/26391a79/review/
[SessionStorage] GET: spa-redirect-path = /app/jobs/26391a79/review/  <-- React on 404.html reads it
[SessionStorage] REMOVE: spa-redirect-path  <-- React clears it before redirect!
[History] replaceState: /app/jobs/26391a79/review/
[History] replaceState: /app/jobs/  <-- Then redirect happens, but sessionStorage is empty
```

## Solution
Only check sessionStorage when we're at the redirect target URL
(`/app/jobs/`), not when we're still on the original 404 page.

```typescript
const pathname = window.location.pathname
if (pathname !== '/app/jobs/' && pathname !== '/app/jobs') {
  return false  // Don't touch sessionStorage if we're not at the target
}
```

## Test plan
- [x] Unit tests pass (181 tests)
- [x] Build succeeds
- [ ] Verified via Playwright debugging

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 13:21:05 -08:00
Andrew Beveridge ☄️andClaude Opus 4.5 b669108010 fix(frontend): Fix infinite redirect loop in SPA routing (#304)
## Summary
Fixes the infinite redirect loop introduced in #303.

## Problem
The previous SPA routing fix used `router.replace()` which triggers a
full page navigation in Next.js static export mode. This caused GitHub
Pages to serve 404.html again, creating an infinite loop.

## Solution
- Remove `router.replace()` entirely
- Use `history.replaceState()` to update the URL without navigation
- Parse route directly from `window.location.pathname` after restore
- Use `useState` lazy initializer for synchronous redirect detection to
avoid flash of "invalid route" UI

## Flow (corrected)
```
User visits /app/jobs/26391a79/review/
    ↓
GitHub Pages serves 404.html
    ↓
Script stores path in sessionStorage, redirects to /app/jobs/
    ↓
JobRouterClient renders, useState initializer checks sessionStorage
    ↓
If found: removes it, calls history.replaceState(), returns true
    ↓
parseRouteFromPathname() parses jobId/routeType from window.location
    ↓
Component renders with correct route (no loop!)
```

## Test plan
- [x] Frontend unit tests pass (181 tests)
- [x] Build succeeds
- [ ] Manual: Verify `/app/jobs/{id}/review` loads without infinite loop

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 12:47:56 -08:00
Andrew Beveridge ☄️andClaude Opus 4.5 eaa4bc8415 fix(frontend): Add SPA routing for dynamic job URLs on GitHub Pages (#303)
## Summary
- Fix 404 errors for dynamic job URLs (e.g.,
`/app/jobs/26391a79/review/`) after frontend consolidation
- Implement SPA redirect pattern for GitHub Pages static export
- Add post-build script that injects redirect logic into 404.html
- Add path restoration in JobRouterClient via sessionStorage

## Problem
The frontend consolidation introduced a catch-all route
`/app/jobs/[[...slug]]` for dynamic job IDs. With Next.js static export
on GitHub Pages, only pre-rendered paths work. Dynamic paths like
`/app/jobs/26391a79/review/` resulted in 404s because they're not
pre-generated at build time.

## Solution
Implemented the SPA redirect pattern:
1. **404.html script** - Detects `/app/jobs/*` URLs, stores path in
sessionStorage, redirects to `/app/jobs/`
2. **JobRouterClient** - On mount, reads sessionStorage and navigates to
the correct route

Flow:
```
User visits /app/jobs/26391a79/review/
    ↓
GitHub Pages serves 404.html (path doesn't exist as static file)
    ↓
Injected script detects /app/jobs/* pattern
    ↓
Stores path in sessionStorage, redirects to /app/jobs/
    ↓
JobRouterClient loads, reads sessionStorage
    ↓
Navigates to /app/jobs/26391a79/review/ with correct component
```

## Test plan
- [x] All backend tests pass (1593 tests)
- [x] All frontend unit tests pass (181 tests)
- [x] Build succeeds with post-build script injection
- [ ] Manual: Verify `/app/jobs/{id}/review` loads correctly in
production

## Files Changed
- `frontend/scripts/spa-redirect-404.js` - Post-build script to inject
redirect
- `frontend/app/app/jobs/[[...slug]]/client.tsx` - Path restoration
logic
- `frontend/package.json` - Updated build script
- `frontend/public/_redirects` - For potential Cloudflare Pages
migration

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 12:31:51 -08:00
Andrew Beveridge ☄️andClaude Opus 4.5 503a0281ae fix(video-worker): Remove duplicate PACKAGING state transition (#302)
## Summary

Removes redundant state transition call that caused "Invalid state
transition: packaging -> packaging" errors in production logs.

## Changes

- Removed duplicate `job_manager.transition_to_state()` call in
`generate_video_orchestrated()`
- The orchestrator already handles this transition in
`_run_distribution()` at line 472
- Jobs completed successfully despite the error (state machine
gracefully rejects invalid transitions)
- This fix eliminates unnecessary error noise in production logs

## Testing

- [x] Unit tests pass (1593 passed)
- [x] No E2E test changes needed (internal fix only)

## Review

- [x] Local CodeRabbit review completed
- [x] No issues found

## Root Cause

When using the orchestrator pipeline (`USE_NEW_ORCHESTRATOR=true`):
1. `video_worker_orchestrator.py:472` transitions to PACKAGING in
`_run_distribution()`
2. `video_worker.py:325` also tried to transition to PACKAGING after
distribution
3. The second call failed because job was already in PACKAGING state

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 11:38:16 -08:00
Andrew Beveridge ☄️andClaude Opus 4.5 0b9ca514b6 fix(cli): Fix --no-video flag to properly skip all video rendering (#301)
## Summary
- Fix `--no-video` flag to properly skip all video rendering throughout
the pipeline
- Previously the flag only affected finalisation; now it skips title/end
screens in prep and preview video in review UI
- When `--no-video` is set, artist/title are extracted from directory
name instead of video filename
- Skip video file requirements in finalisation when flag is set

## Changes
- `gen_cli.py`: Pass `render_video=not args.no_video` to KaraokePrep
- `karaoke_gen.py`: Check `self.render_video` before creating title/end
screen videos
- `lyrics_processor.py`: Set `allow_preview_video=self.render_video` in
OutputConfig
- `config.py`: Add `allow_preview_video` field to OutputConfig
- `server.py`: Check `allow_preview_video` before generating preview
video
- `karaoke_finalise.py`: Extract artist/title from directory name when
no_video=True, skip video file requirements

## Test plan
- [x] Added unit tests for --no-video flag in
`tests/unit/test_karaoke_finalise_no_video.py`
- [x] Added assertion in `test_gen_cli.py` for render_video passthrough
- [x] Updated existing tests to match new behavior
- [x] All 1593 tests pass

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 10:00:11 -08:00
Andrew Beveridge ☄️andClaude Opus 4.5 404c6e6133 fix: make lyrics_transcriber a subpackage of karaoke_gen (#299)
## Summary
Fixes the deployment failure from PR #297 by making lyrics_transcriber a
proper subpackage of karaoke_gen instead of a separate vendored library.

### Changes
- Move `libs/lyrics_transcriber/` to `karaoke_gen/lyrics_transcriber/`
- Update all imports from `from lyrics_transcriber.X` to `from
karaoke_gen.lyrics_transcriber.X`
- Simplify Dockerfile (no separate `libs/` COPY needed)
- Update pyproject.toml to remove separate package entry
- Update test mocks and logger names

### Why this is better
- Cleaner project structure - one package containing everything
- Simpler Dockerfile - just COPY karaoke_gen/
- No confusion about vendored vs internal code

## Test plan
- [x] `poetry install` succeeds
- [x] All imports work correctly
- [x] All 2614 tests pass
- [ ] Backend deployment succeeds

@coderabbitai ignore

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 16:53:34 +00:00
Shimpei TakamatsuandAndrew Beveridge ☄️ f3ee9e05f3 feat(cli): Add --no-video flag for CDG/TXT-only generation (#288)
## Summary
- Add `--no-video` flag to skip video encoding and distribution features
- Allows CDG/TXT-only generation for faster processing (~15-20 min saved
on full songs)
- Skips: final video encoding, remuxing, YouTube upload, Discord,
rclone, brand code organization
- Still runs: audio separation, transcription, CDG/TXT package
generation

Addresses #278

## Test plan
- [x] Unit tests for `--no-video` flag handling
- [x] Integration test: `test_full_cli_integration_no_video`
- [x] Manual testing on macOS with Local Whisper

## Known Behaviors

**Preview and prep phase videos still generated:**
- Preview video (360p) - needed for Transcription Review UI (~few
seconds)
- Prep phase video (4K) - `(With Vocals).mkv` (~several seconds)
- The `--no-video` flag specifically skips **finalisation phase
encoding** (~15-20 min for full songs)

**Output format requirements:**
- When using `--no-video`, specify at least one of: `--enable_cdg` or
`--enable_txt`
- Without these, command completes but generates no output packages

## Usage Examples

```bash
# CDG only
karaoke-gen --no-video --enable_cdg audio.flac "Artist" "Title"

# CDG + TXT
karaoke-gen --no-video --enable_cdg --enable_txt audio.flac "Artist" "Title"

# With auto-download
karaoke-gen --no-video --enable_cdg --auto-download "Artist" "Title"
```

## Questions for Reviewers

1. **Video generation behavior:** Is the current behavior (generating
preview and prep phase videos) acceptable, or should we document it more
prominently in the help text?

2. **Output format requirements:** Should we add validation to require
at least one of `--enable_cdg` or `--enable_txt` when `--no-video` is
specified, or is the current behavior (completing with no output
packages) acceptable?


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **New Features**
* Added `--no-video` flag to skip video encoding and distribution steps,
enabling faster CDG/TXT-only package generation.

* **Documentation**
  * Updated README with usage example for the new `--no-video` option.

* **Tests**
* Added comprehensive integration and unit tests for the no-video
workflow.

<sub>✏️ Tip: You can customize this high-level summary in your review
settings.</sub>

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Andrew Beveridge ☄️ <andrew@beveridge.uk>
2026-01-19 08:20:15 -08:00
204 changed files with 1518 additions and 373 deletions

No files matched your search

@@ -57,7 +57,7 @@ karaoke-gen/
1. **`libs/`** - Clear convention for vendored/embedded libraries, separate from main codebase
2. **Single level** - `lyrics_transcriber` directly under `libs/`, not nested (no `libs/lyrics_transcriber/lyrics_transcriber/`)
3. **Clean imports** - `from lyrics_transcriber.core import ...` continues to work with proper Poetry config
3. **Clean imports** - `from karaoke_gen.lyrics_transcriber.core import ...` continues to work with proper Poetry config
### pyproject.toml Changes
@@ -132,7 +132,7 @@ From current `lyrics_transcriber_temp/`:
7. [ ] Remove `lyrics_transcriber_temp/` directory (with all its extra files)
8. [ ] Update `pyproject.toml` packages and include paths
9. [ ] Update the one script that references `lyrics_transcriber_temp` directly:
- `scripts/benchmark_encoding.py` line 232: change `from lyrics_transcriber_temp.lyrics_transcriber.output.video` to `from lyrics_transcriber.output.video`
- `scripts/benchmark_encoding.py` line 232: change `from lyrics_transcriber_temp.lyrics_transcriber.output.video` to `from karaoke_gen.lyrics_transcriber.output.video`
### Phase 3: Verify and Test
@@ -140,9 +140,9 @@ From current `lyrics_transcriber_temp/`:
11. [ ] Run `make test` to ensure all tests pass
12. [ ] Verify imports work:
```python
from lyrics_transcriber.core.controller import LyricsControllerResult
from lyrics_transcriber.output.generator import OutputGenerator
from lyrics_transcriber.types import CorrectionResult
from karaoke_gen.lyrics_transcriber.core.controller import LyricsControllerResult
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
```
### Phase 4: Handle Tests from lyrics_transcriber
@@ -199,6 +199,6 @@ If issues arise:
## Notes
- The import paths like `from lyrics_transcriber.core import ...` will continue to work unchanged
- The import paths like `from karaoke_gen.lyrics_transcriber.core import ...` will continue to work unchanged
- Only the internal project structure changes, not the API
- This is primarily a cleanup/organization task with some external repo admin work
+3
View File
@@ -159,6 +159,9 @@ karaoke-gen --style_params_json="./styles.json" "Artist" "Title"
# Generate CDG and TXT packages
karaoke-gen --enable_cdg --enable_txt "Artist" "Title"
# Skip video encoding (CDG/TXT only, faster)
karaoke-gen --no-video --enable_cdg "Artist" "Title"
# YouTube upload
karaoke-gen --enable_youtube_upload --youtube_description_file="./desc.txt" "Artist" "Title"
+2 -3
View File
@@ -22,10 +22,9 @@ WORKDIR /app
COPY backend /app/backend
# Copy and reinstall karaoke_gen from local source
# This ensures new modules (like style_loader.py) are included without rebuilding base image
# Note: lyrics_transcriber is vendored in lyrics_transcriber_temp/ and bundled via pyproject.toml
# This ensures new modules are included without rebuilding base image
# Note: lyrics_transcriber is now a subpackage of karaoke_gen
COPY karaoke_gen /app/karaoke_gen
COPY lyrics_transcriber_temp /app/lyrics_transcriber_temp
COPY pyproject.toml README.md LICENSE /app/
RUN pip install --no-cache-dir -e .
+3 -3
View File
@@ -33,9 +33,9 @@ from backend.services.auth_service import UserType
from backend.config import get_settings
# LyricsTranscriber imports for preview generation
from lyrics_transcriber.types import CorrectionResult
from lyrics_transcriber.core.config import OutputConfig
from lyrics_transcriber.correction.operations import CorrectionOperations
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
# Import from the unified style loader
from karaoke_gen.style_loader import load_styles_from_gcs
+4 -4
View File
@@ -53,13 +53,13 @@ class JobNotificationService:
def _build_review_url(self, job_id: str, audio_hash: Optional[str] = None, review_token: Optional[str] = None) -> str:
"""Build the lyrics review URL for a job."""
# Use consolidated frontend route
return f"{self.frontend_url}/app/jobs/{job_id}/review"
# Use hash-based routing for static hosting compatibility
return f"{self.frontend_url}/app/jobs#/{job_id}/review"
def _build_instrumental_url(self, job_id: str, instrumental_token: Optional[str] = None) -> str:
"""Build the instrumental selection URL for a job."""
# Use consolidated frontend route
return f"{self.frontend_url}/app/jobs/{job_id}/instrumental"
# Use hash-based routing for static hosting compatibility
return f"{self.frontend_url}/app/jobs#/{job_id}/instrumental"
async def send_job_completion_email(
self,
+1 -1
View File
@@ -120,7 +120,7 @@ class PackagingService:
)
self.logger.info("Generating CDG and MP3 files")
from lyrics_transcriber.output.cdg import CDGGenerator
from karaoke_gen.lyrics_transcriber.output.cdg import CDGGenerator
output_dir = os.path.dirname(output_zip_path) or os.getcwd()
generator = CDGGenerator(output_dir=output_dir, logger=self.logger)
@@ -22,7 +22,7 @@ class TestURLBuilding:
url = service._build_review_url("job-123")
assert url == "https://gen.nomadkaraoke.com/app/jobs/job-123/review"
assert url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/review"
def test_build_review_url_ignores_legacy_params(self):
"""Test review URL ignores legacy audio_hash and review_token params."""
@@ -33,7 +33,7 @@ class TestURLBuilding:
url = service._build_review_url("job-123", audio_hash="abc123", review_token="token456")
# URL should be the simple consolidated route
assert url == "https://gen.nomadkaraoke.com/app/jobs/job-123/review"
assert url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/review"
# No query params
assert "?" not in url
@@ -45,7 +45,7 @@ class TestURLBuilding:
# Note: job IDs with slashes would be unusual in real usage
url = service._build_review_url("abc-def-123")
assert url == "https://gen.nomadkaraoke.com/app/jobs/abc-def-123/review"
assert url == "https://gen.nomadkaraoke.com/app/jobs#/abc-def-123/review"
def test_build_instrumental_url_basic(self):
"""Test basic instrumental URL building."""
@@ -54,7 +54,7 @@ class TestURLBuilding:
url = service._build_instrumental_url("job-123")
assert url == "https://gen.nomadkaraoke.com/app/jobs/job-123/instrumental"
assert url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/instrumental"
def test_build_instrumental_url_ignores_legacy_params(self):
"""Test instrumental URL ignores legacy instrumental_token param."""
@@ -65,7 +65,7 @@ class TestURLBuilding:
url = service._build_instrumental_url("job-123", instrumental_token="inst-token")
# URL should be the simple consolidated route
assert url == "https://gen.nomadkaraoke.com/app/jobs/job-123/instrumental"
assert url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/instrumental"
# No query params
assert "?" not in url
@@ -312,7 +312,7 @@ class TestActionReminderEmail:
# Verify the review URL was passed to template
call_kwargs = service.template_service.render_action_needed_lyrics.call_args.kwargs
review_url = call_kwargs.get('review_url')
assert review_url == "https://gen.nomadkaraoke.com/app/jobs/job-123/review"
assert review_url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/review"
@pytest.mark.asyncio
async def test_send_instrumental_reminder_includes_url(self):
@@ -334,7 +334,7 @@ class TestActionReminderEmail:
# Verify the instrumental URL was passed to template
call_kwargs = service.template_service.render_action_needed_instrumental.call_args.kwargs
instrumental_url = call_kwargs.get('instrumental_url')
assert instrumental_url == "https://gen.nomadkaraoke.com/app/jobs/job-123/instrumental"
assert instrumental_url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/instrumental"
class TestGetCompletionMessage:
+1 -1
View File
@@ -201,7 +201,7 @@ class TestPackagingServiceCDGPackage:
assert result[1] == mp3_file
assert result[2] == cdg_file
@patch("lyrics_transcriber.output.cdg.CDGGenerator")
@patch("karaoke_gen.lyrics_transcriber.output.cdg.CDGGenerator")
def test_create_cdg_package_with_generator(self, mock_cdg_generator_class):
"""Test CDG package creation using CDGGenerator."""
with tempfile.TemporaryDirectory() as tmpdir:
+1 -1
View File
@@ -204,7 +204,7 @@ class TestAddLyricsEndpoint:
def test_add_lyrics_uses_correction_operations(self):
"""Verify CorrectionOperations.add_lyrics_source is available."""
from lyrics_transcriber.correction.operations import CorrectionOperations
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
# The method should exist
assert hasattr(CorrectionOperations, 'add_lyrics_source')
+2 -2
View File
@@ -560,7 +560,7 @@ class TestRenderVideoWorkerCountdownPadding:
def test_countdown_processor_has_process_method(self):
"""Test that CountdownProcessor has the process method (main API)."""
from lyrics_transcriber.output.countdown_processor import CountdownProcessor
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
countdown_processor = CountdownProcessor(cache_dir="/tmp")
assert hasattr(countdown_processor, 'process')
@@ -568,7 +568,7 @@ class TestRenderVideoWorkerCountdownPadding:
def test_countdown_processor_constants(self):
"""Test that CountdownProcessor has expected constants."""
from lyrics_transcriber.output.countdown_processor import CountdownProcessor
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
# Verify the constants exist (these control countdown behavior)
assert hasattr(CountdownProcessor, 'COUNTDOWN_TEXT')
+8 -8
View File
@@ -36,10 +36,10 @@ from backend.workers.worker_logging import create_job_logger, setup_job_logging,
from backend.services.tracing import job_span, add_span_event, add_span_attribute
# Import from lyrics_transcriber (submodule)
from lyrics_transcriber.output.generator import OutputGenerator
from lyrics_transcriber.output.countdown_processor import CountdownProcessor
from lyrics_transcriber.types import CorrectionResult
from lyrics_transcriber.core.config import OutputConfig
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
# Import from the unified style loader
from karaoke_gen.style_loader import load_styles_from_gcs
@@ -51,10 +51,10 @@ logger = logging.getLogger(__name__)
# Loggers to capture for render video worker
RENDER_VIDEO_WORKER_LOGGERS = [
"lyrics_transcriber.output",
"lyrics_transcriber.output.generator",
"lyrics_transcriber.output.video",
"lyrics_transcriber.output.ass",
"karaoke_gen.lyrics_transcriber.output",
"karaoke_gen.lyrics_transcriber.output.generator",
"karaoke_gen.lyrics_transcriber.output.video",
"karaoke_gen.lyrics_transcriber.output.ass",
]
+1 -7
View File
@@ -322,13 +322,7 @@ async def generate_video_orchestrated(job_id: str) -> bool:
)
# Upload generated files to GCS
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.PACKAGING,
progress=95,
message="Uploading final files"
)
# Note: State transition to PACKAGING is handled by the orchestrator in _run_distribution()
with job_span("upload-results", job_id):
await _upload_results(job_id, job_manager, storage, temp_dir, {
'final_video': result.final_video,
+3 -3
View File
@@ -65,7 +65,7 @@ class JobLogHandler(logging.Handler):
lyrics_logger.addHandler(handler)
# Also capture logs from lyrics_transcriber package itself
lt_logger = logging.getLogger("lyrics_transcriber")
lt_logger = logging.getLogger("karaoke_gen.lyrics_transcriber")
lt_logger.addHandler(handler)
"""
@@ -235,7 +235,7 @@ def setup_job_logging(job_id: str, worker_name: str, *logger_names: str) -> JobL
Args:
job_id: Job ID
worker_name: Worker name
*logger_names: Names of loggers to capture (e.g., "lyrics_transcriber", "karaoke_gen")
*logger_names: Names of loggers to capture (e.g., "karaoke_gen.lyrics_transcriber", "karaoke_gen")
Returns:
The JobLogHandler (can be removed later if needed)
@@ -246,7 +246,7 @@ def setup_job_logging(job_id: str, worker_name: str, *logger_names: str) -> JobL
job_id,
"lyrics",
"karaoke_gen.lyrics_processor",
"lyrics_transcriber", # Capture LyricsTranscriber logs
"karaoke_gen.lyrics_transcriber", # Capture LyricsTranscriber logs
)
# IMPORTANT: Use job_logging_context for proper isolation
+1 -1
View File
@@ -265,7 +265,7 @@ gcloud logging read 'resource.type="cloud_run_revision" "ANCHOR SEARCH: Progress
When adding new operations that may need investigation:
```python
from lyrics_transcriber.utils.tracing import create_span, add_span_attribute
from karaoke_gen.lyrics_transcriber.utils.tracing import create_span, add_span_attribute
with create_span("operation_name", {"initial": "attributes"}) as span:
# ... do work ...
+2 -2
View File
@@ -285,7 +285,7 @@ async def process_audio_separation_task(job_id: str):
```python
# backend/workers/lyrics_worker.py
from karaoke_gen.lyrics_processor import LyricsProcessor
from lyrics_transcriber.transcriber import LyricsTranscriber
from karaoke_gen.lyrics_transcriber.transcriber import LyricsTranscriber
import os
async def process_lyrics_transcription_task(job_id: str):
@@ -735,7 +735,7 @@ async def encode_videos_task(job_id: str):
**Implementation:**
```python
# backend/workers/packaging_worker.py
from lyrics_transcriber.output.cdg import CDGGenerator
from karaoke_gen.lyrics_transcriber.output.cdg import CDGGenerator
from lyrics_converter import convert_lrc_to_txt
async def generate_cdg_package(job_id: str, work_dir: str):
+3 -3
View File
@@ -246,9 +246,9 @@ import logging
import tempfile
from typing import Optional
from lyrics_transcriber.output.generator import OutputGenerator
from lyrics_transcriber.correction.corrector import CorrectionResult
from lyrics_transcriber.core.config import OutputConfig
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
from karaoke_gen.lyrics_transcriber.correction.corrector import CorrectionResult
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
from backend.services.job_manager import job_manager
from backend.services.storage_service import storage
@@ -175,8 +175,8 @@ config = LyricsTranscriberConfig(
**Key Insight:** Uses `OutputGenerator` from LyricsTranscriber library:
```python
from lyrics_transcriber.output.generator import OutputGenerator
from lyrics_transcriber.correction.corrector import CorrectionResult
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
from karaoke_gen.lyrics_transcriber.correction.corrector import CorrectionResult
# Load corrected data (from human review)
correction_result = CorrectionResult.from_dict(corrections_data)
@@ -382,9 +382,9 @@ POST /api/jobs/{job_id}/select-instrumental
### Example: Using OutputGenerator
```python
from lyrics_transcriber.output.generator import OutputGenerator
from lyrics_transcriber.correction.corrector import CorrectionResult
from lyrics_transcriber.core.config import OutputConfig
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
from karaoke_gen.lyrics_transcriber.correction.corrector import CorrectionResult
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
# 1. Load corrected data from GCS (after human review)
corrections_data = download_json_from_gcs(f"jobs/{job_id}/corrections_updated.json")
@@ -181,7 +181,7 @@ You can also detect from LRC files:
To disable countdown for a specific transcription:
```python
from lyrics_transcriber.core.config import OutputConfig
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
output_config = OutputConfig(
# ... other options
+2 -2
View File
@@ -1035,8 +1035,8 @@ function AdminJobsPageContent() {
</p>
{[
{ key: "theme_id", label: "Theme", value: selectedJob.theme_id || "default" },
{ key: "brand_prefix", label: "Brand Prefix", value: (selectedJob as any).brand_prefix },
{ key: "customer_email", label: "Customer Email", value: (selectedJob as any).customer_email },
{ key: "brand_prefix", label: "Brand Prefix", value: selectedJob.brand_prefix },
{ key: "customer_email", label: "Customer Email", value: selectedJob.customer_email },
].map(({ key, label, value }) => (
<div key={key} className="flex items-center gap-2 mb-2">
<span className="text-sm font-medium w-28">{label}:</span>
@@ -69,7 +69,7 @@ const mockOverrides = {
{
email: "vip@example.com",
bypass_job_limit: true,
custom_daily_job_limit: null,
custom_daily_job_limit: undefined,
reason: "VIP user",
created_by: "admin@nomadkaraoke.com",
created_at: "2025-01-08T15:00:00Z",
@@ -242,7 +242,7 @@ describe("AdminRateLimitsPage", () => {
})
it("adds a disposable domain", async () => {
mockAdminApi.addDisposableDomain.mockResolvedValue({ success: true })
mockAdminApi.addDisposableDomain.mockResolvedValue({ success: true, message: "Operation successful" })
const user = userEvent.setup()
render(<AdminRateLimitsPage />)
@@ -339,7 +339,7 @@ describe("AdminRateLimitsPage", () => {
})
it("creates a new override", async () => {
mockAdminApi.setUserOverride.mockResolvedValue({ success: true })
mockAdminApi.setUserOverride.mockResolvedValue({ success: true, message: "Operation successful" })
const user = userEvent.setup()
render(<AdminRateLimitsPage />)
+52 -15
View File
@@ -1,7 +1,7 @@
"use client"
import { useEffect, useState, useCallback } from "react"
import { useParams, useRouter } from "next/navigation"
import { useParams } from "next/navigation"
import { useAuth } from "@/lib/auth"
import { api, Job, createLyricsReviewApiClient, lyricsReviewApi } from "@/lib/api"
import { Spinner } from "@/components/ui/spinner"
@@ -12,7 +12,7 @@ import { InstrumentalSelector } from "@/components/instrumental-review"
import { LyricsAnalyzer } from "@/components/lyrics-review"
import { ThemeToggle } from "@/components/ThemeToggle"
import type { CorrectionData } from "@/lib/lyrics-review/types"
import { isLocalMode, createLocalModeJob, getLocalJobId } from "@/lib/local-mode"
import { isLocalMode, createLocalModeJob } from "@/lib/local-mode"
type RouteType = "review" | "instrumental" | "unknown"
@@ -26,7 +26,8 @@ type AccessState =
| { status: "authorized"; job: Job; routeType: RouteType }
| { status: "local_mode"; job: Job; routeType: RouteType }
function parseRoute(slug: string[] | undefined): { jobId: string | null; routeType: RouteType } {
// Parse route from Next.js slug params (used for local mode with path-based routing)
function parseRouteFromSlug(slug: string[] | undefined): { jobId: string | null; routeType: RouteType } {
if (!slug || slug.length === 0) {
return { jobId: null, routeType: "unknown" }
}
@@ -47,6 +48,24 @@ function parseRoute(slug: string[] | undefined): { jobId: string | null; routeTy
return { jobId: null, routeType: "unknown" }
}
// Parse route from URL hash (used for cloud mode)
// Expected format: #/{jobId}/review or #/{jobId}/instrumental
function parseRouteFromHash(hash: string): { jobId: string | null; routeType: RouteType } {
if (!hash || hash.length <= 1) {
return { jobId: null, routeType: "unknown" }
}
// Remove the leading '#' and parse
const hashPath = hash.substring(1)
const match = hashPath.match(/^\/?([^/]+)\/(review|instrumental)\/?$/)
if (match) {
const [, jobId, action] = match
return { jobId, routeType: action as RouteType }
}
return { jobId: null, routeType: "unknown" }
}
function getExpectedStates(routeType: RouteType): string[] {
switch (routeType) {
case "review":
@@ -60,20 +79,38 @@ function getExpectedStates(routeType: RouteType): string[] {
export function JobRouterClient() {
const params = useParams()
const router = useRouter()
const slug = params.slug as string[] | undefined
const { jobId, routeType } = parseRoute(slug)
// Track hash for re-renders when hash changes
const [hash, setHash] = useState(() =>
typeof window !== 'undefined' ? window.location.hash : ''
)
const { user, isLoading: authLoading } = useAuth()
// Listen for hash changes
useEffect(() => {
const handleHashChange = () => {
setHash(window.location.hash)
}
window.addEventListener('hashchange', handleHashChange)
return () => window.removeEventListener('hashchange', handleHashChange)
}, [])
// Determine routing mode and parse route
// - Local mode: Use path-based routing from Next.js slug params
// - Cloud mode: Use hash-based routing (e.g., /app/jobs/#/{jobId}/review)
const inLocalMode = isLocalMode()
const { jobId, routeType } = inLocalMode
? parseRouteFromSlug(slug)
: parseRouteFromHash(hash)
const { user, isLoading: authLoading, hasHydrated } = useAuth()
const [accessState, setAccessState] = useState<AccessState>({ status: "loading" })
useEffect(() => {
async function checkAccess() {
// Check for local mode first (skip all auth checks)
if (isLocalMode()) {
// Handle local mode (skip all auth checks)
if (inLocalMode) {
// In local mode, determine route type from URL or default to review
// The local server will redirect to /app/jobs/local/review or /app/jobs/local/instrumental
let localRouteType: RouteType = routeType
// If route is unknown but we're in local mode, try to determine from path
@@ -92,14 +129,15 @@ export function JobRouterClient() {
return
}
// Invalid route (cloud mode)
// Cloud mode: Check hash-based route
if (!jobId || routeType === "unknown") {
setAccessState({ status: "invalid_route" })
return
}
// Wait for auth to finish loading
if (authLoading) return
// Wait for auth to finish loading and hydration to complete
// This prevents a flash of "Sign in required" before auth state is restored from localStorage
if (authLoading || !hasHydrated) return
// Must be authenticated
if (!user) {
@@ -150,7 +188,7 @@ export function JobRouterClient() {
}
checkAccess()
}, [jobId, routeType, user, authLoading])
}, [inLocalMode, jobId, routeType, user, authLoading, hasHydrated])
// Loading state
if (accessState.status === "loading") {
@@ -267,7 +305,6 @@ export function JobRouterClient() {
// Authorized or local mode - render the appropriate UI
const { job, routeType: authorizedRouteType } = accessState
const inLocalMode = accessState.status === "local_mode"
if (authorizedRouteType === "review") {
return <LyricsReviewWrapper job={job} isLocalMode={inLocalMode} />
@@ -369,7 +406,7 @@ function LyricsReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMo
)}
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src="/static/nomad-karaoke-logo.svg"
src="/nomad-karaoke-logo.svg"
alt="Nomad Karaoke"
style={{ height: 40 }}
/>
@@ -12,7 +12,7 @@ jest.mock('@/lib/auth', () => ({
useAuth: jest.fn(),
}))
const mockUseAuth = useAuth as jest.Mock
const mockUseAuth = useAuth as unknown as jest.Mock
// Mock window.location.reload
const mockReload = jest.fn()
@@ -99,8 +99,9 @@ describe('JobCard', () => {
const reviewLink = screen.getByText('Review Lyrics')
expect(reviewLink).toBeInTheDocument()
const href = reviewLink.closest('a')?.getAttribute('href') || ''
// Now uses internal routes instead of external URLs
expect(href).toBe('/app/jobs/123/review')
// Uses hash-based routing for static hosting
// Uses <a> tag (not Next.js Link) to ensure hashchange event fires
expect(href).toBe('/app/jobs#/123/review')
})
it('shows audio search button for awaiting_audio_selection status', () => {
@@ -121,8 +122,9 @@ describe('JobCard', () => {
const instrumentalLink = screen.getByText('Select Instrumental')
expect(instrumentalLink).toBeInTheDocument()
const href = instrumentalLink.closest('a')?.getAttribute('href') || ''
// Now uses internal routes instead of external URLs
expect(href).toBe('/app/jobs/123/instrumental')
// Uses hash-based routing for static hosting
// Uses <a> tag (not Next.js Link) to ensure hashchange event fires
expect(href).toBe('/app/jobs#/123/instrumental')
})
it('does not show Auto badge for regular jobs', () => {
+13 -3
View File
@@ -17,6 +17,7 @@ interface StatsCardProps {
}
loading?: boolean
className?: string
valueClassName?: string
}
export function StatsCard({
@@ -27,6 +28,7 @@ export function StatsCard({
trend,
loading,
className,
valueClassName,
}: StatsCardProps) {
if (loading) {
return (
@@ -53,7 +55,7 @@ export function StatsCard({
{Icon && <Icon className="h-4 w-4 text-muted-foreground" />}
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{value}</div>
<div className={cn("text-2xl font-bold", valueClassName)}>{value}</div>
{description && (
<p className="text-xs text-muted-foreground mt-1">{description}</p>
)}
@@ -73,12 +75,20 @@ export function StatsCard({
interface StatsGridProps {
children: React.ReactNode
className?: string
columns?: 2 | 3 | 4
}
export function StatsGrid({ children, className }: StatsGridProps) {
export function StatsGrid({ children, className, columns }: StatsGridProps) {
const colsClass = columns === 2
? "md:grid-cols-2"
: columns === 3
? "md:grid-cols-2 lg:grid-cols-3"
: "md:grid-cols-2 lg:grid-cols-4"
return (
<div className={cn(
"grid gap-4 md:grid-cols-2 lg:grid-cols-4",
"grid gap-4",
colsClass,
className
)}>
{children}
+8 -7
View File
@@ -1,7 +1,6 @@
"use client"
import { useState } from "react"
import Link from "next/link"
import { Job } from "@/lib/api"
import { Button } from "@/components/ui/button"
import { Zap } from "lucide-react"
@@ -102,13 +101,14 @@ export function JobCard({ job, onRefresh }: JobCardProps) {
}
if (job.status === "awaiting_review" || job.status === "in_review") {
// Use <a> instead of Link for hash-based URLs to ensure hashchange event fires
return (
<Link
href={`/app/jobs/${job.job_id}/review`}
<a
href={`/app/jobs#/${job.job_id}/review`}
className="inline-flex items-center gap-1 text-xs px-3 py-1.5 rounded bg-primary-500 hover:bg-primary-600 text-white"
>
Review Lyrics
</Link>
</a>
)
}
@@ -125,13 +125,14 @@ export function JobCard({ job, onRefresh }: JobCardProps) {
}
if (job.status === "awaiting_instrumental_selection") {
// Use <a> instead of Link for hash-based URLs to ensure hashchange event fires
return (
<Link
href={`/app/jobs/${job.job_id}/instrumental`}
<a
href={`/app/jobs#/${job.job_id}/instrumental`}
className="inline-flex items-center gap-1 text-xs px-3 py-1.5 rounded bg-primary-500 hover:bg-primary-600 text-white"
>
Select Instrumental
</Link>
</a>
)
}
+1 -1
View File
@@ -7,7 +7,7 @@ function Card({ className, ...props }: React.ComponentProps<'div'>) {
<div
data-slot="card"
className={cn(
'bg-card text-card-foreground flex flex-col gap-1 rounded-lg border shadow-sm',
'bg-card text-card-foreground flex flex-col gap-1 rounded-lg border py-6 shadow-sm',
className,
)}
{...props}
+12 -6
View File
@@ -25,10 +25,14 @@ const DialogOverlay = React.forwardRef<
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
interface DialogContentProps extends React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> {
showCloseButton?: boolean
}
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
DialogContentProps
>(({ className, children, showCloseButton = true, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
@@ -40,10 +44,12 @@ const DialogContent = React.forwardRef<
{...props}
>
{children}
<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>
{showCloseButton && (
<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>
)}
</DialogPrimitive.Content>
</DialogPortal>
))
+1 -1
View File
@@ -21,7 +21,7 @@ yarn dev # Starts on port 5173
# Terminal 2: Start LyricsTranscriber backend (for API)
# This serves the review API on port 8767
poetry run python -c "from lyrics_transcriber.review.server import ReviewServer; ..."
poetry run python -c "from karaoke_gen.lyrics_transcriber.review.server import ReviewServer; ..."
# Terminal 3: Run the test
cd frontend
@@ -243,7 +243,7 @@ async function testLyricsReview(page: any, context: any, jobId: string) {
console.log(` WARNING: Preview error: ${errorText}`);
} else if (await videoElement.isVisible({ timeout: 10000 }).catch(() => false)) {
console.log(' Video element visible');
const videoState = await videoElement.first().evaluate((el) => {
const videoState = await videoElement.first().evaluate((el: Element) => {
const video = el as HTMLVideoElement;
return {
src: video.src?.substring(0, 50),
+1
View File
@@ -0,0 +1 @@
/// <reference types="@testing-library/jest-dom" />
+17 -6
View File
@@ -55,6 +55,7 @@ export interface Job {
title?: string;
filename?: string;
error_message?: string;
error_details?: Record<string, any>;
file_urls?: Record<string, any>;
state_data?: Record<string, any>;
timeline?: Array<{
@@ -70,6 +71,16 @@ export interface Job {
user_email?: string;
outputs_deleted_at?: string;
outputs_deleted_by?: string;
// Audio search fields
audio_search_artist?: string;
audio_search_title?: string;
// Theme and branding
theme_id?: string;
brand_prefix?: string;
// Customer order fields
customer_email?: string;
// Request tracking metadata
request_metadata?: Record<string, any>;
}
export interface UploadJobResponse {
@@ -1699,7 +1710,7 @@ export function createLyricsReviewApiClient(jobId: string): LyricsReviewApiClien
*/
getAudioUrl(hash: string): string {
const token = getAccessToken()
const base = `${API_BASE_URL}/api/audio/${hash}`
const base = `${API_BASE_URL}/api/review/${jobId}/audio/${hash}`
return token ? `${base}?token=${encodeURIComponent(token)}` : base
},
@@ -1711,7 +1722,7 @@ export function createLyricsReviewApiClient(jobId: string): LyricsReviewApiClien
message?: string
preview_hash?: string
}> {
const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/preview-video`, {
const response = await fetch(`${API_BASE_URL}/api/review/${jobId}/preview-video`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@@ -1727,7 +1738,7 @@ export function createLyricsReviewApiClient(jobId: string): LyricsReviewApiClien
*/
getPreviewVideoUrl(hash: string): string {
const token = getAccessToken()
const base = `${API_BASE_URL}/api/preview-video/${hash}`
const base = `${API_BASE_URL}/api/review/${jobId}/preview-video/${hash}`
return token ? `${base}?token=${encodeURIComponent(token)}` : base
},
}
@@ -1739,7 +1750,7 @@ export const lyricsReviewApi = {
* Get correction data for a job
*/
async getCorrectionData(jobId: string): Promise<CorrectionData> {
const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/corrections`, {
const response = await fetch(`${API_BASE_URL}/api/review/${jobId}/correction-data`, {
headers: getAuthHeaders()
})
return handleResponse<CorrectionData>(response)
@@ -1748,9 +1759,9 @@ export const lyricsReviewApi = {
/**
* Get audio URL for a job by hash
*/
getAudioUrl(hash: string): string {
getAudioUrl(jobId: string, hash: string): string {
const token = getAccessToken()
const base = `${API_BASE_URL}/api/audio/${hash}`
const base = `${API_BASE_URL}/api/review/${jobId}/audio/${hash}`
return token ? `${base}?token=${encodeURIComponent(token)}` : base
},
}
+11
View File
@@ -10,6 +10,9 @@ interface AuthStore {
isLoading: boolean
error: string | null
// Hydration state - true once zustand has loaded persisted data
hasHydrated: boolean
// Impersonation state (not persisted)
isImpersonating: boolean
originalAdminToken: string | null
@@ -22,6 +25,7 @@ interface AuthStore {
logout: () => Promise<void>
updateCredits: (credits: number) => void
clearError: () => void
setHasHydrated: (state: boolean) => void
// For legacy token-based auth (admin tokens)
loginWithToken: (token: string) => Promise<boolean>
@@ -37,12 +41,15 @@ export const useAuth = create<AuthStore>()(
user: null,
isLoading: false,
error: null,
hasHydrated: false,
// Impersonation state
isImpersonating: false,
originalAdminToken: null,
impersonatedUserEmail: null,
setHasHydrated: (state: boolean) => set({ hasHydrated: state }),
sendMagicLink: async (email: string) => {
set({ isLoading: true, error: null })
try {
@@ -259,6 +266,10 @@ export const useAuth = create<AuthStore>()(
name: "nomad-karaoke-auth",
// Only persist user, not impersonation state (impersonation should not survive page refresh)
partialize: (state) => ({ user: state.user }),
onRehydrateStorage: () => (state) => {
// Called when hydration is complete
state?.setHasHydrated(true)
},
},
),
)
+1 -1
View File
@@ -3,7 +3,7 @@
"version": "0.84.0",
"private": true,
"scripts": {
"build": "next build",
"build": "next build && node scripts/spa-redirect-404.js",
"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",
+7
View File
@@ -0,0 +1,7 @@
# Cloudflare Pages redirects/rewrites
# https://developers.cloudflare.com/pages/configuration/redirects/
# Note: With hash-based routing (e.g., /app/jobs/#/{jobId}/review),
# no server-side redirects are needed. The hash portion is never sent
# to the server, so all requests go to /app/jobs/ and routing is
# handled client-side.
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env node
/**
* Post-build script for 404.html
*
* Previously, this injected SPA redirect logic for path-based routing.
* Now that we use hash-based routing (e.g., /app/jobs/#/{jobId}/review),
* the redirect is no longer needed - the hash is handled client-side and
* never sent to the server.
*
* This script is kept as a no-op for backwards compatibility with the build process.
*/
console.log('Hash-based routing enabled - no SPA redirect injection needed');
+152
View File
@@ -0,0 +1,152 @@
import { chromium } from 'playwright';
const BASE_URL = 'https://gen.nomadkaraoke.com';
const ADMIN_TOKEN = '9021de39710208e5dc31b6b28baf8e94172843fff177a9d5435135dd5388b6f8';
const JOB_ID = '26391a79';
const CACHE_BUSTER = Date.now();
async function test() {
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext();
const page = await context.newPage();
const consoleErrors = [];
const failedRequests = [];
// Capture console errors
page.on('console', msg => {
const text = msg.text();
const type = msg.type();
if (type === 'error' || text.toLowerCase().includes('error') || text.toLowerCase().includes('fail')) {
consoleErrors.push({ type, text });
}
});
// Capture failed HTTP requests (excluding expected ones)
page.on('response', response => {
const status = response.status();
const url = response.url();
// Ignore YouTube, Cloudflare RUM, and static 404 redirects
if (status >= 400 &&
!url.includes('youtube.com') &&
!url.includes('cdn-cgi/rum') &&
!url.includes('__next._tree')) {
failedRequests.push({
url,
status,
statusText: response.statusText()
});
}
});
console.log('\n=== Final Production Test ===\n');
try {
// Step 1: Set auth token
console.log('Step 1: Navigate to /app and set auth token');
await page.goto(BASE_URL + '/app?_cb=' + CACHE_BUSTER, { waitUntil: 'networkidle' });
await page.evaluate((token) => {
localStorage.setItem('karaoke_access_token', token);
}, ADMIN_TOKEN);
await page.reload({ waitUntil: 'networkidle' });
// Step 2: Navigate to review page
console.log('Step 2: Navigate to /app/jobs/' + JOB_ID + '/review/');
await page.goto(BASE_URL + '/app/jobs/' + JOB_ID + '/review/?_cb=' + CACHE_BUSTER, {
waitUntil: 'networkidle',
timeout: 30000
});
await page.waitForTimeout(5000);
// Check URL (should be updated via history.replaceState)
const currentUrl = page.url();
console.log('\n--- URL Check ---');
console.log('Final URL:', currentUrl);
if (currentUrl.includes(JOB_ID + '/review')) {
console.log('URL contains job ID and review path');
} else if (currentUrl.endsWith('/app/jobs/')) {
console.log('URL was NOT updated (still at /app/jobs/)');
}
// Check page content
const bodyText = await page.evaluate(() => document.body.innerText);
console.log('\n--- Page Content Check ---');
if (bodyText.includes('Lyrics Transcription Review')) {
console.log('Page header found: "Lyrics Transcription Review"');
}
if (bodyText.includes('Failed to load')) {
console.log('ERROR: Page shows failure message');
}
// Check logo
console.log('\n--- Logo Check ---');
const logoLoaded = await page.evaluate(() => {
const img = document.querySelector('img[alt="Nomad Karaoke"]');
return img ? img.complete && img.naturalHeight > 0 : false;
});
console.log('Logo loaded:', logoLoaded);
// Check for audio element
console.log('\n--- Audio Check ---');
const audioSrc = await page.evaluate(() => {
const audio = document.querySelector('audio');
return audio ? audio.src : null;
});
if (audioSrc) {
console.log('Audio src:', audioSrc);
if (audioSrc.includes('/api/review/')) {
console.log('Audio URL uses correct /api/review/ path');
}
} else {
console.log('No audio element found on page');
}
// Report failed requests
console.log('\n--- Failed HTTP Requests (excluding expected) ---');
const relevantFailures = failedRequests.filter(r =>
!r.url.includes(JOB_ID + '/review') // Exclude initial 404 redirect
);
if (relevantFailures.length === 0) {
console.log('No unexpected failed requests');
} else {
relevantFailures.forEach((req, i) => {
console.log((i + 1) + '. HTTP ' + req.status + ' ' + req.statusText + ': ' + req.url.substring(0, 100));
});
}
// Report console errors
console.log('\n--- Console Errors ---');
const relevantErrors = consoleErrors.filter(e =>
!e.text.includes('404') // Exclude 404 console errors from initial redirect
);
if (relevantErrors.length === 0) {
console.log('No relevant console errors');
} else {
relevantErrors.forEach((err, i) => {
console.log((i + 1) + '. [' + err.type + '] ' + err.text.substring(0, 150));
});
}
// Step 3: Test reload
console.log('\n--- Reload Test ---');
await page.reload({ waitUntil: 'networkidle' });
await page.waitForTimeout(3000);
const reloadUrl = page.url();
const reloadBody = await page.evaluate(() => document.body.innerText);
console.log('URL after reload:', reloadUrl);
if (reloadBody.includes('Lyrics Transcription Review')) {
console.log('Reload SUCCESS: Page still shows lyrics review');
} else if (reloadBody.includes('Page not found')) {
console.log('Reload FAILED: Shows "Page not found"');
} else {
console.log('Reload result unclear. Content preview:', reloadBody.substring(0, 100));
}
} catch (e) {
console.log('Error:', e.message);
}
await browser.close();
}
test().catch(console.error);
+78
View File
@@ -0,0 +1,78 @@
import { chromium } from 'playwright';
const BASE_URL = 'https://gen.nomadkaraoke.com';
const ADMIN_TOKEN = '9021de39710208e5dc31b6b28baf8e94172843fff177a9d5435135dd5388b6f8';
const JOB_ID = '26391a79';
const CACHE_BUSTER = Date.now();
async function test() {
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext();
const page = await context.newPage();
// Log ALL console messages
page.on('console', msg => {
console.log('CONSOLE [' + msg.type() + ']:', msg.text());
});
console.log('\n=== URL Debug Test ===\n');
try {
// Set auth token
await page.goto(BASE_URL + '/app', { waitUntil: 'networkidle' });
await page.evaluate((token) => {
localStorage.setItem('karaoke_access_token', token);
}, ADMIN_TOKEN);
// Navigate to review page and watch URL changes
console.log('Navigating to review page...');
// Watch URL changes
let urlLog = [];
page.on('framenavigated', frame => {
if (frame === page.mainFrame()) {
urlLog.push({ time: Date.now(), url: frame.url() });
}
});
await page.goto(BASE_URL + '/app/jobs/' + JOB_ID + '/review/?_cb=' + CACHE_BUSTER, {
waitUntil: 'domcontentloaded'
});
// Check sessionStorage before it gets consumed
const storedPath = await page.evaluate(() => {
return sessionStorage.getItem('spa-redirect-path');
});
console.log('SessionStorage spa-redirect-path:', storedPath);
await page.waitForTimeout(3000);
console.log('\nURL history:');
urlLog.forEach((entry, i) => {
console.log(i + 1 + '. ' + entry.url);
});
console.log('\nFinal URL:', page.url());
// Check if history.replaceState is being called
const historyState = await page.evaluate(() => {
return {
url: window.location.href,
pathname: window.location.pathname,
historyLength: window.history.length
};
});
console.log('History state:', historyState);
// Check body content
const content = await page.evaluate(() => document.body.innerText.substring(0, 200));
console.log('\nPage content preview:', content);
} catch (e) {
console.log('Error:', e.message);
}
await browser.close();
}
test().catch(console.error);
@@ -19,7 +19,7 @@ import time
from google.oauth2.credentials import Credentials
import base64
from email.mime.text import MIMEText
from lyrics_transcriber.output.cdg import CDGGenerator
from karaoke_gen.lyrics_transcriber.output.cdg import CDGGenerator
from ..utils import sanitize_filename
@@ -49,6 +49,7 @@ class KaraokeFinalise:
server_side_mode=False, # New parameter for server-side deployment
selected_instrumental_file=None, # Add support for pre-selected instrumental file
countdown_padding_seconds=None, # Padding applied to vocals; instrumental must match
no_video=False, # Skip video encoding and distribution
):
self.log_level = log_level
self.log_formatter = log_formatter
@@ -111,6 +112,7 @@ class KaraokeFinalise:
self.server_side_mode = server_side_mode
self.selected_instrumental_file = selected_instrumental_file
self.countdown_padding_seconds = countdown_padding_seconds
self.no_video = no_video
self.suffixes = {
"title_mov": " (Title).mov",
@@ -167,12 +169,15 @@ class KaraokeFinalise:
self.logger.info(f"Checking required input files exist...")
input_files = {
"title_mov": f"{base_name}{self.suffixes['title_mov']}",
"title_jpg": f"{base_name}{self.suffixes['title_jpg']}",
"instrumental_audio": instrumental_audio_file,
"with_vocals_mov": with_vocals_file,
}
# Video files are only required when not in --no-video mode
if not self.no_video:
input_files["title_mov"] = f"{base_name}{self.suffixes['title_mov']}"
input_files["title_jpg"] = f"{base_name}{self.suffixes['title_jpg']}"
input_files["with_vocals_mov"] = with_vocals_file
optional_input_files = {
"end_mov": f"{base_name}{self.suffixes['end_mov']}",
"end_jpg": f"{base_name}{self.suffixes['end_jpg']}",
@@ -190,9 +195,9 @@ class KaraokeFinalise:
for key, file_path in optional_input_files.items():
if not os.path.isfile(file_path):
self.logger.info(f" Optional input file {key} not found: {file_path}")
self.logger.info(f" Input file {key} found, adding to input_files: {file_path}")
input_files[key] = file_path
else:
self.logger.info(f" Input file {key} found, adding to input_files: {file_path}")
input_files[key] = file_path
return input_files
@@ -1776,9 +1781,25 @@ class KaraokeFinalise:
# Check required input files and parameters exist, get user to confirm features before proceeding
self.validate_input_parameters_for_features()
with_vocals_file = self.find_with_vocals_file()
base_name, artist, title = self.get_names_from_withvocals(with_vocals_file)
# When --no-video is set, we don't have a (With Vocals).mkv file
# Extract artist/title from the current directory name instead
if self.no_video:
with_vocals_file = None
# Current directory should be "Artist - Title"
dir_name = os.path.basename(os.getcwd())
if " - " in dir_name:
artist, title = dir_name.split(" - ", 1)
base_name = dir_name
self.logger.info(f"--no-video mode: extracted artist/title from directory name: {dir_name}")
else:
raise Exception(
f"Cannot extract artist/title from directory name '{dir_name}'. "
"Expected format: 'Artist - Title'"
)
else:
with_vocals_file = self.find_with_vocals_file()
base_name, artist, title = self.get_names_from_withvocals(with_vocals_file)
self.logger.info(f"Processing: {artist} - {title}")
# Use the selected instrumental file if provided, otherwise search for one
@@ -1804,35 +1825,55 @@ class KaraokeFinalise:
self.create_txt_zip_file(input_files, output_files)
self.logger.info("TXT package created successfully")
self.logger.info("Starting video encoding (this is the longest step, ~15-20 minutes)...")
self.remux_and_encode_output_video_files(with_vocals_file, input_files, output_files)
self.logger.info("Video encoding completed successfully")
if not self.no_video:
self.logger.info("Starting video encoding (this is the longest step, ~15-20 minutes)...")
self.remux_and_encode_output_video_files(with_vocals_file, input_files, output_files)
self.logger.info("Video encoding completed successfully")
self.logger.info("Executing distribution features (YouTube, Dropbox, Discord)...")
self.execute_optional_features(artist, title, base_name, input_files, output_files, replace_existing)
self.logger.info("Executing distribution features (YouTube, Dropbox, Discord)...")
self.execute_optional_features(artist, title, base_name, input_files, output_files, replace_existing)
else:
self.logger.info("--no-video flag set: Skipping video encoding and distribution")
result = {
"artist": artist,
"title": title,
"video_with_vocals": output_files["with_vocals_mp4"],
"video_with_instrumental": output_files["karaoke_mp4"],
"final_video": output_files["final_karaoke_lossless_mp4"],
"final_video_mkv": output_files["final_karaoke_lossless_mkv"],
"final_video_lossy": output_files["final_karaoke_lossy_mp4"],
"final_video_720p": output_files["final_karaoke_lossy_720p_mp4"],
"youtube_url": self.youtube_url,
"brand_code": self.brand_code,
"new_brand_code_dir_path": self.new_brand_code_dir_path,
"brand_code_dir_sharing_link": self.brand_code_dir_sharing_link,
}
if not self.no_video:
result.update({
"video_with_vocals": output_files["with_vocals_mp4"],
"video_with_instrumental": output_files["karaoke_mp4"],
"final_video": output_files["final_karaoke_lossless_mp4"],
"final_video_mkv": output_files["final_karaoke_lossless_mkv"],
"final_video_lossy": output_files["final_karaoke_lossy_mp4"],
"final_video_720p": output_files["final_karaoke_lossy_720p_mp4"],
"youtube_url": self.youtube_url,
"brand_code": self.brand_code,
"new_brand_code_dir_path": self.new_brand_code_dir_path,
"brand_code_dir_sharing_link": self.brand_code_dir_sharing_link,
})
else:
result.update({
"video_with_vocals": None,
"video_with_instrumental": None,
"final_video": None,
"final_video_mkv": None,
"final_video_lossy": None,
"final_video_720p": None,
"youtube_url": None,
"brand_code": None,
"new_brand_code_dir_path": None,
"brand_code_dir_sharing_link": None,
})
if self.enable_cdg:
result["final_karaoke_cdg_zip"] = output_files["final_karaoke_cdg_zip"]
if self.enable_txt:
result["final_karaoke_txt_zip"] = output_files["final_karaoke_txt_zip"]
if self.email_template_file:
if self.email_template_file and not self.no_video:
self.draft_completion_email(artist, title, result["youtube_url"], result["brand_code_dir_sharing_link"])
return result
+6 -6
View File
@@ -32,10 +32,10 @@ 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
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig as LyricsOutputConfig
class KaraokePrep:
@@ -898,7 +898,7 @@ class KaraokePrep:
processed_track["title_video"] = os.path.join(track_output_dir, f"{artist_title} (Title).mov")
# Use FileHandler._file_exists
if not self.file_handler._file_exists(processed_track["title_video"]) and not os.environ.get("KARAOKE_GEN_SKIP_TITLE_END_SCREENS"):
if self.render_video and not self.file_handler._file_exists(processed_track["title_video"]) and not os.environ.get("KARAOKE_GEN_SKIP_TITLE_END_SCREENS"):
self.logger.info(f"Creating title video...")
# Delegate to VideoGenerator
self.video_generator.create_title_video(
@@ -917,7 +917,7 @@ class KaraokePrep:
processed_track["end_video"] = os.path.join(track_output_dir, f"{artist_title} (End).mov")
# Use FileHandler._file_exists
if not self.file_handler._file_exists(processed_track["end_video"]) and not os.environ.get("KARAOKE_GEN_SKIP_TITLE_END_SCREENS"):
if self.render_video and not self.file_handler._file_exists(processed_track["end_video"]) and not os.environ.get("KARAOKE_GEN_SKIP_TITLE_END_SCREENS"):
self.logger.info(f"Creating end screen video...")
# Delegate to VideoGenerator
self.video_generator.create_end_video(
+3 -2
View File
@@ -4,8 +4,8 @@ import logging
import shutil
import json
from typing import Optional
from lyrics_transcriber import LyricsTranscriber, OutputConfig, TranscriberConfig, LyricsConfig
from lyrics_transcriber.core.controller import LyricsControllerResult
from karaoke_gen.lyrics_transcriber import LyricsTranscriber, OutputConfig, TranscriberConfig, LyricsConfig
from karaoke_gen.lyrics_transcriber.core.controller import LyricsControllerResult
from dotenv import load_dotenv
from .utils import sanitize_filename
@@ -401,6 +401,7 @@ class LyricsProcessor:
output_styles_json=self.style_params_json,
output_dir=lyrics_dir,
render_video=False, # Always defer - caller handles video rendering after countdown
allow_preview_video=self.render_video, # Allow preview videos unless --no-video is set
fetch_lyrics=True,
run_transcription=not self.skip_transcription,
run_correction=True,
@@ -1,5 +1,5 @@
from lyrics_transcriber.core.config import TranscriberConfig, LyricsConfig, OutputConfig
from lyrics_transcriber.core.controller import LyricsTranscriber
from karaoke_gen.lyrics_transcriber.core.config import TranscriberConfig, LyricsConfig, OutputConfig
from karaoke_gen.lyrics_transcriber.core.controller import LyricsTranscriber
from importlib.metadata import version, PackageNotFoundError
try:
@@ -11,8 +11,8 @@ from typing import Dict
from importlib.metadata import version
from dotenv import load_dotenv
from lyrics_transcriber import LyricsTranscriber
from lyrics_transcriber.core.controller import TranscriberConfig, LyricsConfig, OutputConfig
from karaoke_gen.lyrics_transcriber import LyricsTranscriber
from karaoke_gen.lyrics_transcriber.core.controller import TranscriberConfig, LyricsConfig, OutputConfig
def create_arg_parser() -> argparse.ArgumentParser:
@@ -55,4 +55,8 @@ class OutputConfig:
subtitle_offset_ms: int = 0
# Countdown feature for songs that start too quickly
add_countdown: bool = True
add_countdown: bool = True
# Whether to allow preview video generation during review
# Separate from render_video which controls final output
allow_preview_video: bool = True
@@ -3,20 +3,20 @@ import logging
import json
from dataclasses import dataclass, field
from typing import Dict, Optional, List
from lyrics_transcriber.types import LyricsData, TranscriptionResult, CorrectionResult
from lyrics_transcriber.transcribers.base_transcriber import BaseTranscriber
from lyrics_transcriber.transcribers.audioshake import AudioShakeTranscriber, AudioShakeConfig
from lyrics_transcriber.transcribers.whisper import WhisperTranscriber, WhisperConfig
from lyrics_transcriber.transcribers.local_whisper import LocalWhisperTranscriber, LocalWhisperConfig
from lyrics_transcriber.lyrics.base_lyrics_provider import BaseLyricsProvider, LyricsProviderConfig
from lyrics_transcriber.lyrics.genius import GeniusProvider
from lyrics_transcriber.lyrics.spotify import SpotifyProvider
from lyrics_transcriber.lyrics.musixmatch import MusixmatchProvider
from lyrics_transcriber.lyrics.lrclib import LRCLIBProvider
from lyrics_transcriber.output.generator import OutputGenerator
from lyrics_transcriber.correction.corrector import LyricsCorrector
from lyrics_transcriber.core.config import TranscriberConfig, LyricsConfig, OutputConfig
from lyrics_transcriber.lyrics.file_provider import FileProvider
from karaoke_gen.lyrics_transcriber.types import LyricsData, TranscriptionResult, CorrectionResult
from karaoke_gen.lyrics_transcriber.transcribers.base_transcriber import BaseTranscriber
from karaoke_gen.lyrics_transcriber.transcribers.audioshake import AudioShakeTranscriber, AudioShakeConfig
from karaoke_gen.lyrics_transcriber.transcribers.whisper import WhisperTranscriber, WhisperConfig
from karaoke_gen.lyrics_transcriber.transcribers.local_whisper import LocalWhisperTranscriber, LocalWhisperConfig
from karaoke_gen.lyrics_transcriber.lyrics.base_lyrics_provider import BaseLyricsProvider, LyricsProviderConfig
from karaoke_gen.lyrics_transcriber.lyrics.genius import GeniusProvider
from karaoke_gen.lyrics_transcriber.lyrics.spotify import SpotifyProvider
from karaoke_gen.lyrics_transcriber.lyrics.musixmatch import MusixmatchProvider
from karaoke_gen.lyrics_transcriber.lyrics.lrclib import LRCLIBProvider
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
from karaoke_gen.lyrics_transcriber.correction.corrector import LyricsCorrector
from karaoke_gen.lyrics_transcriber.core.config import TranscriberConfig, LyricsConfig, OutputConfig
from karaoke_gen.lyrics_transcriber.lyrics.file_provider import FileProvider
@dataclass
@@ -301,7 +301,7 @@ class LyricsTranscriber:
# Debug: Log package version and environment variables
try:
import lyrics_transcriber
from karaoke_gen import lyrics_transcriber
package_version = getattr(lyrics_transcriber, '__version__', 'unknown')
self.logger.info(f"LyricsTranscriber package version: {package_version}")
except Exception as e:
@@ -345,7 +345,7 @@ class LyricsTranscriber:
# This is important because the video needs to use padded audio to sync
# with the countdown-adjusted timestamps in the ASS subtitles
if self.output_config.add_countdown:
from lyrics_transcriber.output.countdown_processor import CountdownProcessor
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
countdown_processor = CountdownProcessor(
cache_dir=self.output_config.cache_dir,
@@ -572,7 +572,7 @@ class LyricsTranscriber:
# Add human review step (moved outside the else block)
if self.output_config.enable_review:
from lyrics_transcriber.review.server import ReviewServer
from karaoke_gen.lyrics_transcriber.review.server import ReviewServer
self.logger.info("Starting human review process")
@@ -590,7 +590,7 @@ class LyricsTranscriber:
# Add countdown intro if enabled and needed (after review, before output generation)
if self.output_config.add_countdown and self.results.transcription_corrected:
from lyrics_transcriber.output.countdown_processor import CountdownProcessor
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
self.logger.info("Processing countdown intro (if needed)")
countdown_processor = CountdownProcessor(
@@ -3,8 +3,8 @@ from __future__ import annotations
from typing import Dict, Any, List
from .models.schemas import CorrectionProposal
from lyrics_transcriber.types import WordCorrection, Word
from lyrics_transcriber.utils.word_utils import WordUtils
from karaoke_gen.lyrics_transcriber.types import WordCorrection, Word
from karaoke_gen.lyrics_transcriber.utils.word_utils import WordUtils
def adapt_proposals_to_word_corrections(
@@ -13,7 +13,7 @@ from .models.schemas import CorrectionProposal, GapClassification, GapCategory
from .workflows.correction_graph import build_correction_graph
from .prompts.classifier import build_classification_prompt
from .handlers.registry import HandlerRegistry
from lyrics_transcriber.utils.tracing import create_span, add_span_attribute
from karaoke_gen.lyrics_transcriber.utils.tracing import create_span, add_span_attribute
logger = logging.getLogger(__name__)
@@ -9,12 +9,12 @@ import json
import hashlib
# Tracing utilities (optional - gracefully handles missing dependency)
from lyrics_transcriber.utils.tracing import create_span, add_span_attribute, add_span_event
from karaoke_gen.lyrics_transcriber.utils.tracing import create_span, add_span_attribute, add_span_event
from lyrics_transcriber.types import LyricsData, PhraseScore, PhraseType, AnchorSequence, GapSequence, ScoredAnchor, TranscriptionResult, Word
from lyrics_transcriber.correction.phrase_analyzer import PhraseAnalyzer
from lyrics_transcriber.correction.text_utils import clean_text
from lyrics_transcriber.utils.word_utils import WordUtils
from karaoke_gen.lyrics_transcriber.types import LyricsData, PhraseScore, PhraseType, AnchorSequence, GapSequence, ScoredAnchor, TranscriptionResult, Word
from karaoke_gen.lyrics_transcriber.correction.phrase_analyzer import PhraseAnalyzer
from karaoke_gen.lyrics_transcriber.correction.text_utils import clean_text
from karaoke_gen.lyrics_transcriber.utils.word_utils import WordUtils
class AnchorSequenceTimeoutError(Exception):
@@ -724,8 +724,8 @@ class AnchorSequenceFinder:
# This can happen in tests using backwards compatible constructors
# Create dummy Word objects with the text from _words if available
if hasattr(anchor, '_words') and anchor._words is not None:
from lyrics_transcriber.types import Word
from lyrics_transcriber.utils.word_utils import WordUtils
from karaoke_gen.lyrics_transcriber.types import Word
from karaoke_gen.lyrics_transcriber.utils.word_utils import WordUtils
anchor.transcribed_words = [
Word(
id=word_id,
@@ -738,7 +738,7 @@ class AnchorSequenceFinder:
]
else:
# Create generic word objects for scoring
from lyrics_transcriber.types import Word
from karaoke_gen.lyrics_transcriber.types import Word
anchor.transcribed_words = [
Word(
id=word_id,
@@ -6,14 +6,14 @@ import os
import shortuuid
import time
from lyrics_transcriber.correction.handlers.levenshtein import LevenshteinHandler
from lyrics_transcriber.correction.handlers.no_space_punct_match import NoSpacePunctuationMatchHandler
from lyrics_transcriber.correction.handlers.relaxed_word_count_match import RelaxedWordCountMatchHandler
from lyrics_transcriber.correction.handlers.repeat import RepeatCorrectionHandler
from lyrics_transcriber.correction.handlers.sound_alike import SoundAlikeHandler
from lyrics_transcriber.correction.handlers.syllables_match import SyllablesMatchHandler
from lyrics_transcriber.correction.handlers.word_count_match import WordCountMatchHandler
from lyrics_transcriber.types import (
from karaoke_gen.lyrics_transcriber.correction.handlers.levenshtein import LevenshteinHandler
from karaoke_gen.lyrics_transcriber.correction.handlers.no_space_punct_match import NoSpacePunctuationMatchHandler
from karaoke_gen.lyrics_transcriber.correction.handlers.relaxed_word_count_match import RelaxedWordCountMatchHandler
from karaoke_gen.lyrics_transcriber.correction.handlers.repeat import RepeatCorrectionHandler
from karaoke_gen.lyrics_transcriber.correction.handlers.sound_alike import SoundAlikeHandler
from karaoke_gen.lyrics_transcriber.correction.handlers.syllables_match import SyllablesMatchHandler
from karaoke_gen.lyrics_transcriber.correction.handlers.word_count_match import WordCountMatchHandler
from karaoke_gen.lyrics_transcriber.types import (
CorrectionStep,
GapSequence,
LyricsData,
@@ -23,11 +23,11 @@ from lyrics_transcriber.types import (
WordCorrection,
Word,
)
from lyrics_transcriber.correction.anchor_sequence import AnchorSequenceFinder
from lyrics_transcriber.correction.handlers.base import GapCorrectionHandler
from lyrics_transcriber.correction.handlers.extend_anchor import ExtendAnchorHandler
from lyrics_transcriber.utils.word_utils import WordUtils
from lyrics_transcriber.utils.tracing import create_span, add_span_attribute, add_span_event
from karaoke_gen.lyrics_transcriber.correction.anchor_sequence import AnchorSequenceFinder
from karaoke_gen.lyrics_transcriber.correction.handlers.base import GapCorrectionHandler
from karaoke_gen.lyrics_transcriber.correction.handlers.extend_anchor import ExtendAnchorHandler
from karaoke_gen.lyrics_transcriber.utils.word_utils import WordUtils
from karaoke_gen.lyrics_transcriber.utils.tracing import create_span, add_span_attribute, add_span_event
class LyricsCorrector:
@@ -299,9 +299,9 @@ class LyricsCorrector:
if use_agentic_env:
try:
from lyrics_transcriber.correction.agentic.agent import AgenticCorrector as _AgenticCorrector
from lyrics_transcriber.correction.agentic.adapter import adapt_proposals_to_word_corrections as _adapt
from lyrics_transcriber.correction.agentic.router import ModelRouter as _ModelRouter
from karaoke_gen.lyrics_transcriber.correction.agentic.agent import AgenticCorrector as _AgenticCorrector
from karaoke_gen.lyrics_transcriber.correction.agentic.adapter import adapt_proposals_to_word_corrections as _adapt
from karaoke_gen.lyrics_transcriber.correction.agentic.router import ModelRouter as _ModelRouter
self.logger.info("🤖 Agentic modules imported successfully - running in AGENTIC-ONLY mode")
# Create agent ONCE and reuse for all gaps (avoids repeated model initialization)
@@ -486,7 +486,7 @@ class LyricsCorrector:
# AGENTIC-ONLY MODE: Process all gaps in parallel for better performance
if use_agentic_env:
from concurrent.futures import ThreadPoolExecutor, as_completed
from lyrics_transcriber.correction.agentic.providers.config import ProviderConfig
from karaoke_gen.lyrics_transcriber.correction.agentic.providers.config import ProviderConfig
# Get parallel processing config
_config = ProviderConfig.from_env()
Loaded 100 of 204 files, more files were not shown because too many files have changed in this diff. Show more