Compare commits

...
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude c3eb794d7d fix: prevent Cloud Run from killing workers during parallel processing (#315)
## Summary
- Fix bug where Cloud Run could shut down prematurely when one parallel
worker completed while another was still running
- Add WorkerRegistry to track active workers per job
- Add shutdown handler that waits for workers to complete before
allowing container termination

## Background
Job `9ed3b0a1` failed because Cloud Run shut down at 05:31:06
immediately after the audio worker completed, while the lyrics
correction worker was still processing. Workers run in BackgroundTasks,
and when one completes, Cloud Run sees no active requests and can
terminate the container.

## Changes
- **New `backend/workers/registry.py`**: WorkerRegistry class that
tracks active workers
- **Updated `backend/workers/audio_worker.py`**: Register/unregister
with registry
- **Updated `backend/workers/lyrics_worker.py`**: Register/unregister
with registry
- **Updated `backend/main.py`**: Shutdown handler waits for workers (10
min timeout)
- **New tests**: 11 unit tests for WorkerRegistry
- **Docs**: Updated ARCHITECTURE.md, LESSONS-LEARNED.md, README.md

## Test plan
- [x] Unit tests pass (11 new tests for WorkerRegistry)
- [x] All 220 worker-related tests pass
- [x] All 7 main.py tests pass
- [ ] E2E happy path test after deployment

@coderabbitai ignore

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-01-19 22:35:41 -08:00
Andrew Beveridge ☄️andClaude Opus 4.5 a5fb5114f2 Add E2E test selectors for instrumental selection (#314)
## Summary
- Add `.selection-option` class and `data-testid` to SelectionOptions
buttons for E2E test compatibility
- Add `id="submit-btn"` to InstrumentalSelector submit button
- Fix missing `completeReview` method in LyricsAnalyzer ApiClient
interface (TypeScript fix)

## Test plan
- [x] Backend tests pass (1593 passed)
- [x] TypeScript compiles without errors
- [x] E2E happy path test passes (production config)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-20 05:25:16 +00:00
Andrew Beveridge ☄️andClaude f18a7f32e3 Fix lyrics review "Complete Review" button (405 error) (#313)
## Summary
- Fix HTTP method mismatch: `submitCorrections` was using PUT but
backend expects POST, causing 405 errors
- Add missing `completeReview()` call to trigger video rendering after
saving corrections

## Changes
- `api.ts`: Change `submitCorrections` method from PUT to POST
- `api.ts`: Add `completeReview` to `LyricsReviewApiClient` interface
and implementation
- `LyricsAnalyzer.tsx`: Call `apiClient.completeReview()` after saving
corrections

## Test plan
- [x] Frontend build passes (TypeScript types verified)
- [x] API tests pass (25 tests including completeReview)
- [x] Backend tests pass (1593 passed)
- [x] Manually verified endpoints work via curl:
  - `POST /api/jobs/{id}/corrections` → 422 (not 405)
  - `POST /api/jobs/{id}/complete-review` → 200 success

@coderabbitai ignore

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-01-19 18:37:47 -08:00
Andrew Beveridge ☄️andClaude Opus 4.5 b16bdb024b Fix: hash-based navigation from job list (#312)
## Summary
- Fix bug where clicking "Review Lyrics" or "Select Instrumental" from
the job list showed "Page not found" but reloading worked
- Changed from Next.js `Link` to regular `<a>` tags for hash-based URLs

## Root Cause
Next.js `Link` uses `history.pushState` for client-side navigation,
which doesn't trigger the `hashchange` event. The client.tsx component's
hash state wasn't updating when navigating.

## Solution
Use regular `<a>` tags for hash URLs (`/app/jobs#/{jobId}/review`). When
clicking an `<a>` tag with a hash URL on the same page, the browser:
1. Updates the hash without reloading
2. Fires the `hashchange` event
3. Our listener updates state
4. Component re-renders with correct route

## Test plan
- [x] Unit tests pass
- [ ] Manual test: Click "Review Lyrics" from job list - should navigate
correctly

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

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-20 01:14:45 +00: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
216 changed files with 1882 additions and 398 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
+18 -2
View File
@@ -15,6 +15,7 @@ from backend.services.nltk_preloader import preload_all_nltk_resources
from backend.services.langfuse_preloader import preload_langfuse_handler
from backend.middleware.audit_logging import AuditLoggingMiddleware
from backend.middleware.tenant import TenantMiddleware
from backend.workers.registry import worker_registry
from backend.version import VERSION
@@ -100,8 +101,23 @@ async def lifespan(app: FastAPI):
logger.error(f"Credential validation failed: {e}")
yield
# Shutdown
# Shutdown - wait for any active workers to complete before terminating
# This prevents Cloud Run from killing workers mid-processing
logger.info("Shutdown requested, checking for active workers...")
if worker_registry.has_active_workers():
active = worker_registry.get_active_workers()
logger.info(f"Active workers found: {active}")
logger.info("Waiting for workers to complete (timeout: 600s)...")
completed = await worker_registry.wait_for_completion(timeout=600) # 10 min max
if not completed:
logger.error(
"Shutdown timeout - some workers may not have completed cleanly. "
f"Remaining workers: {worker_registry.get_active_workers()}"
)
else:
logger.info("No active workers, proceeding with shutdown")
logger.info("Shutting down karaoke generation backend")
+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')
+131
View File
@@ -0,0 +1,131 @@
"""Tests for the worker registry module."""
import asyncio
import pytest
from backend.workers.registry import WorkerRegistry
@pytest.fixture
def registry():
"""Create a fresh WorkerRegistry for each test."""
return WorkerRegistry()
class TestWorkerRegistry:
"""Test cases for WorkerRegistry."""
@pytest.mark.asyncio
async def test_register_adds_worker(self, registry):
"""Register should add worker to active workers."""
await registry.register("job-123", "audio")
assert registry.has_active_workers()
active = registry.get_active_workers()
assert "job-123" in active
assert "audio" in active["job-123"]
@pytest.mark.asyncio
async def test_unregister_removes_worker(self, registry):
"""Unregister should remove worker from active workers."""
await registry.register("job-123", "audio")
await registry.unregister("job-123", "audio")
assert not registry.has_active_workers()
assert "job-123" not in registry.get_active_workers()
@pytest.mark.asyncio
async def test_multiple_workers_same_job(self, registry):
"""Multiple workers can be registered for the same job."""
await registry.register("job-123", "audio")
await registry.register("job-123", "lyrics")
active = registry.get_active_workers()
assert "job-123" in active
assert active["job-123"] == {"audio", "lyrics"}
@pytest.mark.asyncio
async def test_partial_unregister_keeps_other_workers(self, registry):
"""Unregistering one worker should keep others active."""
await registry.register("job-123", "audio")
await registry.register("job-123", "lyrics")
await registry.unregister("job-123", "audio")
assert registry.has_active_workers()
active = registry.get_active_workers()
assert "job-123" in active
assert active["job-123"] == {"lyrics"}
@pytest.mark.asyncio
async def test_multiple_jobs(self, registry):
"""Workers from different jobs are tracked separately."""
await registry.register("job-123", "audio")
await registry.register("job-456", "lyrics")
active = registry.get_active_workers()
assert "job-123" in active
assert "job-456" in active
@pytest.mark.asyncio
async def test_unregister_nonexistent_worker(self, registry):
"""Unregistering a worker that doesn't exist should not error."""
await registry.unregister("nonexistent-job", "audio")
assert not registry.has_active_workers()
@pytest.mark.asyncio
async def test_wait_for_completion_no_workers(self, registry):
"""Wait should return immediately when no workers are active."""
result = await registry.wait_for_completion(timeout=1.0)
assert result is True
@pytest.mark.asyncio
async def test_wait_for_completion_workers_finish(self, registry):
"""Wait should complete when workers finish."""
await registry.register("job-123", "audio")
# Create a task that unregisters after a delay
async def unregister_after_delay():
await asyncio.sleep(0.2)
await registry.unregister("job-123", "audio")
asyncio.create_task(unregister_after_delay())
result = await registry.wait_for_completion(timeout=5.0)
assert result is True
@pytest.mark.asyncio
async def test_wait_for_completion_timeout(self, registry):
"""Wait should return False on timeout."""
await registry.register("job-123", "audio")
# Short timeout, worker never unregisters
result = await registry.wait_for_completion(timeout=0.1)
assert result is False
@pytest.mark.asyncio
async def test_concurrent_registration(self, registry):
"""Concurrent registrations should be thread-safe."""
job_ids = [f"job-{i}" for i in range(10)]
async def register_worker(job_id):
await registry.register(job_id, "audio")
# Register all workers concurrently
await asyncio.gather(*[register_worker(job_id) for job_id in job_ids])
active = registry.get_active_workers()
assert len(active) == 10
for job_id in job_ids:
assert job_id in active
@pytest.mark.asyncio
async def test_get_active_workers_returns_copy(self, registry):
"""get_active_workers should return a copy, not the internal state."""
await registry.register("job-123", "audio")
active = registry.get_active_workers()
active["job-123"].add("fake-worker")
# Internal state should not be affected
internal = registry.get_active_workers()
assert "fake-worker" not in internal.get("job-123", set())
+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')
+10 -2
View File
@@ -26,6 +26,7 @@ from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.config import get_settings
from backend.workers.worker_logging import create_job_logger, setup_job_logging, job_logging_context
from backend.workers.registry import worker_registry
from backend.services.tracing import job_span, add_span_event, add_span_attribute
from backend.services.metrics import metrics
@@ -264,7 +265,11 @@ async def process_audio_separation(job_id: str) -> bool:
logger.info(f"[job:{job_id}] WORKER_START worker=audio")
job_log.info("=== AUDIO WORKER STARTED ===")
job_log.info(f"Job ID: {job_id}")
# Register with worker registry to prevent premature container shutdown
# This ensures Cloud Run waits for this worker to complete before terminating
await worker_registry.register(job_id, "audio")
# Set up log capture for AudioProcessor
log_handler = setup_job_logging(job_id, "audio", *AUDIO_WORKER_LOGGERS)
job_log.info(f"Log handler attached for {len(AUDIO_WORKER_LOGGERS)} loggers")
@@ -411,13 +416,16 @@ async def process_audio_separation(job_id: str) -> bool:
return False
finally:
# Unregister from worker registry to signal completion
await worker_registry.unregister(job_id, "audio")
# Remove log handler to avoid duplicate logging on future runs
for logger_name in AUDIO_WORKER_LOGGERS:
try:
logging.getLogger(logger_name).removeHandler(log_handler)
except Exception:
pass
# Cleanup temporary directory
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
+10 -2
View File
@@ -35,6 +35,7 @@ from backend.services.storage_service import StorageService
from backend.services.lyrics_cache_service import LyricsCacheService
from backend.workers.worker_logging import create_job_logger, setup_job_logging, job_logging_context
from backend.workers.style_helper import load_style_config
from backend.workers.registry import worker_registry
from backend.services.tracing import job_span, add_span_event, add_span_attribute
from backend.services.metrics import metrics
@@ -164,7 +165,11 @@ async def process_lyrics_transcription(job_id: str) -> bool:
logger.info(f"[job:{job_id}] WORKER_START worker=lyrics")
job_log.info("=== LYRICS WORKER STARTED ===")
job_log.info(f"Job ID: {job_id}")
# Register with worker registry to prevent premature container shutdown
# This ensures Cloud Run waits for this worker to complete before terminating
await worker_registry.register(job_id, "lyrics")
# Set up log capture for LyricsTranscriber and its dependencies
# This ensures logs from the lyrics_transcriber library are also captured
log_handler = setup_job_logging(job_id, "lyrics", *LYRICS_WORKER_LOGGERS)
@@ -460,13 +465,16 @@ async def process_lyrics_transcription(job_id: str) -> bool:
return False
finally:
# Unregister from worker registry to signal completion
await worker_registry.unregister(job_id, "lyrics")
# Remove log handler to avoid duplicate logging on future runs
for logger_name in LYRICS_WORKER_LOGGERS:
try:
logging.getLogger(logger_name).removeHandler(log_handler)
except Exception:
pass
# Cleanup temporary directory (only if it was created)
if temp_dir and os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
+132
View File
@@ -0,0 +1,132 @@
"""
Worker registry for tracking active background workers.
This module provides coordination to prevent Cloud Run from shutting down
while workers are still processing. Without this, when one worker completes
and returns (ending the HTTP request), Cloud Run has no reason to keep the
container alive, even if other workers are still running.
Key insight: Workers run in BackgroundTasks, which are tied to the HTTP
request lifecycle. When the request completes, Cloud Run can terminate
the container, even if BackgroundTasks are still running.
This registry:
1. Tracks which workers are active for each job
2. Provides a shutdown hook that waits for workers to complete
3. Has timeout protection to prevent infinite hangs
"""
import asyncio
import logging
import time
from collections import defaultdict
from typing import Dict, Set
logger = logging.getLogger(__name__)
class WorkerRegistry:
"""Track active workers to prevent premature container shutdown."""
def __init__(self):
self._active_workers: Dict[str, Set[str]] = defaultdict(set) # job_id -> {worker_types}
self._lock = asyncio.Lock()
async def register(self, job_id: str, worker_type: str) -> None:
"""Register a worker as active.
Args:
job_id: The job ID this worker is processing
worker_type: Type of worker (e.g., 'audio', 'lyrics')
"""
async with self._lock:
self._active_workers[job_id].add(worker_type)
logger.info(
f"[job:{job_id}] Worker registered: {worker_type}, "
f"active workers for job: {self._active_workers[job_id]}"
)
async def unregister(self, job_id: str, worker_type: str) -> None:
"""Unregister a worker when complete.
Args:
job_id: The job ID this worker was processing
worker_type: Type of worker (e.g., 'audio', 'lyrics')
"""
async with self._lock:
self._active_workers[job_id].discard(worker_type)
remaining = self._active_workers.get(job_id, set())
if not remaining:
# Clean up empty entries
self._active_workers.pop(job_id, None)
logger.info(
f"[job:{job_id}] Worker unregistered: {worker_type}, "
f"no workers remaining for job"
)
else:
logger.info(
f"[job:{job_id}] Worker unregistered: {worker_type}, "
f"remaining workers: {remaining}"
)
def has_active_workers(self) -> bool:
"""Check if any workers are still active.
Returns:
True if any workers are registered as active
"""
return len(self._active_workers) > 0
def get_active_workers(self) -> Dict[str, Set[str]]:
"""Get a snapshot of all active workers.
Returns:
Dict mapping job_id to set of active worker types (deep copy)
"""
# Return a deep copy to prevent external modification of internal state
return {job_id: set(workers) for job_id, workers in self._active_workers.items()}
async def wait_for_completion(self, timeout: float = 600) -> bool:
"""Wait for all workers to complete, with timeout.
This is called during shutdown to ensure workers finish before
the container terminates.
Args:
timeout: Maximum seconds to wait (default 10 minutes)
Returns:
True if all workers completed, False if timeout was reached
"""
start = time.time()
poll_interval = 1.0 # Check every second
last_log_time = 0
while self.has_active_workers():
elapsed = time.time() - start
if elapsed > timeout:
active = self.get_active_workers()
logger.warning(
f"Worker completion timeout after {timeout}s, "
f"active workers: {active}"
)
return False
# Log progress every 10 seconds
elapsed_int = int(elapsed)
if elapsed_int >= last_log_time + 10:
last_log_time = elapsed_int
active = self.get_active_workers()
logger.info(
f"Waiting for workers to complete... "
f"elapsed={elapsed:.0f}s, active={active}"
)
await asyncio.sleep(poll_interval)
elapsed = time.time() - start
logger.info(f"All workers completed (waited {elapsed:.1f}s)")
return True
# Global registry instance - imported by workers and main.py
worker_registry = WorkerRegistry()
+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
+31 -1
View File
@@ -45,11 +45,13 @@
• Create job in Firestore
• Trigger parallel workers
2. PARALLEL PROCESSING
2. PARALLEL PROCESSING (with Worker Registry coordination)
┌─────────────────┐ ┌─────────────────┐
│ Audio Worker │ │ Lyrics Worker │
│ Modal API │ │ AudioShake │
│ 2-stage sep │ │ Auto-correct │
│ ↓ register() │ │ ↓ register() │
│ ↓ unregister() │ │ ↓ unregister() │
└────────┬────────┘ └────────┬────────┘
└──────────┬───────────┘
▼
@@ -217,6 +219,34 @@ The Video Worker uses an orchestrator pattern to ensure all features work regard
| `template_service.py` | GCS-backed email templates |
| `job_notification_service.py` | Email orchestration (completion, reminders) |
## Worker Coordination
Workers run in parallel via FastAPI BackgroundTasks. To prevent Cloud Run from terminating the container when one worker completes while another is still running, workers register with a global `WorkerRegistry`.
```text
┌─────────────────────────────────────────────────────────────────┐
│ WorkerRegistry │
│ │
│ register(job_id, "audio") unregister(job_id, "audio") │
│ register(job_id, "lyrics") unregister(job_id, "lyrics") │
│ │
│ has_active_workers() → bool │
│ wait_for_completion(timeout) → bool │
└─────────────────────────────────────────────────────────────────┘
```
**Flow**:
1. Worker starts → `await worker_registry.register(job_id, "audio")`
2. Worker does work in try block
3. Worker completes → `await worker_registry.unregister(job_id, "audio")` in finally block
**Shutdown Handler** (in `main.py` lifespan):
- On shutdown signal, checks `worker_registry.has_active_workers()`
- If workers active, calls `wait_for_completion(timeout=600)` (10 min max)
- Logs which workers are still running for debugging
**Why needed**: Without this, when the audio worker's BackgroundTask completes, Cloud Run sees the container as idle (no active requests) and may terminate it, killing the still-running lyrics worker.
## Multitenancy
The platform supports white-label B2B portals where business customers get their own branded karaoke generation experience.
+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 ...
+3
View File
@@ -81,6 +81,9 @@ Base Docker images have no fonts. Install `fonts-noto-core`, `fonts-noto-cjk` fo
### Cloud Run CPU Throttling Kills Background Tasks
Cloud Run throttles CPU to near-zero when the main request handler returns, even if background tasks are running. This caused lyrics processing (running as a FastAPI background task) to slow from 17-52 seconds to 8+ minutes, and instances being terminated mid-processing. **Fix**: Add `--no-cpu-throttling` flag to `gcloud run deploy`. Keep `--cpu-boost` for faster cold starts. **Diagnosis**: Look for "Application shutdown" in logs during long operations, and compare processing times (27x slowdown is a telltale sign).
### Cloud Run Premature Shutdown with Parallel Workers
When multiple workers run in parallel via BackgroundTasks, Cloud Run can shut down when one worker completes, killing others mid-processing. This happens because each worker endpoint returns quickly after spawning its BackgroundTask - when the audio worker's task completes, Cloud Run sees the container as idle. **Fix**: Implement a `WorkerRegistry` that tracks active workers per job. Register at worker start, unregister in finally block. Add shutdown handler in FastAPI lifespan that calls `worker_registry.wait_for_completion(timeout=600)` before allowing shutdown. **Pattern**: `backend/workers/registry.py` provides the global registry; workers import and call `await worker_registry.register(job_id, "audio")` / `unregister()`.
### Add Progress Logging for Long Operations
Operations over ~30 seconds should log progress periodically (time-based, not count-based). Count-based logging like "log every 20 items" can miss entirely if items complete slowly. Time-based logging (every 30s) ensures visibility regardless of processing speed.
+2
View File
@@ -42,6 +42,8 @@
## Recent Changes
- **Worker Coordination Fix** (2026-01-20): Fixed bug where Cloud Run could shut down prematurely when one parallel worker completed while another was still running. Added `WorkerRegistry` to track active workers per job. Workers register at start and unregister in finally block. FastAPI lifespan shutdown handler now waits up to 10 minutes for active workers to complete before allowing container termination. Fixes job failures where lyrics worker was killed mid-processing after audio worker completed. See [ARCHITECTURE.md](ARCHITECTURE.md#worker-coordination) and [LESSONS-LEARNED.md](LESSONS-LEARNED.md#cloud-run-premature-shutdown-with-parallel-workers).
- **Admin Delete Outputs** (2026-01-10): Added admin button to delete all distributed outputs (YouTube, Dropbox, Google Drive) for a job while preserving the job record. Use case: fix quality issues by deleting outputs, resetting to `awaiting_review`, correcting lyrics, and re-generating. The brand code is freed for reuse when Dropbox folder is deleted. New endpoint: `POST /api/admin/jobs/{job_id}/delete-outputs`. UI: Delete Outputs button in admin job detail page, "Outputs Deleted" badge when flag is set. See [API.md](API.md#delete-job-outputs).
- **Rate Limiting & Abuse Prevention** (2026-01-09): Added per-user rate limiting (5 jobs/day default), system-wide YouTube upload limits (10/day), and beta enrollment abuse prevention. Features: email normalization (Gmail alias detection), disposable domain blocklist (130+ domains), blocked email/IP lists, IP-based enrollment rate limiting (1 per 24h), and admin UI for managing blocklists and user overrides at `/admin/rate-limits`. Admins can grant users bypass permissions or custom limits. All limits configurable via environment variables. See [API.md](API.md#rate-limits).
+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}
@@ -645,6 +645,7 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
backingVocalAnalysis={analysisData?.analysis}
/>
<Button
id="submit-btn"
onClick={handleSubmit}
disabled={isSubmitting}
className="mt-auto w-full"
@@ -77,9 +77,10 @@ export function SelectionOptions({
<button
key={option.value}
type="button"
data-testid={`selection-option-${option.value}`}
onClick={() => onChange(option.value)}
className={cn(
"flex items-center gap-3 p-3 rounded-lg transition-all text-left",
"selection-option flex items-center gap-3 p-3 rounded-lg transition-all text-left",
"bg-secondary hover:bg-secondary/80",
"border-2 border-transparent",
value === option.value && "border-primary bg-primary/10"
+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>
)
}
@@ -68,6 +68,7 @@ interface ApiClient {
preview_hash?: string
}>
getPreviewVideoUrl: (hash: string) => string
completeReview: () => Promise<{ status: string; job_status: string; message: string }>
}
export interface LyricsAnalyzerProps {
@@ -588,6 +589,9 @@ export default function LyricsAnalyzer({
}
}
// Complete review and trigger video rendering
await apiClient.completeReview()
setIsReviewComplete(true)
setIsReviewModalOpen(false)
window.close()
+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
@@ -692,6 +692,8 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
const statusText = await jobCard.textContent() || '';
console.log(` Status: ${statusText.substring(0, 80)}...`);
// Look for instrumental selection UI availability
// Users ALWAYS have to go through the instrumental review UI - there's no skip
if (statusText.toLowerCase().includes('select instrumental') ||
statusText.toLowerCase().includes('awaiting_instrumental') ||
(statusText.toLowerCase().includes('action needed') && statusText.toLowerCase().includes('instrumental'))) {
@@ -700,21 +702,6 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
break;
}
// Check if already complete (auto-mode might have run)
if (statusText.toLowerCase().includes('complete') && !statusText.toLowerCase().includes('prep')) {
console.log(' Job already complete - skipping instrumental selection');
break;
}
// Check if encoding is in progress (past instrumental stage)
// NOTE: "rendering" status is BEFORE instrumental selection, not after!
// The flow is: rendering_video -> awaiting_instrumental_selection -> encoding -> complete
// So only skip if job is at encoding (not rendering)
if (statusText.toLowerCase().includes('encoding') && !statusText.toLowerCase().includes('awaiting')) {
console.log(' Job is encoding - instrumental selection was handled');
break;
}
if (statusText.toLowerCase().includes('failed')) {
throw new Error('Job failed during video rendering');
}
@@ -722,7 +709,11 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
await page.waitForTimeout(10000);
}
if (foundInstrumentalStatus) {
if (!foundInstrumentalStatus) {
throw new Error('Timeout waiting for instrumental selection - users must always complete this step');
}
{
// Click the Select Instrumental button/link
const instrumentalLink = jobCard.getByRole('link', { name: /select instrumental/i });
await expect(instrumentalLink).toBeVisible({ timeout: TIMEOUTS.action });
@@ -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" />
+30 -7
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 {
@@ -1627,6 +1638,7 @@ export interface LyricsReviewApiClient {
preview_hash?: string
}>
getPreviewVideoUrl: (hash: string) => string
completeReview: () => Promise<{ status: string; job_status: string; message: string }>
}
/**
@@ -1639,7 +1651,7 @@ export function createLyricsReviewApiClient(jobId: string): LyricsReviewApiClien
*/
async submitCorrections(data: CorrectionData): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/corrections`, {
method: 'PUT',
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
@@ -1699,7 +1711,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 +1723,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,9 +1739,20 @@ 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
},
/**
* Complete the review and trigger video rendering
*/
async completeReview(): Promise<{ status: string; job_status: string; message: string }> {
const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/complete-review`, {
method: 'POST',
headers: getAuthHeaders()
})
return handleResponse(response)
},
}
}
@@ -1739,7 +1762,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 +1771,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__)
Loaded 100 of 216 files, more files were not shown because too many files have changed in this diff. Show more