Compare commits

...
24 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.6 6577babfea Reduce free credits from 2 to 1 per grant (#592)
## Summary

- Welcome credits: 2 → 1 (granted on first email verification)
- Feedback credits: 2 → 1 (granted for submitting product feedback)
- Total possible free credits per account: 4 → 2

## Changes

**Backend:** `NEW_USER_FREE_CREDITS` constant, feedback credit grant, AI
evaluation prompt, model defaults
**Frontend:** Landing page, dashboard banner, feedback dialog, auth
dropdown menu text
**Tests:** Updated all assertions and mock values (115 backend + 712
frontend tests pass)
**Docs:** AI-CREDIT-GATING.md, API.md, README.md,
PRODUCT-COMMUNICATION-GUIDE.md

## Test plan

- [x] Backend tests pass (115 passed)
- [x] Frontend Jest tests pass (712 passed)
- [ ] CI pipeline passes
- [ ] Verify landing page shows "1 Free Credit" after deploy
- [ ] Verify new user signup grants 1 credit (not 2)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 21:30:38 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 a7e41a09d6 Fix custom background image not applied in guided flow (#590)
@coderabbitai ignore

## Summary

- **Bug:** Custom background images uploaded during guided job creation
were silently ignored — the endpoint returned 500 due to
`AttributeError: 'StorageService' object has no attribute 'bucket_name'`
- **Fix:** `storage_service.bucket_name` → `storage_service.bucket.name`
(the correct attribute path)
- **Test fix:** Updated mock to use real attribute path
(`mock.bucket.name`) so this class of bug is caught

## Root Cause

The `complete_style_uploads` endpoint (line 2489) referenced
`storage_service.bucket_name`, but `StorageService` only exposes
`self.bucket` (a GCS Bucket object). The correct path is
`storage_service.bucket.name`.

The frontend's `uploadStyleAssets` caught the 500 error silently
(`console.error` only), so jobs continued rendering with default theme
backgrounds instead of the user's uploaded custom image.

The test passed because Mock objects auto-create attributes —
`mock.bucket_name = "test-bucket"` worked even though the real service
has no such attribute.

## Test plan

- [x] All 23 style upload tests pass
- [ ] Submit a job with custom background image and verify it renders
correctly

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 21:00:12 -04:00
Andrew Beveridge ☄️andClaude Sonnet 4.6 3e8e3474b2 Fix Pulumi state drift: env var ordering, divebar VM, model bucket (#591)
@coderabbitai ignore

## Summary
- Sort Cloud Run Job env vars alphabetically to match GCP API return
order (prevents phantom diffs on every `pulumi preview`)
- Add divebar-sync VM infrastructure code that was deployed from a
feature branch but never merged to main (prevents accidental deletion of
active infrastructure)
- Remove dead `create_model_bucket()` code and empty GCS bucket (models
baked into Docker image)

## Changes
- **`infrastructure/modules/cloud_run.py`**: Reorder env vars
alphabetically in all 4 Cloud Run Jobs (video-encoding,
audio-separation, lyrics-transcription, audio-download)
- **`infrastructure/compute/divebar_sync_vm.py`** (new): GCE VM
definition for divebar file sync (Drive → GCS)
- **`infrastructure/compute/startup_scripts/divebar_sync.sh`** (new): VM
startup script with google-auth pinning and MTLS workarounds
- **`infrastructure/__main__.py`**: Wire divebar-sync VM, Cloud
Scheduler, and IAM binding
- **`infrastructure/modules/audio_separator_service.py`**: Remove unused
`create_model_bucket()` and `storage` import

## Verification
- `pulumi preview` shows **0 changes** after applying
- `pulumi up` applied successfully (4 Cloud Run Job SDK metadata updates
+ 2 empty bucket deletes)
- Divebar-sync VM continues running undisturbed

## Test plan
- [x] `pulumi preview --diff` confirms zero drift
- [x] `pulumi up` applied cleanly (update #649)
- [x] Divebar-sync VM verified RUNNING in GCP
- [x] No application code changes — infra-only

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-24 20:53:58 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 4f8d2d71ed Fix pip resolution-too-deep in Docker base image build (#589)
## Summary
- Pin all 10 google-cloud-* and google-auth-* packages to exact latest
versions instead of loose lower bounds (e.g., `>=2.14.0` → `2.26.0`)
- Eliminates pip's massive backtracking that caused
`resolution-too-deep` errors during Docker base image builds
- Version bump: 0.150.2 → 0.150.3

## Context
The Docker base image build (`pip install -e .`) was failing because pip
had to search through hundreds of version combinations for
google-cloud-run, google-cloud-monitoring, grpc-google-iam-v1, and
googleapis-common-protos. Exact pins give pip zero backtracking to do.

## Test plan
- [x] `poetry lock` resolves cleanly
- [x] Backend tests pass (297 passed)
- [ ] CI Docker base image build succeeds (the actual fix)

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 20:47:05 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 0666a827dd Fix: migrate from google-generativeai to google-genai SDK (#588)
## Summary
- Remove `google-generativeai` (old SDK) from pyproject.toml — caused
17h encoding worker outage via pip dependency resolution explosion
- Migrate `credit_evaluation_service.py` to use `google.genai.Client`
(new SDK, already available via langchain-google-genai)
- Regenerate poetry.lock

Fixes the encoding worker crash loop from PR #584. See PR #587 for the
immediate `--no-deps` workaround.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 16:00:53 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 0635f800f6 Fix audio separation failure: smart fallback, retry, scale GPU (#586)
@coderabbitai ignore

## Summary

Fixes job 491be627 which failed because the remote audio-separator API
was busy and the code fell back to local `Separator()` which crashed
with `model_file_dir=None` in Cloud Run.

- **audio_processor**: Only fall back to local processing if
`model_file_dir` is configured (preserves CLI fallback, prevents crash
in Cloud Run)
- **audio_worker**: Retry separation up to 5x with exponential backoff
(60s, 120s, 240s, 480s — handles 15+ min busy periods)
- **infrastructure**: Scale audio-separator from 1→5 max instances with
`concurrency=1` so Cloud Run routes concurrent jobs to separate GPU
instances

## Infrastructure changes (already applied via `pulumi up`)

- `audio-separator` Cloud Run service: `maxInstanceCount: 1 → 5`,
`maxInstanceRequestConcurrency: 80 → 1`
- `audio-separator-allow-unauthenticated` IAM member created

## Test plan

- [x] Backend tests pass (2549 passed)
- [x] Pulumi changes applied successfully to prod
- [ ] Verify next audio separation job succeeds

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 15:34:48 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 9142ae5e5d fix: encoding worker crash loop from pip resolution-too-deep (#587)
## Summary
- Encoding worker has been in a crash loop since Mar 24 01:58 UTC (~17
hours) because `pip install --force-reinstall` of the 0.150.0 wheel hits
pip 25.3's `resolution-too-deep` error
- Root cause: `google-generativeai >= 0.8.0` added in #584 creates an
overly complex dependency graph when combined with existing
langchain/CUDA packages
- Fix: add `--no-deps` to pip install in `startup.sh` — the venv already
has runtime deps pre-installed, only the karaoke-gen code needs updating
- **Already deployed**: fixed `startup.sh` uploaded to GCS and encoding
worker restarted successfully

## Test plan
- [x] Reproduced `resolution-too-deep` locally with pip 25.3 in clean
venv
- [x] Verified `--no-deps` install works locally (instant, module loads)
- [x] Tested `--no-deps` install directly on the encoding worker VM with
sudo
- [x] Uploaded fixed startup.sh to GCS and restarted service
- [x] Verified health check passes:
`{"status":"ok","wheel_version":"0.150.0"}`
- [x] Retried failed job `b6e4b044` — now processing

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 15:31:26 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 5ea7a57eac Fix admin sidebar transparent background on mobile and desktop (#585)
## Summary
- Add missing sidebar CSS variables to `app/globals.css` for both dark
and light themes
- Add Tailwind v4 `@theme inline` color mappings for sidebar utilities
(`bg-sidebar`, `text-sidebar-foreground`, etc.)
- The sidebar component (shadcn/ui) was using `bg-sidebar` which
resolved to transparent because the CSS variables were defined in an
unused `styles/globals.css` file but missing from the active
`app/globals.css`

## Test plan
- [x] Verified sidebar has solid opaque background on mobile (375px) —
Sheet drawer no longer shows content behind
- [x] Verified sidebar has solid background on desktop (1280px) — no
transparency on abuse page or other admin screens
- [x] Verified sidebar renders correctly at tablet width (768px)
- [x] Verified all 10 admin pages render correctly on mobile (Dashboard,
Users, Jobs, Payments, Audio Searches, Rate Limits, Edit Reviews, Audio
Edits, Feedback, Abuse Investigation)
- [x] All 712 frontend tests pass

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 15:06:23 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 42a7793681 AI-powered credit gating with Gemini evaluation (#584)
## Summary
- Replace automatic welcome/feedback credit grants with AI-powered abuse
evaluation using Gemini 3.1 Pro
- **Fail-closed**: errors/uncertainty → credits withheld, admin notified
via email with user admin link
- Clean users (no correlations) get instant grant with no AI call
latency
- Frontend verify page shows preparing account →
celebratory/denied/pending interstitial
- Comprehensive docs at `docs/AI-CREDIT-GATING.md`

## Changes
| File | What |
|------|------|
| `backend/services/credit_evaluation_service.py` | **New**: Signal
collection, Gemini prompt, response parsing, Firestore audit |
| `backend/config.py` | `CREDIT_EVAL_ENABLED`, `CREDIT_EVAL_MODEL`
config |
| `backend/services/user_service.py` | Welcome credit flow integration
(returns tuple) |
| `backend/api/routes/users.py` | Feedback credit + verify response
integration |
| `backend/services/email_service.py` | `send_credit_denied_email()`,
`send_credit_review_needed_email()` |
| `backend/models/user.py` | `credit_status` field on verify response |
| `frontend/app/auth/verify/page.tsx` | 5-state interstitial flow |
| `frontend/lib/types.ts` + `auth.ts` | Type + state updates |
| `backend/tests/test_credit_evaluation.py` | **New**: 17 tests |
| `backend/tests/test_anti_abuse.py` | Updated for new return type |
| `docs/AI-CREDIT-GATING.md` | **New**: Comprehensive documentation |
| `pyproject.toml` | `google-generativeai` dep, version bump |

## Test plan
- [x] 50 backend tests pass (17 new + 33 updated)
- [ ] Manual: test with new account signup in prod (see docs for
expected flow)
- [ ] Manual: verify admin review email received for error cases

## Rollback
Set `CREDIT_EVAL_ENABLED=false` in Cloud Run env vars → instant revert
to auto-grant.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 21:57:46 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 21d8b270ae Fix: filter bad IPs from abuse correlation clusters (#583)
## Summary
- Filter known bad IPs (169.254.169.126 GCP load balancer, "unknown",
empty) from IP correlation clusters
- Discovered in production: the load balancer IP was creating a false
22-account cluster

Follow-up to #582.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 17:05:43 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 8e33c4b6aa Rework abuse investigation with cross-account correlations (#582)
## Summary
- **Fix** broken user profile link URL (was 404, now goes to correct
detail page)
- **Add** internal/test account filtering — excludes @nomadkaraoke.com,
@beveridge.uk, @inbox.testmail.app from all abuse views
- **New** Correlations tab (now default) showing fingerprint clusters
(RED flag) and IP clusters (ORANGE flag), with user agent matching
highlighted (YELLOW signal)
- **Demote** old "Suspicious Accounts" to secondary tab

## Motivation
The existing "Suspicious Accounts" view flagged too many false positives
— legitimate users who just used their 2 free credits, internal test
accounts, etc. The real abuse signal is **cross-account correlation**:
multiple accounts sharing the same device fingerprint or signup IP.

## Changes
| File | What |
|------|------|
| `backend/utils/test_data.py` | Add internal email domain filtering |
| `backend/services/user_service.py` | New
`find_account_correlations()`, filter suspicious accounts |
| `backend/api/routes/admin.py` | New `GET
/api/admin/abuse/correlations` endpoint |
| `frontend/lib/api.ts` | New types + API client method |
| `frontend/app/admin/abuse/page.tsx` | Fix link URL, new Correlations
tab, restructure tabs |
| `backend/tests/test_anti_abuse_investigation.py` | 10 new tests |

## Test plan
- [x] 27 anti-abuse investigation tests pass (10 new)
- [x] 2749 backend tests pass
- [x] Frontend dev server starts without errors
- [ ] Manual: verify correlations tab shows real data in prod

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 16:40:07 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 c9e434037b feat: admin feedback visibility — page + email notification (#581)
<!-- @coderabbitai ignore -->

## Summary

- **Admin feedback page** at `/admin/feedback` — browse all user
feedback submissions with star ratings, text fields, search, pagination,
and aggregate stats
- **Email notification** to admin@nomadkaraoke.com whenever a user
submits new feedback (configurable via `ADMIN_NOTIFICATION_EMAIL` env
var)
- **Admin API endpoint** `GET /api/admin/feedback` with pagination,
search, test-data filtering, and average ratings

## Context

User feedback was stored in Firestore (`user_feedback` collection) but
completely invisible to the admin — the admin panel only showed a
boolean "Feedback Submitted: Yes/No" badge per user. This PR closes that
gap.

## Changes

**Backend:**
- `GET /api/admin/feedback` endpoint with pagination, search,
`exclude_test` filter, aggregate rating averages
- `send_feedback_notification()` method on `EmailService` — sends HTML
email with star ratings, all text fields, link to admin page
- Wired into `submit_user_feedback` as fire-and-forget (won't block user
response)

**Frontend:**
- New admin page with aggregate stat cards, searchable/paginated table,
visual star ratings, expandable rows for text detail
- "Feedback" sidebar nav item with MessageSquare icon
- `adminApi.listFeedback()` client method + TypeScript types

**Tests:** 14 tests covering endpoint (pagination, search, filtering,
aggregates, empty state, datetime edge cases), email (content, subject,
custom admin, failure), and caller-callee contract integration

## Test plan

- [x] `make test` — 712 tests pass (39 suites)
- [x] 14 new tests in `test_admin_feedback.py`
- [ ] Manual: verify admin page renders at `/admin/feedback` after
deploy
- [ ] Manual: submit feedback → verify email arrives at
admin@nomadkaraoke.com

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 16:18:32 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 17265a6f28 fix: runner manager idle check misses python-audio-separator jobs (#579)
## Summary

- The `check_github_for_pending_jobs` function in the runner manager
Cloud Function only checked `karaoke-gen` for active workflow runs
- When `python-audio-separator` had queued GPU integration tests, the
idle checker saw no pending jobs and stopped the GPU runners prematurely
- Now checks both `karaoke-gen` and `python-audio-separator` repos

Already deployed via `pulumi up` (infra change — deploy first, merge
second).

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 15:57:30 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 5e7ede1cfe feat: show audio-separator version in footer (#580)
## Summary

- Adds audio-separator package version to the version footer display
- Shows as `● Separator: v0.43.1` alongside existing Encoder and
Flacfetch versions
- Uses locally installed package version (`importlib.metadata`) — does
NOT call the remote Cloud Run GPU service, avoiding unnecessary
cold-starts (~$0.07 per wake)

## Test plan

- [x] All 712 tests pass (`make test`)
- [ ] After deploy: verify footer shows separator version on
gen.nomadkaraoke.com

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 19:47:34 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 7294db2f6d fix: ASS subtitle preview/render divergence — embedded newlines drop lyrics (#578)
## Summary

- **Bug:** Lyrics that rendered correctly in preview videos were missing
words in final (with_vocals/final) video output. Discovered on job
`0d4b550c` (The Ataris - All Souls Day).
- **Root cause:** Word objects from the transcription pipeline contain
embedded newline characters (e.g., `"spell\n"`) at segment boundaries.
These corrupt ASS subtitle dialogue events by splitting them across file
lines, causing the video renderer to silently drop words after the
newline.
- **Why preview worked but final didn't:** Two divergent
CorrectionResult construction paths — preview used
`update_correction_result_with_data()` which `.strip()`s word text,
while the render worker used manual dict merge + `Word.from_dict()`
which did not strip.

## Changes

- **`Word.__post_init__`** strips whitespace/newlines from text — single
source of truth for Word invariants
- **Defensive strip in `_create_ass_text()`** — belt-and-suspenders
safety net at the ASS output boundary
- **Render worker refactored** to use the same
`CorrectionOperations.update_correction_result_with_data()` method as
preview generation (DRY, eliminates divergence)
- **Removed redundant `.strip()`** from
`update_correction_result_with_data()` Word text (now handled by
`__post_init__`)
- **Documented lesson** in `docs/LESSONS-LEARNED.md`: "Data Types Must
Enforce Their Own Invariants"
- **8 unit tests** covering Word stripping and ASS output sanitization

## Testing

- [x] 1126 unit tests pass, 0 failures
- [x] Sanity check with real bug data from job `0d4b550c` confirms fix
- [x] CodeRabbit CLI review completed, feedback addressed

## Review

- [x] Local CodeRabbit review completed
- [x] Review feedback addressed (test improved to bypass `__post_init__`
and exercise defensive strip independently)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 23:20:12 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 83c75a9d98 Cutover: audio separation Modal → Cloud Run GPU (#577)
@coderabbitai ignore

## Summary
- Switch `AUDIO_SEPARATOR_API_URL` from Modal to Cloud Run GPU service
- Bump `audio-separator` dependency to >=0.43.0 (preset + CLI support)

The Cloud Run GPU service has been tested and verified:
- Health check: healthy, models ready
- Both ensemble presets (instrumental_clean, karaoke) verified
- Full 2-stage separation tested with real audio files

**Note:** Pulumi apply was done locally. The Cloud Run Job env var is
already live.

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 02:53:46 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 38b966f30c Modal → GCP audio separation migration (#571)
@coderabbitai ignore

## Summary
- Comprehensive migration plan: Modal → Cloud Run GPU (L4) for audio
separation
- Replaces old stub plan with full implementation details
- **Architecture**: Cloud Run GPU service (scale-to-zero, ~$0.13/job)
- **Model upgrade**: Ensemble presets as default (instrumental_clean +
karaoke) for +35% quality
- **Pipeline optimization**: Decouple separation from lyrics review
critical path
- Implementation will be added to this PR

## Plan highlights
- Phase 1: Cloud Run GPU server (python-audio-separator repo)
- Phase 2: GCP infrastructure via Pulumi (this repo)
- Phase 3: Pipeline decoupling + preset-based model config
- Phase 4: Cutover, monitor, decommission Modal

See `docs/archive/2026-03-22-modal-to-gcp-migration-plan.md` for full
details.

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 22:20:55 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 3391e5c9f5 Fix missing pip in GPU runner Python toolcache (#576)
## Summary

- Python 3.13 on GPU runners was built with `--with-ensurepip=install`
but `pip` wasn't actually in site-packages
- `setup-python@v5` requires a working `pip` module — CI failed with `No
module named pip`
- Added explicit `ensurepip --upgrade` bootstrap after `make install`
- Manually fixed all 3 runners (cleared toolcache + bootstrapped pip)

Follows #573, #574, #575 in the GPU runner fix series.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 20:21:29 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 b0575ba62c Fix Poetry permissions on GPU runners (#575)
## Summary

- Follow-up to #574. GPU runners' CI jobs failed with `EACCES:
permission denied, stat '/usr/local/bin/poetry'` because Poetry was
installed under `/root/.local/` (mode 700)
- The `runner` user can't follow symlinks into root's home directory
- Fix: install Poetry to `/opt/poetry` (shared location) using
`POETRY_HOME` env var

## What happened

1. Startup script runs `curl | python3 -` as root → Poetry installed to
`/root/.local/share/pypoetry/`
2. Symlink created: `/usr/local/bin/poetry` → `/root/.local/bin/poetry`
3. Poetry binary's shebang:
`#!/root/.local/share/pypoetry/venv/bin/python`
4. `runner` user can't access anything under `/root/` (mode 700)
5. `setup-python@v5` cache step tries to stat Poetry → EACCES → job
cancellation

## Test plan

- [x] Manually fixed permissions on all 3 running runners (temporary)
- [x] Applied via `pulumi up` — runners recreated with new startup
script
- [ ] Runners will re-register with GitHub after full startup (~15-20
min)
- [ ] Re-run audio-separator CI to confirm

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 20:10:24 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 8baa7d7db2 Fix GPU startup: upgrade kernel when headers unavailable (#574)
## Summary

- Follow-up to #573. The previous fix handled kernel mismatches on
**existing** VMs but failed on **fresh** VMs created from the
`debian-cloud/debian-12` base image
- The base image ships kernel `6.1.0-43` but Debian repos have moved to
`6.1.0-44`, so `apt-get install linux-headers-6.1.0-43-cloud-amd64`
fails with "Unable to locate package"
- The startup script now detects this and upgrades the kernel + reboots
once before proceeding

## What changed

Added kernel upgrade + reboot logic to `github_runner_gpu.sh`:

1. Check if headers are available for the running kernel via `apt-cache
show`
2. If not: install `linux-image-cloud-amd64` +
`linux-headers-cloud-amd64` (meta-packages tracking latest), set a
reboot flag, and reboot
3. After reboot: running kernel matches available headers, flag is
cleaned up, script continues normally with DKMS build + NVIDIA driver
install

The reboot flag (`/var/lib/gpu-runner-kernel-upgraded`) prevents
infinite reboot loops — if headers are still unavailable after one
upgrade attempt, the script gives up with diagnostics.

## Test plan

- [x] Applied new startup script to all 3 GPU runners via `pulumi up
--target`
- [x] Verified runner 1: kernel upgraded from `6.1.0-43` → `6.1.0-44`,
reboot happened, nvidia-smi shows `595.45.04, Tesla T4, 15360 MiB`
- [x] Verified runner 2: same result
- [ ] Waiting for all 3 runners to complete full startup and register
online with GitHub

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 16:52:25 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 067a66fc26 Fix GPU runner NVIDIA driver failure on kernel updates (#573)
## Summary

- GPU runners (github-gpu-runner-1/2/3) failed with `nvidia-smi` errors
because Debian auto-updated the kernel but the NVIDIA kernel module
wasn't rebuilt for the new version
- The startup script's idempotency check (`command -v nvidia-smi`) was
checking for the *binary*, not the *loaded kernel module*, so it
silently skipped driver setup on restarts
- Fixed the startup script to always ensure kernel headers match the
running kernel, rebuild DKMS modules when the nvidia module isn't
loaded, and clean up stale headers

## What happened

1. Debian updated kernel from `6.1.0-43` → `6.1.0-44-cloud-amd64`
2. NVIDIA kernel module was built for `-43` only
3. On next VM start, `nvidia-smi` binary existed (passes `command -v`)
so driver install was skipped
4. But the kernel module couldn't load (built for wrong kernel) →
`nvidia-smi` failed at runtime
5. All 3 GPU integration test jobs failed on PR #273
(python-audio-separator)

## Fix

**Immediate** (already applied to all 3 runners via SSH):
- Installed `linux-headers-6.1.0-44-cloud-amd64`, ran `dkms
autoinstall`, `modprobe nvidia`
- Re-ran CI run 23408072295 → all 4 jobs passed

**Permanent** (this PR — startup script changes):
- Always install kernel headers for `$(uname -r)` on every boot
- Install `dkms` alongside headers (not just as fallback)
- Check `lsmod | grep nvidia` to detect unloaded module → rebuild via
DKMS
- Clean up stale kernel headers for old kernels (prevents disk bloat)
- Add diagnostic output on failure (dkms status, module listing)
- Reduce retry from 30×10s to 10×5s (DKMS rebuild is deterministic)

## Test plan

- [x] Manually fixed all 3 GPU runners and verified `nvidia-smi` works
- [x] Re-ran failing CI (run 23408072295) — all jobs passed
- [ ] After merge + Pulumi deploy, stop/start a GPU runner to verify the
new startup script works end-to-end

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 15:10:13 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 d1a877c8f4 Disable GDrive validator success notifications (#572)
## Summary
- Set `NOTIFY_ON_SUCCESS` to `false` for the GDrive validator Cloud
Function
- Stops "Karaoke GDrive: All Clear" emails and Pushbullet notifications
on successful daily validation
- Error/issue notifications remain active and unaffected

Already deployed via `pulumi up`.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 14:23:44 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 be4acbe915 IP geolocation enrichment for admin UI (#570)
Enrich all admin IP displays with country flag + ISP inline, hover
popover for full details. Backend caches via ip-api.com in Firestore.

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 03:05:18 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 fef5130519 Add stats action to divebar-lookup Cloud Function (#568)
## Summary
- New `stats` action on the divebar-lookup Cloud Function
- Returns catalog, GCS mirror, format breakdown, cross-reference, and KN
data stats
- Used by KJ Controller's new status panel

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 22:14:43 +00:00
78 changed files with 6943 additions and 780 deletions

No files matched your search

@@ -0,0 +1,109 @@
# Plan: Admin Feedback Visibility
**Created:** 2026-03-23
**Branch:** feat/sess-20260323-1454-feedback-email-debug
**Status:** Draft
## Overview
User feedback submissions are stored in Firestore (`user_feedback` collection) but are completely invisible to the admin. The admin panel only shows a boolean "Feedback Submitted: Yes/No" badge per user. This plan adds:
1. **Admin UI page** to browse and review all submitted feedback
2. **Email notification** to admin@nomadkaraoke.com on each new submission
## Requirements
- [ ] Admin page at `/admin/feedback` listing all feedback with ratings, text, timestamps, and user info
- [ ] Sortable by date (newest first by default) and filterable by search (email)
- [ ] Star ratings rendered visually (not just numbers)
- [ ] Email sent to admin@nomadkaraoke.com immediately when feedback is submitted
- [ ] Email includes all feedback content (ratings, text fields, user email)
- [ ] Test data filtering works (exclude_test toggle)
- [ ] Sidebar navigation includes new "Feedback" item
## Technical Approach
### Admin API Endpoint
Add `GET /api/admin/feedback` to `backend/api/routes/admin.py`. Follows the standard admin endpoint pattern: `require_admin` dependency, pagination with `limit`/`offset`/`search`/`exclude_test`, returns Pydantic response model. Queries `user_feedback` Firestore collection.
### Admin UI Page
New page at `frontend/app/admin/feedback/page.tsx`. Follows existing admin page patterns (Card, Table, Badge, pagination, search input, loading states). Uses `adminApi.listFeedback()` to fetch data.
### Email Notification
Add a new method to `EmailService` (or call `send_email` directly) from the `submit_user_feedback` endpoint in `users.py`. Uses the existing SendGrid infrastructure — no new template service templates needed since this is an internal admin notification (simple HTML table with the feedback data).
## Implementation Steps
### Step 1: Backend — Admin feedback list endpoint
1. [ ] Add `AdminFeedbackItem` and `AdminFeedbackListResponse` Pydantic models to `admin.py`
2. [ ] Add `GET /api/admin/feedback` endpoint with:
- Pagination: `limit=50`, `offset=0`
- Search by user email
- `exclude_test` filter (reuse `is_test_email`)
- Sort by `created_at` descending
- Return: items, total, offset, limit, has_more
3. [ ] Add aggregate stats in response: average ratings, total count
### Step 2: Backend — Email notification on submission
4. [ ] Add `send_feedback_notification` method to `EmailService` that sends an HTML email to `admin@nomadkaraoke.com` containing:
- User email
- All 4 star ratings
- All text fields
- Would recommend / would use again
- Submitted timestamp
- Link to admin feedback page
5. [ ] Call `send_feedback_notification` from `submit_user_feedback` in `users.py` (fire-and-forget, don't block the user response on email success)
### Step 3: Frontend — Admin API client
6. [ ] Add `listFeedback` method to `adminApi` in `frontend/lib/api.ts`
7. [ ] Add TypeScript types for `AdminFeedbackItem` and `AdminFeedbackListResponse`
### Step 4: Frontend — Admin feedback page
8. [ ] Create `frontend/app/admin/feedback/page.tsx` with:
- Table: user email, date, overall rating (stars), ease of use, lyrics accuracy, correction experience, would recommend, would use again
- Expandable rows or click-to-detail for text fields (what went well, what could improve, additional comments)
- Search by email
- Pagination (50 per page)
- Refresh button
- Test data toggle (via `useAdminSettings`)
9. [ ] Add "Feedback" item to admin sidebar in `frontend/components/admin/admin-sidebar.tsx` with `MessageSquare` icon
### Step 5: Testing
10. [ ] Backend unit test for `GET /api/admin/feedback` endpoint (pagination, search, exclude_test)
11. [ ] Backend unit test for `send_feedback_notification` email method
12. [ ] Frontend component test for feedback page (render, empty state)
## Files to Create/Modify
| File | Action | Description |
|------|--------|-------------|
| `backend/api/routes/admin.py` | Modify | Add feedback list endpoint + response models |
| `backend/api/routes/users.py` | Modify | Add email notification call in `submit_user_feedback` |
| `backend/services/email_service.py` | Modify | Add `send_feedback_notification` method |
| `frontend/lib/api.ts` | Modify | Add `adminApi.listFeedback()` method + types |
| `frontend/app/admin/feedback/page.tsx` | Create | Admin feedback review page |
| `frontend/components/admin/admin-sidebar.tsx` | Modify | Add "Feedback" nav item |
| `backend/tests/test_admin_feedback.py` | Create | Tests for admin feedback endpoint |
| `backend/tests/test_feedback_email.py` | Create | Tests for feedback email notification |
## Testing Strategy
- **Unit tests**: Admin endpoint (pagination, filtering, sorting), email method (content formatting, send call)
- **Integration**: Submit feedback → verify email service called
- **Manual verification**: Check email arrives in admin@nomadkaraoke.com inbox after submission
## Open Questions
- [ ] Should the admin page show feedback from the old `beta_feedback` collection too, or just `user_feedback`? (Recommendation: just `user_feedback` — the beta collection is legacy)
- [ ] Should there be any spam/quality detection flagging? (Some submissions appear to game the system for credits)
## Rollback Plan
- Backend: Remove endpoint from admin.py, revert email call in users.py
- Frontend: Delete feedback page, remove sidebar item
- No data migration needed — Firestore collection unchanged
+151
View File
@@ -0,0 +1,151 @@
# Plan: AI-Powered Credit Gating
**Created:** 2026-03-23
**Branch:** feat/sess-20260323-1716-ai-credit-gating
**Status:** Implemented
## Overview
Replace the automatic welcome/feedback credit grants with an AI-powered evaluation step. When a user triggers a credit grant (email verification or feedback submission), instead of immediately granting credits, we collect abuse signals and ask Gemini to make a grant/deny decision. Suspected abusers get a friendly rejection email (CC'd to Andrew) instead of free credits.
## Requirements
- [ ] Welcome credit grants go through AI evaluation before granting
- [ ] Feedback credit grants go through AI evaluation before granting
- [ ] AI evaluates: fingerprint correlations, IP correlations, IP geo info, user agent, signup recency patterns
- [ ] Approved users get credits as before (seamless experience)
- [ ] Rejected users get a friendly-but-firm email explaining the situation, CC'd to andrew@beveridge.uk
- [ ] Rejection email invites them to reply if it's a mistake
- [ ] Decision is logged to Firestore for audit trail
- [ ] Fail-open: if AI evaluation fails, grant credits (don't punish users for our errors)
- [ ] Admin can override decisions via existing admin credit grant endpoint
## Technical Approach
### Architecture
```
User verifies email / submits feedback
↓
Collect abuse signals (sync, fast):
- User's fingerprint + IP
- Other accounts with same fingerprint (from correlations)
- Other accounts with same IP
- IP geolocation info
- Recent signup count from same IP/fingerprint (last 24h)
- User agent string
- For feedback: the feedback content itself
↓
Call Gemini (vertexai/gemini-2.5-pro-preview) with structured prompt:
- Present all signals
- Ask for JSON response: {decision: "grant" | "deny", reasoning: string, confidence: number}
↓
If "grant": grant credits normally, log decision
If "deny": skip credit grant, send rejection email, log decision
If AI call fails: grant credits (fail-open), log error
```
### Key Design Decisions
1. **Two-phase verification**: The magic link verify endpoint returns immediately with session + a `credit_status: "evaluating"` field. The frontend shows a "preparing your account" loading screen, then polls/waits for the evaluation result via a new lightweight endpoint. This keeps the auth flow snappy while the AI evaluation runs in the background of the same request or via a short follow-up call. The frontend then shows either a celebratory "2 free credits!" interstitial or a "sorry, couldn't grant credits" interstitial before navigating to the dashboard.
2. **Fail-open**: If Gemini is down or returns an error, we grant credits. Better to let an occasional abuser through than block legitimate users.
3. **Use google-genai directly**: The project already has `langchain-google-genai` installed. We can use the simpler `google.generativeai` library directly for a focused prompt/response, or use the existing LangChain setup. We'll use `google.generativeai` for simplicity since this is a single-turn evaluation, not an agentic workflow.
4. **Structured JSON output**: Ask Gemini for structured output with decision, reasoning, and confidence to make decisions parseable and auditable.
5. **Log all decisions**: Store every evaluation in a `credit_evaluations` Firestore collection for audit trail and to tune the prompt over time.
## Implementation Steps
### Step 1: Add google-generativeai dependency
- Add `google-generativeai` to pyproject.toml (lightweight, direct Gemini access)
- Verify it works with Vertex AI auth in the nomadkaraoke project
### Step 2: Create credit evaluation service
- New file: `backend/services/credit_evaluation_service.py`
- `CreditEvaluationService` class with:
- `evaluate_credit_grant(email, grant_type, feedback_content=None) -> CreditEvaluation`
- Collects all abuse signals by calling existing services (user_service, ip_geolocation_service)
- Builds prompt with signals
- Calls Gemini for decision
- Logs decision to Firestore
- Returns structured result
### Step 3: Build the Gemini prompt
- System prompt explaining the role: "You are an anti-abuse evaluator for a karaoke video service..."
- Present all signals in a structured format
- Request JSON response: `{decision: "grant"|"deny", reasoning: "...", confidence: 0.0-1.0}`
- Include clear guidelines: same fingerprint across accounts = very suspicious, same IP = somewhat suspicious, etc.
### Step 4: Create rejection email template
- Add `send_credit_denied_email(email, reasoning)` to EmailService
- Friendly-but-firm tone
- CC andrew@beveridge.uk
- Invite reply if it's a mistake
- Use existing email template infrastructure (branding, styling)
### Step 5: Integrate into welcome credit flow
- Modify `grant_welcome_credits_if_eligible()` in user_service.py
- Before granting: call `CreditEvaluationService.evaluate_credit_grant(email, "welcome")`
- If denied: send rejection email, return False
- If error: log warning, grant anyway (fail-open)
### Step 6: Integrate into feedback credit flow
- Modify feedback endpoint in users.py
- Before granting credits: evaluate with feedback content included
- If denied: return different response message, send rejection email
- If error: grant anyway
### Step 7: Add Firestore collection for audit trail
- Collection: `credit_evaluations`
- Document fields: email, grant_type, decision, reasoning, confidence, signals_snapshot, model_used, evaluated_at
- TTL: keep indefinitely (small volume, high audit value)
### Step 8: Tests
- Unit tests for signal collection
- Unit tests for prompt building
- Unit tests for decision parsing (grant/deny/error cases)
- Integration test for the evaluation service with mocked Gemini
- Integration test for welcome credit flow with evaluation
- Integration test for feedback credit flow with evaluation
- Test fail-open behavior
### Step 9: Configuration
- Add env vars: `CREDIT_EVAL_MODEL` (default: "gemini-2.5-pro-preview"), `CREDIT_EVAL_ENABLED` (default: true)
- Add to config.py
## Files to Create/Modify
| File | Action | Description |
|------|--------|-------------|
| `pyproject.toml` | Modify | Add google-generativeai dependency |
| `backend/config.py` | Modify | Add credit evaluation config vars |
| `backend/services/credit_evaluation_service.py` | Create | New service: collect signals, call Gemini, log decision |
| `backend/services/user_service.py` | Modify | Integrate evaluation into welcome credit grant |
| `backend/api/routes/users.py` | Modify | Integrate evaluation into feedback credit grant |
| `backend/services/email_service.py` | Modify | Add credit denied email template |
| `backend/tests/test_credit_evaluation.py` | Create | Tests for evaluation service |
| `backend/tests/test_anti_abuse.py` | Modify | Update welcome credit tests for evaluation |
| `frontend/app/auth/verify/page.tsx` | Modify | Add "preparing account" loading + credit result interstitial |
| `frontend/lib/api.ts` | Modify | Add credit evaluation status endpoint |
## Testing Strategy
- **Unit tests**: Signal collection, prompt building, response parsing, fail-open behavior
- **Integration tests**: Full evaluation flow with mocked Gemini responses
- **E2E tests**: Manual verification in production with test accounts
- **Edge cases**: Gemini timeout, malformed response, missing signals, first-ever user (no correlations)
## Open Questions
1. **Gemini model**: Using `gemini-3.1-pro-preview` as specified — already available in the nomadkaraoke GCP project.
2. **Latency UX**: Frontend shows a friendly "preparing your account" loading screen while evaluation runs. Then transitions to either a celebratory "2 free credits!" message (with gentle reminder not to abuse) or a "sorry, couldn't grant free credits" message with a buy credits CTA. User clicks through to dashboard from either.
3. **Should we also gate the existing rate limiter?** Currently `is_signup_rate_limited()` silently blocks at 2 accounts per IP/fingerprint per 24h. The AI evaluation is complementary — rate limiter blocks obvious rapid abuse, AI evaluation catches more subtle patterns.
## Rollback Plan
Set `CREDIT_EVAL_ENABLED=false` in Cloud Run env vars → immediate rollback to auto-grant behavior. No data model changes needed. The evaluation service is purely additive.
+1 -1
View File
@@ -28,7 +28,7 @@
- **Backend**: FastAPI on Cloud Run, Firestore, GCS, Secret Manager
- **Frontend**: Next.js on Cloudflare Pages
- **Processing**: Modal (GPU audio separation), AudioShake/Whisper (transcription)
- **Processing**: Cloud Run GPU (L4 audio separation), AudioShake/Whisper (transcription)
- **Infra**: Pulumi IaC, GitHub Actions CI/CD
## Essential Rules
+189
View File
@@ -24,6 +24,7 @@ from backend.services.audio_search_service import get_audio_search_service, NoRe
from backend.models.job import JobStatus
from backend.services.firestore_service import log_to_job
from backend.utils.test_data import is_test_email
from backend.services.ip_geolocation_service import get_ip_geolocation_service
from karaoke_gen.utils import sanitize_filename
@@ -3585,6 +3586,56 @@ async def find_related_accounts(
}
@router.get("/abuse/correlations")
async def find_account_correlations(
auth_result: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
"""
Find clusters of accounts sharing the same device fingerprint or signup IP.
Returns fingerprint clusters (RED flag - near-certain multi-accounting) and
IP clusters (ORANGE flag - suspicious but could be shared network), sorted
by group size. Includes user agent data for additional correlation signal.
"""
result = user_service.find_account_correlations()
user_agents = result.get("user_agents", {})
def serialize_cluster_user(u, include_user_agent=True):
data = {
"email": u.email,
"signup_ip": u.signup_ip,
"device_fingerprint": u.device_fingerprint,
"credits": u.credits,
"total_jobs_created": u.total_jobs_created,
"total_jobs_completed": u.total_jobs_completed,
"total_spent": u.total_spent,
"created_at": str(u.created_at),
}
if include_user_agent:
data["user_agent"] = user_agents.get(u.email)
return data
return {
"fingerprint_clusters": [
{
"fingerprint": cluster["fingerprint"],
"count": len(cluster["users"]),
"users": [serialize_cluster_user(u) for u in cluster["users"]],
}
for cluster in result["fingerprint_clusters"]
],
"ip_clusters": [
{
"ip": cluster["ip"],
"count": len(cluster["users"]),
"users": [serialize_cluster_user(u) for u in cluster["users"]],
}
for cluster in result["ip_clusters"]
],
}
@router.get("/abuse/suspicious")
async def find_suspicious_accounts(
min_jobs: int = 2,
@@ -3761,3 +3812,141 @@ async def backfill_signup_ips(
"skipped_already_set": skipped,
"no_ip_found": no_ip_found,
}
# =============================================================================
# IP Geolocation Lookup
# =============================================================================
class IpBatchRequest(BaseModel):
"""Request for batch IP geolocation lookup."""
ips: list[str]
@router.get("/abuse/ip-info/{ip_address:path}")
async def get_ip_info(
ip_address: str,
auth_result: AuthResult = Depends(require_admin),
):
"""Look up geolocation info for a single IP address."""
geo_service = get_ip_geolocation_service()
return geo_service.lookup_ip(ip_address)
@router.post("/abuse/ip-info/batch")
async def get_ip_info_batch(
request: IpBatchRequest,
auth_result: AuthResult = Depends(require_admin),
):
"""Look up geolocation info for multiple IP addresses."""
if len(request.ips) > 100:
raise HTTPException(status_code=400, detail="Maximum 100 IPs per batch request")
geo_service = get_ip_geolocation_service()
return geo_service.lookup_ips_batch(request.ips)
# =============================================================================
# User Feedback
# =============================================================================
class AdminFeedbackItem(BaseModel):
"""Single feedback submission for admin view."""
id: str
user_email: str
created_at: Optional[str] = None
overall_rating: int
ease_of_use_rating: int
lyrics_accuracy_rating: int
correction_experience_rating: int
what_went_well: Optional[str] = None
what_could_improve: Optional[str] = None
additional_comments: Optional[str] = None
would_recommend: bool = True
would_use_again: bool = True
class AdminFeedbackListResponse(BaseModel):
"""Paginated list of feedback submissions."""
items: List[AdminFeedbackItem]
total: int
offset: int
limit: int
has_more: bool
avg_overall_rating: Optional[float] = None
avg_ease_of_use_rating: Optional[float] = None
avg_lyrics_accuracy_rating: Optional[float] = None
avg_correction_experience_rating: Optional[float] = None
@router.get("/feedback", response_model=AdminFeedbackListResponse)
def list_user_feedback(
limit: int = 50,
offset: int = 0,
search: Optional[str] = None,
exclude_test: bool = False,
auth_result: AuthResult = Depends(require_admin),
):
"""List all user feedback submissions with pagination and search."""
limit = max(1, min(limit, 200))
offset = max(0, offset)
user_service = get_user_service()
db = user_service.db
items = []
for doc in db.collection("user_feedback").stream():
data = doc.to_dict()
email = data.get("user_email", "")
if exclude_test and is_test_email(email):
continue
if search and search.lower() not in email.lower():
continue
created_at = data.get("created_at")
if created_at is not None and hasattr(created_at, "isoformat"):
created_at = created_at.isoformat()
elif created_at is not None:
created_at = str(created_at)
items.append(AdminFeedbackItem(
id=data.get("id", doc.id),
user_email=email,
created_at=created_at,
overall_rating=data.get("overall_rating", 0),
ease_of_use_rating=data.get("ease_of_use_rating", 0),
lyrics_accuracy_rating=data.get("lyrics_accuracy_rating", 0),
correction_experience_rating=data.get("correction_experience_rating", 0),
what_went_well=data.get("what_went_well"),
what_could_improve=data.get("what_could_improve"),
additional_comments=data.get("additional_comments"),
would_recommend=data.get("would_recommend", True),
would_use_again=data.get("would_use_again", True),
))
# Sort by newest first
items.sort(key=lambda x: x.created_at or "", reverse=True)
# Compute aggregate stats
total = len(items)
avg_overall = sum(i.overall_rating for i in items) / total if total else None
avg_ease = sum(i.ease_of_use_rating for i in items) / total if total else None
avg_lyrics = sum(i.lyrics_accuracy_rating for i in items) / total if total else None
avg_correction = sum(i.correction_experience_rating for i in items) / total if total else None
paginated = items[offset:offset + limit]
return AdminFeedbackListResponse(
items=paginated,
total=total,
offset=offset,
limit=limit,
has_more=(offset + limit) < total,
avg_overall_rating=round(avg_overall, 2) if avg_overall is not None else None,
avg_ease_of_use_rating=round(avg_ease, 2) if avg_ease is not None else None,
avg_lyrics_accuracy_rating=round(avg_lyrics, 2) if avg_lyrics is not None else None,
avg_correction_experience_rating=round(avg_correction, 2) if avg_correction is not None else None,
)
+1 -1
View File
@@ -2486,7 +2486,7 @@ async def complete_style_uploads(
# Overwrite background paths with custom uploads
for asset_key, gcs_path in new_style_assets.items():
bucket_name = storage_service.bucket_name
bucket_name = storage_service.bucket.name
gcs_uri = f"gs://{bucket_name}/{gcs_path}"
if asset_key == "intro_background" and "intro" in style_params:
style_params["intro"]["background_image"] = gcs_uri
+33
View File
@@ -308,6 +308,39 @@ async def flacfetch_health() -> Dict[str, Any]:
}
@router.get("/health/audio-separator")
async def audio_separator_health() -> Dict[str, Any]:
"""
Return the installed audio-separator package version.
Does NOT call the remote GPU service — that would cold-start an expensive
Cloud Run GPU instance (~$0.07 per wake). Instead reports the locally
installed package version, which matches what the audio worker uses.
No authentication required.
"""
from backend.config import get_settings
settings = get_settings()
if not settings.audio_separator_api_url:
return {
"available": False,
"status": "not_configured",
}
try:
from importlib.metadata import version
pkg_version = version("audio-separator")
except Exception:
pkg_version = None
return {
"available": True,
"status": "ok",
"version": pkg_version,
}
@router.get("/health/detailed")
async def detailed_health_check() -> Dict[str, Any]:
"""
+81 -6
View File
@@ -297,13 +297,17 @@ async def verify_magic_link(
if not success or not user:
raise HTTPException(status_code=401, detail=message)
# Grant welcome credits on first verification (not at account creation)
# Grant welcome credits on first verification (with AI abuse evaluation)
credits_granted = 0
if user_service.grant_welcome_credits_if_eligible(user.email):
credit_status = "not_applicable" # returning user, not first login
granted, credit_status = user_service.grant_welcome_credits_if_eligible(user.email)
if granted:
credits_granted = user_service.NEW_USER_FREE_CREDITS
logger.info(f"Granted {credits_granted} welcome credits to {_mask_email(user.email)}")
# Refresh user to get updated credit balance
user = user_service.get_user(user.email)
elif credit_status == "denied":
logger.info(f"Welcome credits denied for {_mask_email(user.email)}")
# Create session with tenant context and device fingerprint from the magic link
magic_link_fingerprint = magic_link_data.get('device_fingerprint') if magic_link_doc.exists else None
@@ -346,6 +350,7 @@ async def verify_magic_link(
message="Successfully signed in",
tenant_subdomain=tenant_subdomain,
credits_granted=credits_granted,
credit_status=credit_status,
)
@@ -1121,7 +1126,7 @@ async def check_feedback_eligibility(
eligible=eligible,
has_submitted=user.has_submitted_feedback,
jobs_completed=user.total_jobs_completed,
credits_reward=2,
credits_reward=1,
)
@@ -1132,7 +1137,7 @@ async def submit_user_feedback(
user_service: UserService = Depends(get_user_service),
):
"""
Submit product feedback to earn 2 free credits.
Submit product feedback to earn 1 free credit.
Requires authentication. Users must have completed 2+ jobs and
not have already submitted feedback. At least one text field
@@ -1210,8 +1215,59 @@ async def submit_user_feedback(
has_submitted_feedback=True,
)
# Grant 2 credits
credits_granted = 2
# AI evaluation before granting feedback credits
credits_granted = 0
feedback_content = {
"overall_rating": request.overall_rating,
"what_went_well": request.what_went_well,
"what_could_improve": request.what_could_improve,
"additional_comments": request.additional_comments,
}
try:
from backend.services.credit_evaluation_service import get_credit_evaluation_service
eval_service = get_credit_evaluation_service()
evaluation = eval_service.evaluate(user.email, "feedback", feedback_content)
if evaluation.decision == "deny":
logger.info(f"Feedback credits denied for {_mask_email(user.email)}: {evaluation.reasoning}")
try:
from backend.services.email_service import get_email_service
get_email_service().send_credit_denied_email(user.email, "feedback")
except Exception:
logger.exception(f"Failed to send credit denied email to {_mask_email(user.email)}")
return UserFeedbackResponse(
status="success",
message="Thank you for your feedback! We appreciate your input.",
credits_granted=0,
)
if evaluation.decision == "pending_review":
logger.info(f"Feedback credits pending review for {_mask_email(user.email)}: {evaluation.reasoning}")
try:
from backend.services.email_service import get_email_service
get_email_service().send_credit_review_needed_email(user.email, "feedback", evaluation.reasoning)
except Exception:
logger.exception(f"Failed to send review needed email for {_mask_email(user.email)}")
return UserFeedbackResponse(
status="success",
message="Thank you for your feedback! Our team will review your account shortly.",
credits_granted=0,
)
except Exception:
logger.exception(f"Credit evaluation failed for {_mask_email(user.email)} — pending review (fail-closed)")
try:
from backend.services.email_service import get_email_service
get_email_service().send_credit_review_needed_email(user.email, "feedback", "Evaluation error")
except Exception:
pass
return UserFeedbackResponse(
status="success",
message="Thank you for your feedback! Our team will review your account shortly.",
credits_granted=0,
)
# Grant 1 credit (passed evaluation)
credits_granted = 1
user_service.add_credits(
email=user.email,
amount=credits_granted,
@@ -1223,6 +1279,25 @@ async def submit_user_feedback(
f"credits granted: {credits_granted}"
)
# Send admin notification email (fire-and-forget)
try:
from backend.services.email_service import get_email_service
email_service = get_email_service()
email_service.send_feedback_notification(
user_email=user.email,
overall_rating=request.overall_rating,
ease_of_use_rating=request.ease_of_use_rating,
lyrics_accuracy_rating=request.lyrics_accuracy_rating,
correction_experience_rating=request.correction_experience_rating,
what_went_well=request.what_went_well,
what_could_improve=request.what_could_improve,
additional_comments=request.additional_comments,
would_recommend=request.would_recommend,
would_use_again=request.would_use_again,
)
except Exception as e:
logger.warning(f"Failed to send feedback notification email: {e}")
return UserFeedbackResponse(
status="success",
message=f"Thank you for your feedback! You earned {credits_granted} free credits.",
+6
View File
@@ -57,6 +57,12 @@ class Settings(BaseSettings):
# use uncorrected transcription - human review will fix any issues.
agentic_correction_timeout_seconds: int = int(os.getenv("AGENTIC_CORRECTION_TIMEOUT_SECONDS", "180"))
# AI Credit Evaluation (anti-abuse gating for free credits)
# When enabled, welcome and feedback credit grants are evaluated by Gemini
# before granting. Fail-open: if evaluation fails, credits are granted anyway.
credit_eval_enabled: bool = os.getenv("CREDIT_EVAL_ENABLED", "true").lower() in ("true", "1", "yes")
credit_eval_model: str = os.getenv("CREDIT_EVAL_MODEL", "gemini-3.1-pro-preview")
# Cloud Tasks (for scalable worker coordination)
# When enabled, workers are triggered via Cloud Tasks for guaranteed delivery
# When disabled (default), workers are triggered via direct HTTP (for development)
+3 -2
View File
@@ -180,6 +180,7 @@ class VerifyMagicLinkResponse(BaseModel):
message: str
tenant_subdomain: Optional[str] = None
credits_granted: int = 0
credit_status: str = "not_applicable" # "granted", "denied", "pending_review", "already_granted", "not_applicable"
class UserPublic(BaseModel):
@@ -228,7 +229,7 @@ class UserFeedback(BaseModel):
Feedback from any user (not just beta testers).
Stored in Firestore 'user_feedback' collection.
Users earn 2 free credits for submitting detailed feedback.
Users earn 1 free credit for submitting detailed feedback.
"""
id: str
user_email: str
@@ -283,4 +284,4 @@ class FeedbackEligibilityResponse(BaseModel):
eligible: bool
has_submitted: bool
jobs_completed: int
credits_reward: int = 2
credits_reward: int = 1
@@ -0,0 +1,431 @@
"""
AI-powered credit evaluation service.
Evaluates whether to grant free credits (welcome or feedback) by collecting
abuse signals and asking Gemini for a grant/deny decision. Fail-open: if
the AI call fails for any reason, credits are granted.
"""
import json
import logging
import uuid
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Optional
from backend.config import get_settings
logger = logging.getLogger(__name__)
CREDIT_EVALUATIONS_COLLECTION = "credit_evaluations"
@dataclass
class CreditEvaluation:
"""Result of an AI credit evaluation."""
decision: str # "grant" or "deny"
reasoning: str
confidence: float
error: Optional[str] = None # Set if evaluation failed (decision defaults to "grant")
SYSTEM_PROMPT = """You are an anti-abuse evaluator for Nomad Karaoke, a web service that creates professional karaoke videos. Each job costs the service real money in API credits and cloud compute.
New users get 1 free welcome credit to try the service. Users who complete 2 jobs and submit feedback get 1 more credit. Some users abuse this by creating multiple accounts to get unlimited free karaoke generation.
Your job: Given the signals below, decide whether to GRANT or DENY free credits to this user.
## Decision Guidelines
**DENY if any of these are true:**
- The user's device fingerprint matches other accounts (strong signal of multi-accounting)
- The user's signup IP matches other accounts AND those accounts also have suspicious patterns (e.g., no spend, same user agent)
- There's a clear pattern of account creation from the same device/network to farm free credits
**GRANT if:**
- This appears to be a genuine new user with no suspicious correlations
- The IP match is explainable (e.g., different fingerprints suggest different actual users on a shared network like a school or office)
- There's insufficient evidence to confidently flag abuse
**When in doubt, GRANT.** False positives (blocking real users) are worse than false negatives (letting an occasional abuser through). We'd rather lose a few dollars than alienate a real customer.
## Response Format
Respond with ONLY a JSON object, no other text:
{"decision": "grant" or "deny", "reasoning": "Brief explanation", "confidence": 0.0 to 1.0}
"""
def _build_user_prompt(
email: str,
grant_type: str,
user_data: dict,
fingerprint_matches: list,
ip_matches: list,
ip_geo: Optional[dict],
recent_signups_ip: int,
recent_signups_fp: int,
user_agent: Optional[str],
feedback_content: Optional[dict] = None,
) -> str:
"""Build the user prompt with all abuse signals."""
lines = [
f"## Credit Grant Request",
f"- **Email:** {email}",
f"- **Grant type:** {grant_type} credits",
f"- **User's device fingerprint:** {user_data.get('device_fingerprint', 'unknown')}",
f"- **User's signup IP:** {user_data.get('signup_ip', 'unknown')}",
f"- **User agent:** {user_agent or 'unknown'}",
f"- **Account created:** {user_data.get('created_at', 'unknown')}",
f"- **Jobs created:** {user_data.get('total_jobs_created', 0)}",
f"- **Jobs completed:** {user_data.get('total_jobs_completed', 0)}",
f"- **Total spent (real money):** ${user_data.get('total_spent', 0) / 100:.2f}",
f"- **Current credits:** {user_data.get('credits', 0)}",
"",
]
# IP geolocation
if ip_geo and ip_geo.get("status") == "success":
lines.extend([
f"## IP Geolocation",
f"- **Country:** {ip_geo.get('country', 'unknown')} ({ip_geo.get('country_code', '')})",
f"- **City/Region:** {ip_geo.get('city', '')}, {ip_geo.get('region', '')}",
f"- **ISP:** {ip_geo.get('isp', 'unknown')}",
f"- **Organization:** {ip_geo.get('org', 'unknown')}",
f"- **ASN:** {ip_geo.get('as_number', '')} {ip_geo.get('as_name', '')}",
"",
])
# Recent signup patterns
lines.extend([
f"## Recent Signup Patterns (last 24 hours)",
f"- **New accounts from same IP:** {recent_signups_ip}",
f"- **New accounts from same fingerprint:** {recent_signups_fp}",
"",
])
# Fingerprint correlations
if fingerprint_matches:
lines.append("## Other Accounts with Same Device Fingerprint (RED FLAG)")
for match in fingerprint_matches:
lines.append(
f"- {match.get('email', '?')} | "
f"Jobs: {match.get('total_jobs_created', 0)} | "
f"Spent: ${match.get('total_spent', 0) / 100:.2f} | "
f"Created: {match.get('created_at', '?')}"
)
lines.append("")
else:
lines.extend(["## Other Accounts with Same Device Fingerprint", "None found.", ""])
# IP correlations
if ip_matches:
lines.append("## Other Accounts from Same Signup IP")
for match in ip_matches:
lines.append(
f"- {match.get('email', '?')} | "
f"Fingerprint: {match.get('device_fingerprint', 'unknown')} | "
f"Jobs: {match.get('total_jobs_created', 0)} | "
f"Spent: ${match.get('total_spent', 0) / 100:.2f} | "
f"Created: {match.get('created_at', '?')}"
)
lines.append("")
else:
lines.extend(["## Other Accounts from Same Signup IP", "None found.", ""])
# Feedback content (if applicable)
if feedback_content:
lines.extend([
"## Feedback Submitted",
f"- **Overall rating:** {feedback_content.get('overall_rating', '?')}/5",
f"- **What went well:** {feedback_content.get('what_went_well', 'N/A')[:200]}",
f"- **What could improve:** {feedback_content.get('what_could_improve', 'N/A')[:200]}",
f"- **Additional comments:** {feedback_content.get('additional_comments', 'N/A')[:200]}",
"",
])
lines.append("Based on these signals, should we GRANT or DENY free credits to this user?")
return "\n".join(lines)
def _parse_gemini_response(response_text: str) -> CreditEvaluation:
"""Parse Gemini's JSON response into a CreditEvaluation."""
try:
# Strip markdown code fences if present
text = response_text.strip()
if text.startswith("```"):
text = text.split("\n", 1)[1] if "\n" in text else text[3:]
if text.endswith("```"):
text = text.rsplit("```", 1)[0]
text = text.strip()
if text.startswith("json"):
text = text[4:].strip()
data = json.loads(text)
decision = data.get("decision", "").lower()
if decision not in ("grant", "deny"):
decision = "pending_review" # fail-closed: unknown decision → manual review
return CreditEvaluation(
decision=decision,
reasoning=str(data.get("reasoning", "No reasoning provided")),
confidence=float(data.get("confidence", 0.5)),
)
except (json.JSONDecodeError, ValueError, TypeError) as e:
logger.warning(f"Failed to parse Gemini response: {e}. Response: {response_text[:200]}")
return CreditEvaluation(
decision="pending_review",
reasoning="Failed to parse AI response — pending manual review",
confidence=0.0,
error=f"Parse error: {e}",
)
class CreditEvaluationService:
"""Evaluates credit grant requests using Gemini AI."""
def __init__(self):
self.settings = get_settings()
def _collect_signals(self, email: str) -> dict:
"""Collect all abuse signals for evaluation."""
from backend.services.user_service import get_user_service
from backend.services.ip_geolocation_service import get_ip_geolocation_service
user_service = get_user_service()
user = user_service.get_user(email)
if not user:
return {
"user_data": {},
"fingerprint_matches": [],
"ip_matches": [],
"ip_geo": None,
"recent_signups_ip": 0,
"recent_signups_fp": 0,
"user_agent": None,
}
user_data = {
"email": user.email,
"device_fingerprint": user.device_fingerprint,
"signup_ip": user.signup_ip,
"credits": user.credits,
"total_jobs_created": user.total_jobs_created,
"total_jobs_completed": user.total_jobs_completed,
"total_spent": user.total_spent,
"created_at": str(user.created_at),
}
# Find other accounts with same fingerprint
fingerprint_matches = []
if user.device_fingerprint:
fp_users = user_service.find_users_by_fingerprint(user.device_fingerprint)
fingerprint_matches = [
{
"email": u.email,
"total_jobs_created": u.total_jobs_created,
"total_spent": u.total_spent,
"created_at": str(u.created_at),
}
for u in fp_users if u.email != email
]
# Find other accounts from same IP
ip_matches = []
if user.signup_ip:
ip_users = user_service.find_users_by_signup_ip(user.signup_ip)
ip_matches = [
{
"email": u.email,
"device_fingerprint": u.device_fingerprint,
"total_jobs_created": u.total_jobs_created,
"total_spent": u.total_spent,
"created_at": str(u.created_at),
}
for u in ip_users if u.email != email
]
# IP geolocation
ip_geo = None
if user.signup_ip:
try:
geo_service = get_ip_geolocation_service()
ip_geo = geo_service.lookup_ip(user.signup_ip)
except Exception:
pass
# Recent signup counts
recent_signups_ip = 0
recent_signups_fp = 0
if user.signup_ip:
recent_signups_ip = user_service.count_recent_signups_from_ip(user.signup_ip)
if user.device_fingerprint:
recent_signups_fp = user_service.count_recent_signups_from_fingerprint(user.device_fingerprint)
# User agent from latest session
user_agent = None
try:
from google.cloud.firestore_v1 import FieldFilter
from google.cloud import firestore as fs
sessions = (
user_service.db.collection("sessions")
.where(filter=FieldFilter("user_email", "==", email))
.order_by("created_at", direction=fs.Query.DESCENDING)
.limit(1)
.stream()
)
for session_doc in sessions:
user_agent = session_doc.to_dict().get("user_agent")
except Exception:
pass
return {
"user_data": user_data,
"fingerprint_matches": fingerprint_matches,
"ip_matches": ip_matches,
"ip_geo": ip_geo,
"recent_signups_ip": recent_signups_ip,
"recent_signups_fp": recent_signups_fp,
"user_agent": user_agent,
}
def _call_gemini(self, prompt: str) -> str:
"""Call Gemini and return the response text."""
from google import genai
client = genai.Client()
response = client.models.generate_content(
model=self.settings.credit_eval_model,
contents=prompt,
config=genai.types.GenerateContentConfig(
system_instruction=SYSTEM_PROMPT,
),
)
return response.text
def _log_evaluation(
self,
email: str,
grant_type: str,
evaluation: CreditEvaluation,
signals: dict,
):
"""Log the evaluation decision to Firestore for audit trail."""
try:
from google.cloud import firestore as fs
db = fs.Client(project=self.settings.google_cloud_project)
doc_id = str(uuid.uuid4())
db.collection(CREDIT_EVALUATIONS_COLLECTION).document(doc_id).set({
"id": doc_id,
"email": email,
"grant_type": grant_type,
"decision": evaluation.decision,
"reasoning": evaluation.reasoning,
"confidence": evaluation.confidence,
"error": evaluation.error,
"model": self.settings.credit_eval_model,
"signals_snapshot": {
"fingerprint_match_count": len(signals.get("fingerprint_matches", [])),
"ip_match_count": len(signals.get("ip_matches", [])),
"recent_signups_ip": signals.get("recent_signups_ip", 0),
"recent_signups_fp": signals.get("recent_signups_fp", 0),
"user_ip": signals.get("user_data", {}).get("signup_ip"),
"user_fingerprint": signals.get("user_data", {}).get("device_fingerprint"),
},
"evaluated_at": datetime.now(timezone.utc).isoformat(),
})
except Exception:
logger.exception(f"Failed to log credit evaluation for {email}")
def evaluate(
self,
email: str,
grant_type: str,
feedback_content: Optional[dict] = None,
) -> CreditEvaluation:
"""
Evaluate whether to grant free credits.
Args:
email: User's email
grant_type: "welcome" or "feedback"
feedback_content: Feedback form data (for feedback grants only)
Returns:
CreditEvaluation with decision, reasoning, confidence.
Fail-closed: returns "pending_review" on any error (admin notified).
"""
if not self.settings.credit_eval_enabled:
return CreditEvaluation(
decision="grant",
reasoning="Credit evaluation disabled — auto-granting",
confidence=1.0,
)
try:
# Collect signals
signals = self._collect_signals(email)
# Quick-grant: if no correlations found at all, skip AI call
if (
not signals["fingerprint_matches"]
and not signals["ip_matches"]
and signals["recent_signups_ip"] <= 1
and signals["recent_signups_fp"] <= 1
):
evaluation = CreditEvaluation(
decision="grant",
reasoning="No suspicious correlations found — clean user",
confidence=1.0,
)
self._log_evaluation(email, grant_type, evaluation, signals)
return evaluation
# Build prompt and call Gemini
prompt = _build_user_prompt(
email=email,
grant_type=grant_type,
user_data=signals["user_data"],
fingerprint_matches=signals["fingerprint_matches"],
ip_matches=signals["ip_matches"],
ip_geo=signals["ip_geo"],
recent_signups_ip=signals["recent_signups_ip"],
recent_signups_fp=signals["recent_signups_fp"],
user_agent=signals["user_agent"],
feedback_content=feedback_content,
)
response_text = self._call_gemini(prompt)
evaluation = _parse_gemini_response(response_text)
self._log_evaluation(email, grant_type, evaluation, signals)
logger.info(
f"Credit evaluation for {email} ({grant_type}): "
f"{evaluation.decision} (confidence={evaluation.confidence:.2f})"
)
return evaluation
except Exception as e:
logger.exception(f"Credit evaluation failed for {email} — pending manual review (fail-closed)")
evaluation = CreditEvaluation(
decision="pending_review",
reasoning="Evaluation failed — pending manual review",
confidence=0.0,
error=str(e),
)
try:
self._log_evaluation(email, grant_type, evaluation, {})
except Exception:
pass
return evaluation
_service_instance: Optional[CreditEvaluationService] = None
def get_credit_evaluation_service() -> CreditEvaluationService:
"""Get or create the singleton credit evaluation service."""
global _service_instance
if _service_instance is None:
_service_instance = CreditEvaluationService()
return _service_instance
+241
View File
@@ -1416,6 +1416,247 @@ Open Job: {app_url}
)
def send_feedback_notification(
self,
user_email: str,
overall_rating: int,
ease_of_use_rating: int,
lyrics_accuracy_rating: int,
correction_experience_rating: int,
what_went_well: Optional[str] = None,
what_could_improve: Optional[str] = None,
additional_comments: Optional[str] = None,
would_recommend: bool = True,
would_use_again: bool = True,
) -> bool:
"""
Send admin notification when a user submits product feedback.
Args:
user_email: Email of the user who submitted feedback
overall_rating: 1-5 star rating
ease_of_use_rating: 1-5 star rating
lyrics_accuracy_rating: 1-5 star rating
correction_experience_rating: 1-5 star rating
what_went_well: Optional text feedback
what_could_improve: Optional text feedback
additional_comments: Optional text feedback
would_recommend: Whether user would recommend
would_use_again: Whether user would use again
Returns:
True if email was sent successfully
"""
admin_email = os.getenv("ADMIN_NOTIFICATION_EMAIL", "admin@nomadkaraoke.com")
subject = f"New Feedback from {user_email} — {overall_rating}/5 overall"
def stars(rating: int) -> str:
return "★" * rating + "☆" * (5 - rating)
def text_block(label: str, value: Optional[str]) -> str:
if not value:
return ""
escaped = html.escape(value).replace("\n", "<br>")
return f"""
<tr>
<td style="padding: 8px 12px; font-weight: bold; vertical-align: top; white-space: nowrap;">{label}</td>
<td style="padding: 8px 12px;">{escaped}</td>
</tr>"""
recommend_badge = "Yes ✓" if would_recommend else "No ✗"
use_again_badge = "Yes ✓" if would_use_again else "No ✗"
admin_url = f"{self.frontend_url}/admin/feedback"
extra_styles = """
.feedback-table {
width: 100%;
border-collapse: collapse;
margin: 16px 0;
}
.feedback-table td {
border-bottom: 1px solid #e5e7eb;
}
.stars {
color: #eab308;
font-size: 18px;
letter-spacing: 2px;
}
"""
content = f"""
<p>New product feedback submitted by <strong>{html.escape(user_email)}</strong>:</p>
<table class="feedback-table">
<tr>
<td style="padding: 8px 12px; font-weight: bold;">Overall</td>
<td style="padding: 8px 12px;"><span class="stars">{stars(overall_rating)}</span> ({overall_rating}/5)</td>
</tr>
<tr>
<td style="padding: 8px 12px; font-weight: bold;">Ease of Use</td>
<td style="padding: 8px 12px;"><span class="stars">{stars(ease_of_use_rating)}</span> ({ease_of_use_rating}/5)</td>
</tr>
<tr>
<td style="padding: 8px 12px; font-weight: bold;">Lyrics Accuracy</td>
<td style="padding: 8px 12px;"><span class="stars">{stars(lyrics_accuracy_rating)}</span> ({lyrics_accuracy_rating}/5)</td>
</tr>
<tr>
<td style="padding: 8px 12px; font-weight: bold;">Correction Experience</td>
<td style="padding: 8px 12px;"><span class="stars">{stars(correction_experience_rating)}</span> ({correction_experience_rating}/5)</td>
</tr>
<tr>
<td style="padding: 8px 12px; font-weight: bold;">Would Recommend</td>
<td style="padding: 8px 12px;">{recommend_badge}</td>
</tr>
<tr>
<td style="padding: 8px 12px; font-weight: bold;">Would Use Again</td>
<td style="padding: 8px 12px;">{use_again_badge}</td>
</tr>
{text_block("What went well", what_went_well)}
{text_block("What could improve", what_could_improve)}
{text_block("Additional comments", additional_comments)}
</table>
<p style="text-align: center;">
<a href="{admin_url}" class="button">View All Feedback</a>
</p>
"""
text_content = f"""New Feedback from {user_email}
Overall: {overall_rating}/5
Ease of Use: {ease_of_use_rating}/5
Lyrics Accuracy: {lyrics_accuracy_rating}/5
Correction Experience: {correction_experience_rating}/5
Would Recommend: {recommend_badge}
Would Use Again: {use_again_badge}
What went well: {what_went_well or '(empty)'}
What could improve: {what_could_improve or '(empty)'}
Additional comments: {additional_comments or '(empty)'}
View all feedback: {admin_url}
"""
html_content = self._build_email_html(content, extra_styles)
return self.provider.send_email(
to_email=admin_email,
subject=subject,
html_content=html_content,
text_content=text_content,
)
def send_credit_review_needed_email(self, user_email: str, grant_type: str, reason: str) -> bool:
"""
Notify Andrew that a credit grant needs manual review.
Sent when AI evaluation fails, is uncertain, or encounters an error.
Includes a direct link to the user's admin page for quick action.
"""
admin_user_url = f"{self.frontend_url}/admin/users/detail?email={user_email}"
subject = f"Credit review needed: {user_email} ({grant_type})"
content = f"""
<p>A {grant_type} credit grant for <strong>{user_email}</strong> needs your review.</p>
<p><strong>Reason:</strong> {reason}</p>
<p>The user has been told that their signup is being reviewed and credits will be
assigned shortly if everything checks out.</p>
<p style="text-align: center;">
<a href="{admin_user_url}" class="button">Review User</a>
</p>
<p style="color: #999; font-size: 14px;">
If the user looks legitimate, grant them credits from their admin page.
If not, no action needed — they already have 0 credits.
</p>
"""
text_content = f"""Credit review needed: {user_email} ({grant_type})
Reason: {reason}
Review user: {admin_user_url}
If the user looks legitimate, grant them credits from their admin page.
"""
html_content = self._build_email_html(content)
return self.provider.send_email(
to_email="andrew@beveridge.uk",
subject=subject,
html_content=html_content,
text_content=text_content,
)
def send_credit_denied_email(self, email: str, grant_type: str = "welcome") -> bool:
"""
Send a friendly-but-firm email when free credits are denied due to abuse signals.
CC'd to andrew@beveridge.uk so he can intervene if it's a false positive.
The tone invites the user to reply if it's a mistake.
"""
subject = "About your Nomad Karaoke free credits"
credit_type = "welcome credits" if grant_type == "welcome" else "feedback bonus credits"
content = f"""
<p>Hi there,</p>
<p>Thanks for signing up for Nomad Karaoke!</p>
<p>Unfortunately, we weren't able to grant your free {credit_type} this time. Our system detected
patterns that suggest this may not be your first account with us, and each karaoke generation job
costs us real money in cloud computing and API fees.</p>
<p>We totally understand if this is a mistake! If you're a genuine new user, please just
<strong>reply to this email</strong> and let Andrew (the founder) know. He built this service and is
happy to grant you some free credits to try it out — he just asks that you provide honest feedback
on the experience in return.</p>
<p>If you'd like to get started right away, you can also purchase credits:</p>
<p style="text-align: center;">
<a href="{self.buy_url}" class="button">Buy Credits</a>
</p>
<p style="color: #999; font-size: 14px;">We keep costs low so we can offer the service affordably,
which means we need to be careful about free credit abuse. Thanks for understanding!</p>
{self._get_email_signature()}
"""
text_content = f"""Hi there,
Thanks for signing up for Nomad Karaoke!
Unfortunately, we weren't able to grant your free {credit_type} this time. Our system detected patterns that suggest this may not be your first account with us, and each karaoke generation job costs us real money in cloud computing and API fees.
We totally understand if this is a mistake! If you're a genuine new user, please just reply to this email and let Andrew (the founder) know. He built this service and is happy to grant you some free credits to try it out - he just asks that you provide honest feedback on the experience in return.
If you'd like to get started right away, you can also purchase credits:
{self.buy_url}
---
© {self._get_year()} Nomad Karaoke
"""
html_content = self._build_email_html(content)
return self.provider.send_email(
to_email=email,
subject=subject,
html_content=html_content,
text_content=text_content,
cc_emails=["andrew@beveridge.uk"],
)
# Global instance
_email_service = None
+228
View File
@@ -0,0 +1,228 @@
"""
IP geolocation service with Firestore caching.
Looks up IP addresses via ip-api.com (free, no key needed) and caches
results in Firestore to avoid repeated lookups. Used by admin UI to
enrich IP displays with country, city, ISP, and ASN info.
"""
import ipaddress
import logging
import time
from datetime import datetime, timedelta
from typing import Optional, Dict, List
import httpx
from google.cloud import firestore
from backend.config import get_settings
logger = logging.getLogger(__name__)
IP_GEOLOCATION_COLLECTION = "ip_geolocation"
CACHE_TTL_DAYS = 90 # Cache results for 90 days
IP_API_URL = "http://ip-api.com/json"
IP_API_BATCH_URL = "http://ip-api.com/batch"
IP_API_FIELDS = "status,country,countryCode,regionName,city,isp,org,as,timezone,query"
RATE_LIMIT_PER_MINUTE = 45
def _is_private_ip(ip: str) -> bool:
"""Check if an IP is private/reserved (not routable on the internet)."""
try:
addr = ipaddress.ip_address(ip)
return addr.is_private or addr.is_reserved or addr.is_loopback or addr.is_link_local
except ValueError:
return True # Invalid IP
def _parse_ip_api_response(data: dict) -> dict:
"""Parse ip-api.com response into our standard format."""
if data.get("status") != "success":
return {
"status": "fail",
"ip": data.get("query", ""),
"cached_at": datetime.utcnow().isoformat(),
}
# Parse AS field: "AS14615 Comporium Inc" -> number + name
as_field = data.get("as", "")
as_number = ""
as_name = ""
if as_field:
parts = as_field.split(" ", 1)
as_number = parts[0] if parts else ""
as_name = parts[1] if len(parts) > 1 else ""
return {
"status": "success",
"ip": data.get("query", ""),
"country": data.get("country", ""),
"country_code": data.get("countryCode", ""),
"region": data.get("regionName", ""),
"city": data.get("city", ""),
"isp": data.get("isp", ""),
"org": data.get("org", ""),
"as_number": as_number,
"as_name": as_name,
"timezone": data.get("timezone", ""),
"cached_at": datetime.utcnow().isoformat(),
}
class IpGeolocationService:
"""IP geolocation lookup with Firestore caching."""
def __init__(self):
settings = get_settings()
self.db = firestore.Client(project=settings.google_cloud_project)
self._last_request_times: List[float] = []
def _check_rate_limit(self):
"""Simple rate limiter — sleep if approaching 45 req/min."""
now = time.time()
# Remove entries older than 60 seconds
self._last_request_times = [
t for t in self._last_request_times if now - t < 60
]
if len(self._last_request_times) >= RATE_LIMIT_PER_MINUTE - 5:
# Getting close to limit, wait
sleep_time = 60 - (now - self._last_request_times[0])
if sleep_time > 0:
logger.info(f"IP geolocation rate limit: sleeping {sleep_time:.1f}s")
time.sleep(sleep_time)
self._last_request_times.append(time.time())
def _get_cached(self, ip: str) -> Optional[dict]:
"""Get cached geolocation data for an IP."""
try:
# Firestore doc IDs can't contain '/' so IPv6 with :: is fine,
# but we need to sanitize for doc ID
doc_id = ip.replace("/", "_")
doc = self.db.collection(IP_GEOLOCATION_COLLECTION).document(doc_id).get()
if not doc.exists:
return None
data = doc.to_dict()
# Check TTL
cached_at = data.get("cached_at", "")
if cached_at:
try:
cached_dt = datetime.fromisoformat(cached_at)
if datetime.utcnow() - cached_dt > timedelta(days=CACHE_TTL_DAYS):
return None # Expired
except (ValueError, TypeError):
pass
return data
except Exception:
logger.exception(f"Error reading IP geo cache for {ip}")
return None
def _cache_result(self, ip: str, data: dict):
"""Store geolocation result in Firestore cache."""
try:
doc_id = ip.replace("/", "_")
self.db.collection(IP_GEOLOCATION_COLLECTION).document(doc_id).set(data)
except Exception:
logger.exception(f"Error caching IP geo for {ip}")
def lookup_ip(self, ip: str) -> dict:
"""
Look up geolocation for a single IP address.
Returns cached result if available, otherwise queries ip-api.com.
"""
if not ip or _is_private_ip(ip):
return {"status": "private", "ip": ip or ""}
# Check cache
cached = self._get_cached(ip)
if cached:
return cached
# Query ip-api.com
try:
self._check_rate_limit()
with httpx.Client(timeout=10) as client:
response = client.get(
f"{IP_API_URL}/{ip}",
params={"fields": IP_API_FIELDS},
)
response.raise_for_status()
data = response.json()
result = _parse_ip_api_response(data)
self._cache_result(ip, result)
return result
except Exception:
logger.exception(f"Error looking up IP {ip}")
return {"status": "error", "ip": ip}
def lookup_ips_batch(self, ips: List[str]) -> Dict[str, dict]:
"""
Look up geolocation for multiple IPs.
Returns dict of ip -> geo data. Uses cache for known IPs,
batches uncached lookups to ip-api.com.
"""
results = {}
uncached = []
for ip in set(ips): # Deduplicate
if not ip or _is_private_ip(ip):
results[ip] = {"status": "private", "ip": ip or ""}
continue
cached = self._get_cached(ip)
if cached:
results[ip] = cached
else:
uncached.append(ip)
if not uncached:
return results
# ip-api.com batch endpoint accepts up to 100 IPs per request
for i in range(0, len(uncached), 100):
batch = uncached[i:i + 100]
try:
self._check_rate_limit()
# Batch endpoint takes a JSON array of IPs
payload = [
{"query": ip, "fields": IP_API_FIELDS}
for ip in batch
]
with httpx.Client(timeout=15) as client:
response = client.post(IP_API_BATCH_URL, json=payload)
response.raise_for_status()
batch_results = response.json()
for data in batch_results:
result = _parse_ip_api_response(data)
ip = result.get("ip", data.get("query", ""))
if ip:
results[ip] = result
self._cache_result(ip, result)
except Exception:
logger.exception(f"Error in batch IP lookup ({len(batch)} IPs)")
# Mark failed IPs
for ip in batch:
if ip not in results:
results[ip] = {"status": "error", "ip": ip}
return results
# Global instance
_service = None
def get_ip_geolocation_service() -> IpGeolocationService:
"""Get the global IP geolocation service instance."""
global _service
if _service is None:
_service = IpGeolocationService()
return _service
+22 -27
View File
@@ -931,22 +931,22 @@ class JobManager:
def check_parallel_processing_complete(self, job_id: str) -> bool:
"""
Check if both parallel tracks (audio + lyrics) are complete.
This is called after audio_complete or lyrics_complete to determine
if we can proceed to screen generation.
Check if lyrics processing is complete (sufficient for screen generation).
Audio separation is decoupled from the critical path — users can start
reviewing lyrics while separation continues in the background. The
instrumental review page handles the case where separation isn't done yet.
Returns:
True if both tracks complete, False otherwise
True if lyrics are complete, False otherwise
"""
job = self.get_job(job_id)
if not job:
return False
audio_complete = job.state_data.get('audio_complete', False)
lyrics_complete = job.state_data.get('lyrics_complete', False)
return audio_complete and lyrics_complete
return lyrics_complete
async def start_job_processing(
self,
@@ -1022,30 +1022,25 @@ class JobManager:
def mark_audio_complete(self, job_id: str) -> None:
"""
Mark audio processing as complete and check if can proceed.
If lyrics are also complete, automatically triggers screens worker.
Mark audio processing as complete.
Audio completion is decoupled from the lyrics review path — it no longer
triggers screens. The instrumental review page polls for this flag.
"""
self.update_state_data(job_id, 'audio_complete', True)
if self.check_parallel_processing_complete(job_id):
logger.info(f"Job {job_id}: Both audio and lyrics complete, triggering screens worker")
# Transition happens in screens worker
# We just trigger it here
self._trigger_screens_worker(job_id)
logger.info(f"Job {job_id}: Audio processing complete (separation finished)")
def mark_lyrics_complete(self, job_id: str) -> None:
"""
Mark lyrics processing as complete and check if can proceed.
If audio is also complete, automatically triggers screens worker.
Mark lyrics processing as complete and trigger screens if ready.
Lyrics completion is the sole gate for screen generation and review.
Audio separation runs independently in the background.
"""
self.update_state_data(job_id, 'lyrics_complete', True)
if self.check_parallel_processing_complete(job_id):
logger.info(f"Job {job_id}: Both audio and lyrics complete, triggering screens worker")
# Transition happens in screens worker
# We just trigger it here
logger.info(f"Job {job_id}: Lyrics complete, triggering screens worker")
self._trigger_screens_worker(job_id)
def _trigger_screens_worker(self, job_id: str) -> None:
+143 -9
View File
@@ -48,7 +48,7 @@ class UserService:
"""Service for user management and authentication."""
# Number of free credits granted to new users
NEW_USER_FREE_CREDITS = 2
NEW_USER_FREE_CREDITS = 1
def __init__(self):
"""Initialize user service with Firestore client."""
@@ -370,31 +370,76 @@ class UserService:
logger.exception("Error verifying magic link")
return False, None, "An error occurred during verification"
def grant_welcome_credits_if_eligible(self, email: str) -> bool:
def grant_welcome_credits_if_eligible(self, email: str) -> Tuple[bool, str]:
"""
Grant welcome credits on first magic link verification.
Uses AI evaluation to check for abuse before granting. Fail-open:
if evaluation fails, credits are granted anyway.
Uses a dedicated welcome_credits_granted flag as primary idempotency
check (survives credit_transactions list trimming). Falls back to
checking for welcome_credit transaction as secondary defense.
Returns:
True if credits were granted, False if already received or user not found.
Tuple of (credits_granted: bool, status: str).
status is one of: "granted", "denied", "already_granted", "not_found", "error"
"""
try:
email = email.lower()
user = self.get_user(email)
if not user:
return False
return False, "not_found"
# Primary check: dedicated flag (survives transaction list trimming)
if user.welcome_credits_granted:
return False
return False, "already_granted"
# Secondary check: look for existing welcome_credit transaction
for txn in user.credit_transactions:
if txn.reason == "welcome_credit":
return False # Already received
return False, "already_granted"
# AI evaluation: check for abuse signals before granting
try:
from backend.services.credit_evaluation_service import get_credit_evaluation_service
eval_service = get_credit_evaluation_service()
evaluation = eval_service.evaluate(email, "welcome")
if evaluation.decision == "deny":
# Mark as evaluated but not granted so we don't re-evaluate
self.update_user(email, welcome_credits_granted=True)
logger.info(
f"Denied welcome credits to {email}: {evaluation.reasoning}"
)
try:
from backend.services.email_service import get_email_service
get_email_service().send_credit_denied_email(email, "welcome")
except Exception:
logger.exception(f"Failed to send credit denied email to {email}")
return False, "denied"
if evaluation.decision == "pending_review":
# Don't mark welcome_credits_granted — allow retry after manual review
logger.info(
f"Welcome credits pending review for {email}: {evaluation.reasoning}"
)
try:
from backend.services.email_service import get_email_service
email_service = get_email_service()
email_service.send_credit_review_needed_email(email, "welcome", evaluation.reasoning)
except Exception:
logger.exception(f"Failed to send review needed email for {email}")
return False, "pending_review"
except Exception:
logger.exception(f"Credit evaluation failed for {email} — pending review (fail-closed)")
try:
from backend.services.email_service import get_email_service
email_service = get_email_service()
email_service.send_credit_review_needed_email(email, "welcome", f"Evaluation error: {email}")
except Exception:
pass
return False, "pending_review"
# Grant welcome credits
welcome_credit = self.NEW_USER_FREE_CREDITS
@@ -416,11 +461,11 @@ class UserService:
)
logger.info(f"Granted {welcome_credit} welcome credits to {email}")
return True
return True, "granted"
except Exception:
logger.exception(f"Error granting welcome credits to {email}")
return False
return False, "error"
# =========================================================================
# Anti-Abuse Rate Limiting
@@ -556,6 +601,8 @@ class UserService:
min_jobs: Minimum total_jobs_created to flag (default: 2)
max_spend: Maximum total_spent in cents to include (default: 0 = free only)
"""
from backend.utils.test_data import is_internal_or_test_email
try:
query = (
self.db.collection(USERS_COLLECTION)
@@ -566,7 +613,7 @@ class UserService:
users = []
for doc in query.stream():
user = User(**doc.to_dict())
if user.total_spent <= max_spend:
if user.total_spent <= max_spend and not is_internal_or_test_email(user.email):
users.append(user)
return users
except Exception:
@@ -602,6 +649,93 @@ class UserService:
"by_fingerprint": by_fingerprint,
}
def find_account_correlations(self) -> dict:
"""
Find clusters of accounts sharing the same fingerprint or signup IP.
Returns groups of 2+ accounts that share the same identifier,
sorted by group size (largest first). Excludes internal/test accounts.
"""
from collections import defaultdict
from backend.utils.test_data import is_internal_or_test_email
# Known bad IPs (load balancer, metadata, placeholder) that don't represent real client IPs
BAD_IPS = {"169.254.169.126", "unknown", ""}
try:
all_users = []
for doc in self.db.collection(USERS_COLLECTION).stream():
user = User(**doc.to_dict())
if not is_internal_or_test_email(user.email):
all_users.append(user)
# Group by fingerprint
fp_groups: dict[str, list[User]] = defaultdict(list)
for user in all_users:
if user.device_fingerprint:
fp_groups[user.device_fingerprint].append(user)
# Group by IP (exclude known bad IPs)
ip_groups: dict[str, list[User]] = defaultdict(list)
for user in all_users:
if user.signup_ip and user.signup_ip not in BAD_IPS:
ip_groups[user.signup_ip].append(user)
# Collect user agents from latest sessions for users in clusters
cluster_emails = set()
for fp, users in fp_groups.items():
if len(users) >= 2:
cluster_emails.update(u.email for u in users)
for ip, users in ip_groups.items():
if len(users) >= 2:
cluster_emails.update(u.email for u in users)
user_agents: dict[str, str] = {}
for email in cluster_emails:
try:
sessions = (
self.db.collection(SESSIONS_COLLECTION)
.where(filter=FieldFilter("user_email", "==", email))
.order_by("created_at", direction=firestore.Query.DESCENDING)
.limit(1)
.stream()
)
for session_doc in sessions:
session_data = session_doc.to_dict()
ua = session_data.get("user_agent")
if ua:
user_agents[email] = ua
except Exception:
pass # Skip if session lookup fails
# Build response - only clusters with 2+ users
fingerprint_clusters = []
for fp, users in fp_groups.items():
if len(users) >= 2:
fingerprint_clusters.append({
"fingerprint": fp,
"users": sorted(users, key=lambda u: u.created_at or "", reverse=True),
})
fingerprint_clusters.sort(key=lambda c: len(c["users"]), reverse=True)
ip_clusters = []
for ip, users in ip_groups.items():
if len(users) >= 2:
ip_clusters.append({
"ip": ip,
"users": sorted(users, key=lambda u: u.created_at or "", reverse=True),
})
ip_clusters.sort(key=lambda c: len(c["users"]), reverse=True)
return {
"fingerprint_clusters": fingerprint_clusters,
"ip_clusters": ip_clusters,
"user_agents": user_agents,
}
except Exception:
logger.exception("Error finding account correlations")
return {"fingerprint_clusters": [], "ip_clusters": [], "user_agents": {}}
# =========================================================================
# Session Management
# =========================================================================
+460
View File
@@ -0,0 +1,460 @@
"""
Unit tests for admin feedback endpoint and feedback email notification.
"""
import pytest
from unittest.mock import Mock, patch, MagicMock
from datetime import datetime
from backend.services.email_service import EmailService
class TestAdminFeedbackEndpoint:
"""Tests for GET /api/admin/feedback endpoint."""
def _make_feedback_doc(self, email="user@example.com", overall=4, **kwargs):
"""Create a mock Firestore feedback document."""
doc = Mock()
doc.id = kwargs.get("id", "test-id-1")
data = {
"id": doc.id,
"user_email": email,
"created_at": kwargs.get("created_at", datetime(2026, 3, 1, 12, 0, 0)),
"overall_rating": overall,
"ease_of_use_rating": kwargs.get("ease_of_use", 4),
"lyrics_accuracy_rating": kwargs.get("lyrics_accuracy", 3),
"correction_experience_rating": kwargs.get("correction_experience", 4),
"what_went_well": kwargs.get("what_went_well", "Great app"),
"what_could_improve": kwargs.get("what_could_improve", "More songs"),
"additional_comments": kwargs.get("additional_comments", None),
"would_recommend": kwargs.get("would_recommend", True),
"would_use_again": kwargs.get("would_use_again", True),
}
doc.to_dict.return_value = data
return doc
@patch("backend.api.routes.admin.get_user_service")
@patch("backend.api.routes.admin.is_test_email")
def test_list_feedback_returns_items(self, mock_is_test, mock_get_user_svc):
"""Test that feedback items are returned correctly."""
from backend.api.routes.admin import list_user_feedback
mock_db = Mock()
mock_user_svc = Mock()
mock_user_svc.db = mock_db
mock_get_user_svc.return_value = mock_user_svc
mock_is_test.return_value = False
doc1 = self._make_feedback_doc("alice@example.com", 5, id="id-1")
doc2 = self._make_feedback_doc("bob@example.com", 3, id="id-2")
mock_db.collection.return_value.stream.return_value = [doc1, doc2]
result = list_user_feedback(
limit=50, offset=0, search=None, exclude_test=False,
auth_result=("admin@test.com", "admin", 1),
)
assert result.total == 2
assert len(result.items) == 2
assert result.has_more is False
@patch("backend.api.routes.admin.get_user_service")
@patch("backend.api.routes.admin.is_test_email")
def test_list_feedback_search_filter(self, mock_is_test, mock_get_user_svc):
"""Test that search filters by email."""
from backend.api.routes.admin import list_user_feedback
mock_db = Mock()
mock_user_svc = Mock()
mock_user_svc.db = mock_db
mock_get_user_svc.return_value = mock_user_svc
mock_is_test.return_value = False
doc1 = self._make_feedback_doc("alice@example.com", 5, id="id-1")
doc2 = self._make_feedback_doc("bob@example.com", 3, id="id-2")
mock_db.collection.return_value.stream.return_value = [doc1, doc2]
result = list_user_feedback(
limit=50, offset=0, search="alice", exclude_test=False,
auth_result=("admin@test.com", "admin", 1),
)
assert result.total == 1
assert result.items[0].user_email == "alice@example.com"
@patch("backend.api.routes.admin.get_user_service")
@patch("backend.api.routes.admin.is_test_email")
def test_list_feedback_exclude_test(self, mock_is_test, mock_get_user_svc):
"""Test that test emails are excluded when exclude_test=True."""
from backend.api.routes.admin import list_user_feedback
mock_db = Mock()
mock_user_svc = Mock()
mock_user_svc.db = mock_db
mock_get_user_svc.return_value = mock_user_svc
doc1 = self._make_feedback_doc("alice@example.com", 5, id="id-1")
doc2 = self._make_feedback_doc("test@inbox.testmail.app", 3, id="id-2")
mock_db.collection.return_value.stream.return_value = [doc1, doc2]
# Make is_test_email return True for the test email
mock_is_test.side_effect = lambda e: "testmail" in e
result = list_user_feedback(
limit=50, offset=0, search=None, exclude_test=True,
auth_result=("admin@test.com", "admin", 1),
)
assert result.total == 1
assert result.items[0].user_email == "alice@example.com"
@patch("backend.api.routes.admin.get_user_service")
@patch("backend.api.routes.admin.is_test_email")
def test_list_feedback_pagination(self, mock_is_test, mock_get_user_svc):
"""Test pagination with offset and limit."""
from backend.api.routes.admin import list_user_feedback
mock_db = Mock()
mock_user_svc = Mock()
mock_user_svc.db = mock_db
mock_get_user_svc.return_value = mock_user_svc
mock_is_test.return_value = False
docs = [
self._make_feedback_doc(f"user{i}@example.com", 4, id=f"id-{i}")
for i in range(5)
]
mock_db.collection.return_value.stream.return_value = docs
result = list_user_feedback(
limit=2, offset=2, search=None, exclude_test=False,
auth_result=("admin@test.com", "admin", 1),
)
assert result.total == 5
assert len(result.items) == 2
assert result.has_more is True
assert result.offset == 2
assert result.limit == 2
@patch("backend.api.routes.admin.get_user_service")
@patch("backend.api.routes.admin.is_test_email")
def test_list_feedback_aggregate_stats(self, mock_is_test, mock_get_user_svc):
"""Test that aggregate rating averages are computed correctly."""
from backend.api.routes.admin import list_user_feedback
mock_db = Mock()
mock_user_svc = Mock()
mock_user_svc.db = mock_db
mock_get_user_svc.return_value = mock_user_svc
mock_is_test.return_value = False
doc1 = self._make_feedback_doc("a@x.com", 5, id="id-1", ease_of_use=4, lyrics_accuracy=3, correction_experience=2)
doc2 = self._make_feedback_doc("b@x.com", 3, id="id-2", ease_of_use=2, lyrics_accuracy=5, correction_experience=4)
mock_db.collection.return_value.stream.return_value = [doc1, doc2]
result = list_user_feedback(
limit=50, offset=0, search=None, exclude_test=False,
auth_result=("admin@test.com", "admin", 1),
)
assert result.avg_overall_rating == 4.0
assert result.avg_ease_of_use_rating == 3.0
assert result.avg_lyrics_accuracy_rating == 4.0
assert result.avg_correction_experience_rating == 3.0
@patch("backend.api.routes.admin.get_user_service")
@patch("backend.api.routes.admin.is_test_email")
def test_list_feedback_empty(self, mock_is_test, mock_get_user_svc):
"""Test empty results."""
from backend.api.routes.admin import list_user_feedback
mock_db = Mock()
mock_user_svc = Mock()
mock_user_svc.db = mock_db
mock_get_user_svc.return_value = mock_user_svc
mock_db.collection.return_value.stream.return_value = []
result = list_user_feedback(
limit=50, offset=0, search=None, exclude_test=False,
auth_result=("admin@test.com", "admin", 1),
)
assert result.total == 0
assert len(result.items) == 0
assert result.avg_overall_rating is None
@patch("backend.api.routes.admin.get_user_service")
@patch("backend.api.routes.admin.is_test_email")
def test_list_feedback_handles_string_created_at(self, mock_is_test, mock_get_user_svc):
"""Test that string timestamps (not datetime objects) are handled correctly."""
from backend.api.routes.admin import list_user_feedback
mock_db = Mock()
mock_user_svc = Mock()
mock_user_svc.db = mock_db
mock_get_user_svc.return_value = mock_user_svc
mock_is_test.return_value = False
doc = self._make_feedback_doc("a@x.com", 5, id="id-1", created_at="2026-03-01T12:00:00")
mock_db.collection.return_value.stream.return_value = [doc]
result = list_user_feedback(
limit=50, offset=0, search=None, exclude_test=False,
auth_result=("admin@test.com", "admin", 1),
)
assert result.items[0].created_at == "2026-03-01T12:00:00"
@patch("backend.api.routes.admin.get_user_service")
@patch("backend.api.routes.admin.is_test_email")
def test_list_feedback_handles_none_created_at(self, mock_is_test, mock_get_user_svc):
"""Test that None created_at is handled correctly."""
from backend.api.routes.admin import list_user_feedback
mock_db = Mock()
mock_user_svc = Mock()
mock_user_svc.db = mock_db
mock_get_user_svc.return_value = mock_user_svc
mock_is_test.return_value = False
doc = self._make_feedback_doc("a@x.com", 5, id="id-1", created_at=None)
mock_db.collection.return_value.stream.return_value = [doc]
result = list_user_feedback(
limit=50, offset=0, search=None, exclude_test=False,
auth_result=("admin@test.com", "admin", 1),
)
assert result.items[0].created_at is None
class TestSubmitFeedbackEmailIntegration:
"""Test that submit_user_feedback correctly calls send_feedback_notification."""
@patch("backend.services.email_service.get_email_service")
@patch("backend.services.auth_service.get_auth_service")
def test_submit_feedback_sends_admin_notification(self, mock_get_auth, mock_get_email):
"""Verify the caller (submit_user_feedback) passes correct args to email service."""
import asyncio
import uuid as uuid_mod
from backend.api.routes.users import submit_user_feedback
from backend.models.user import UserFeedbackRequest
# Mock auth
mock_auth_svc = Mock()
mock_auth_result = Mock()
mock_auth_result.is_valid = True
mock_auth_result.user_email = "alice@example.com"
mock_auth_svc.validate_token_full.return_value = mock_auth_result
mock_get_auth.return_value = mock_auth_svc
# Mock email service
mock_email_svc = Mock()
mock_email_svc.send_feedback_notification.return_value = True
mock_get_email.return_value = mock_email_svc
# Mock user service with a db that has a collection mock
mock_user_svc = Mock()
mock_user = Mock()
mock_user.email = "alice@example.com"
mock_user.total_jobs_completed = 5
mock_user.has_submitted_feedback = False
mock_user_svc.get_or_create_user.return_value = mock_user
mock_user_svc.update_user.return_value = None
mock_user_svc.add_credits.return_value = None
went_well = "The lyrics synchronization was incredibly accurate and impressive overall"
could_improve = "Speed could be faster for longer songs in the processing queue"
request = UserFeedbackRequest(
overall_rating=4,
ease_of_use_rating=3,
lyrics_accuracy_rating=5,
correction_experience_rating=2,
what_went_well=went_well,
what_could_improve=could_improve,
additional_comments=None,
would_recommend=True,
would_use_again=False,
)
with patch.object(uuid_mod, "uuid4", return_value="fake-uuid"):
result = asyncio.get_event_loop().run_until_complete(
submit_user_feedback(request, authorization="Bearer test-token", user_service=mock_user_svc)
)
# Verify email notification was called with matching args
mock_email_svc.send_feedback_notification.assert_called_once_with(
user_email="alice@example.com",
overall_rating=4,
ease_of_use_rating=3,
lyrics_accuracy_rating=5,
correction_experience_rating=2,
what_went_well=went_well,
what_could_improve=could_improve,
additional_comments=None,
would_recommend=True,
would_use_again=False,
)
assert result.credits_granted == 1
@patch("backend.services.email_service.get_email_service")
@patch("backend.services.auth_service.get_auth_service")
def test_submit_feedback_continues_on_email_failure(self, mock_get_auth, mock_get_email):
"""Verify feedback submission succeeds even if email notification fails."""
import asyncio
import uuid as uuid_mod
from backend.api.routes.users import submit_user_feedback
from backend.models.user import UserFeedbackRequest
mock_auth_svc = Mock()
mock_auth_result = Mock()
mock_auth_result.is_valid = True
mock_auth_result.user_email = "bob@example.com"
mock_auth_svc.validate_token_full.return_value = mock_auth_result
mock_get_auth.return_value = mock_auth_svc
# Email service throws an exception
mock_email_svc = Mock()
mock_email_svc.send_feedback_notification.side_effect = Exception("SendGrid down")
mock_get_email.return_value = mock_email_svc
mock_user_svc = Mock()
mock_user = Mock()
mock_user.email = "bob@example.com"
mock_user.total_jobs_completed = 3
mock_user.has_submitted_feedback = False
mock_user_svc.get_or_create_user.return_value = mock_user
request = UserFeedbackRequest(
overall_rating=5,
ease_of_use_rating=5,
lyrics_accuracy_rating=5,
correction_experience_rating=5,
what_went_well="Everything was perfect and I really enjoyed the experience a lot",
)
with patch.object(uuid_mod, "uuid4", return_value="fake-uuid"):
result = asyncio.get_event_loop().run_until_complete(
submit_user_feedback(request, authorization="Bearer test-token", user_service=mock_user_svc)
)
# User still gets credits even though email failed
assert result.status == "success"
assert result.credits_granted == 1
class TestFeedbackEmailNotification:
"""Tests for send_feedback_notification email method."""
@patch.object(EmailService, '_get_provider')
def test_send_feedback_notification_calls_provider(self, mock_get_provider):
"""Test that feedback notification sends email via provider."""
mock_provider = Mock()
mock_provider.send_email.return_value = True
mock_get_provider.return_value = mock_provider
service = EmailService()
result = service.send_feedback_notification(
user_email="alice@example.com",
overall_rating=5,
ease_of_use_rating=4,
lyrics_accuracy_rating=3,
correction_experience_rating=4,
what_went_well="Great lyrics sync",
what_could_improve="More song variety",
additional_comments=None,
would_recommend=True,
would_use_again=True,
)
assert result is True
mock_provider.send_email.assert_called_once()
call_args = mock_provider.send_email.call_args
# Check email is sent to admin
to_email = call_args.kwargs.get("to_email") or call_args[0][0]
assert to_email == "admin@nomadkaraoke.com"
# Check subject contains user email and rating
subject = call_args.kwargs.get("subject") or call_args[0][1]
assert "alice@example.com" in subject
assert "5/5" in subject
@patch.object(EmailService, '_get_provider')
def test_send_feedback_notification_content(self, mock_get_provider):
"""Test that feedback notification email contains all feedback fields."""
mock_provider = Mock()
mock_provider.send_email.return_value = True
mock_get_provider.return_value = mock_provider
service = EmailService()
service.send_feedback_notification(
user_email="bob@example.com",
overall_rating=3,
ease_of_use_rating=2,
lyrics_accuracy_rating=4,
correction_experience_rating=5,
what_went_well="Easy to use",
what_could_improve="Better mobile support",
additional_comments="Love it overall",
would_recommend=False,
would_use_again=True,
)
call_args = mock_provider.send_email.call_args
html_content = call_args.kwargs.get("html_content") or call_args[0][2]
text_content = call_args.kwargs.get("text_content") or call_args[0][3]
# Check HTML contains feedback text
assert "Easy to use" in html_content
assert "Better mobile support" in html_content
assert "Love it overall" in html_content
assert "bob@example.com" in html_content
# Check plain text also contains feedback
assert "Easy to use" in text_content
assert "Better mobile support" in text_content
assert "3/5" in text_content
@patch.object(EmailService, '_get_provider')
@patch.dict("os.environ", {"ADMIN_NOTIFICATION_EMAIL": "custom@admin.com"})
def test_send_feedback_notification_custom_admin_email(self, mock_get_provider):
"""Test that admin email can be configured via env var."""
mock_provider = Mock()
mock_provider.send_email.return_value = True
mock_get_provider.return_value = mock_provider
service = EmailService()
service.send_feedback_notification(
user_email="test@example.com",
overall_rating=4,
ease_of_use_rating=4,
lyrics_accuracy_rating=4,
correction_experience_rating=4,
)
call_args = mock_provider.send_email.call_args
to_email = call_args.kwargs.get("to_email") or call_args[0][0]
assert to_email == "custom@admin.com"
@patch.object(EmailService, '_get_provider')
def test_send_feedback_notification_returns_false_on_failure(self, mock_get_provider):
"""Test that failure is returned when provider fails."""
mock_provider = Mock()
mock_provider.send_email.return_value = False
mock_get_provider.return_value = mock_provider
service = EmailService()
result = service.send_feedback_notification(
user_email="test@example.com",
overall_rating=1,
ease_of_use_rating=1,
lyrics_accuracy_rating=1,
correction_experience_rating=1,
)
assert result is False
+18 -15
View File
@@ -118,13 +118,16 @@ class TestGrantWelcomeCredits:
from backend.services.user_service import UserService
service = UserService()
result = service.grant_welcome_credits_if_eligible("new@example.com")
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval:
from backend.services.credit_evaluation_service import CreditEvaluation
mock_eval.return_value.evaluate.return_value = CreditEvaluation(decision="grant", reasoning="OK", confidence=1.0)
granted, status = service.grant_welcome_credits_if_eligible("new@example.com")
assert result is True
assert granted is True
# Verify update was called with credits and flag
mock_db.collection.return_value.document.return_value.update.assert_called_once()
update_args = mock_db.collection.return_value.document.return_value.update.call_args[0][0]
assert update_args['credits'] == 2
assert update_args['credits'] == 1
assert update_args['welcome_credits_granted'] is True
@patch('backend.services.user_service.get_settings')
@@ -148,9 +151,9 @@ class TestGrantWelcomeCredits:
from backend.services.user_service import UserService
service = UserService()
result = service.grant_welcome_credits_if_eligible("existing@example.com")
granted, status = service.grant_welcome_credits_if_eligible("existing@example.com")
assert result is False
assert granted is False
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
@@ -180,9 +183,9 @@ class TestGrantWelcomeCredits:
from backend.services.user_service import UserService
service = UserService()
result = service.grant_welcome_credits_if_eligible("existing@example.com")
granted, status = service.grant_welcome_credits_if_eligible("existing@example.com")
assert result is False
assert granted is False
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
@@ -199,9 +202,9 @@ class TestGrantWelcomeCredits:
from backend.services.user_service import UserService
service = UserService()
result = service.grant_welcome_credits_if_eligible("ghost@example.com")
granted, status = service.grant_welcome_credits_if_eligible("ghost@example.com")
assert result is False
assert granted is False
# =============================================================================
@@ -376,7 +379,7 @@ def mock_user_svc():
email="test@example.com",
expires_at=datetime.utcnow() + timedelta(minutes=15),
)
svc.NEW_USER_FREE_CREDITS = 2
svc.NEW_USER_FREE_CREDITS = 1
return svc
@@ -524,10 +527,10 @@ class TestVerifyGrantsCredits:
from backend.services.email_service import get_email_service
mock_user_svc.verify_magic_link.return_value = (True, user, "Success")
mock_user_svc.grant_welcome_credits_if_eligible.return_value = credits_eligible
mock_user_svc.grant_welcome_credits_if_eligible.return_value = (credits_eligible, "granted" if credits_eligible else "already_granted")
mock_user_svc.get_user.return_value = user
mock_user_svc.create_session.return_value = MagicMock(token="session-token")
mock_user_svc.NEW_USER_FREE_CREDITS = 2
mock_user_svc.NEW_USER_FREE_CREDITS = 1
# Mock magic link doc for first-login check
mock_ml_doc = MagicMock()
@@ -556,7 +559,7 @@ class TestVerifyGrantsCredits:
assert response.status_code == 200
data = response.json()
assert data["credits_granted"] == 2
assert data["credits_granted"] == 1
mock_user_svc.grant_welcome_credits_if_eligible.assert_called_once()
finally:
from backend.main import app
@@ -652,8 +655,8 @@ class TestErrorPaths:
from backend.services.user_service import UserService
service = UserService()
result = service.grant_welcome_credits_if_eligible("test@example.com")
assert result is False
granted, status = service.grant_welcome_credits_if_eligible("test@example.com")
assert granted is False
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
+186 -1
View File
@@ -65,6 +65,40 @@ class TestJobCreationIp:
assert job.creation_ip is None
# =============================================================================
# Internal/Test Email Filtering
# =============================================================================
class TestInternalOrTestEmail:
"""Tests for is_internal_or_test_email utility."""
def test_nomadkaraoke_is_internal(self):
from backend.utils.test_data import is_internal_or_test_email
assert is_internal_or_test_email("admin@nomadkaraoke.com") is True
def test_beveridge_is_internal(self):
from backend.utils.test_data import is_internal_or_test_email
assert is_internal_or_test_email("vocalstar@beveridge.uk") is True
def test_testmail_is_test(self):
from backend.utils.test_data import is_internal_or_test_email
assert is_internal_or_test_email("test123@inbox.testmail.app") is True
def test_regular_email_is_not_internal(self):
from backend.utils.test_data import is_internal_or_test_email
assert is_internal_or_test_email("user@gmail.com") is False
def test_empty_email(self):
from backend.utils.test_data import is_internal_or_test_email
assert is_internal_or_test_email("") is False
def test_is_internal_email_only(self):
from backend.utils.test_data import is_internal_email
assert is_internal_email("andrew@beveridge.uk") is True
assert is_internal_email("user@gmail.com") is False
# =============================================================================
# UserService Investigation Methods
# =============================================================================
@@ -153,6 +187,33 @@ class TestFindSuspiciousAccounts:
assert len(results) == 1
assert results[0].email == "free@test.com"
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_excludes_internal_and_test_accounts(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
real_user = User(email="abuser@gmail.com", total_jobs_created=5, total_spent=0).model_dump(mode='json')
internal_user = User(email="admin@nomadkaraoke.com", total_jobs_created=10, total_spent=0).model_dump(mode='json')
test_user = User(email="e2e@inbox.testmail.app", total_jobs_created=8, total_spent=0).model_dump(mode='json')
personal_user = User(email="vocalstar@beveridge.uk", total_jobs_created=3, total_spent=0).model_dump(mode='json')
docs = []
for data in [real_user, internal_user, test_user, personal_user]:
doc = MagicMock()
doc.to_dict.return_value = data
docs.append(doc)
mock_db.collection.return_value.where.return_value.order_by.return_value.limit.return_value.stream.return_value = docs
from backend.services.user_service import UserService
service = UserService()
results = service.find_suspicious_accounts(min_jobs=2, max_spend=0)
assert len(results) == 1
assert results[0].email == "abuser@gmail.com"
class TestFindRelatedAccounts:
@@ -215,7 +276,7 @@ class TestFindRelatedAccounts:
@pytest.fixture
def mock_user_svc():
svc = MagicMock()
svc.NEW_USER_FREE_CREDITS = 2
svc.NEW_USER_FREE_CREDITS = 1
return svc
@@ -293,3 +354,127 @@ class TestAdminAbuseEndpoints:
response = admin_client.get("/api/admin/abuse/related/ghost@test.com")
assert response.status_code == 404
def test_correlations_endpoint(self, admin_client, mock_user_svc):
user_a = User(email="a@test.com", signup_ip="1.2.3.4", device_fingerprint="fp123", total_jobs_created=2)
user_b = User(email="b@test.com", signup_ip="1.2.3.4", device_fingerprint="fp123", total_jobs_created=3)
mock_user_svc.find_account_correlations.return_value = {
"fingerprint_clusters": [
{"fingerprint": "fp123", "users": [user_a, user_b]},
],
"ip_clusters": [
{"ip": "1.2.3.4", "users": [user_a, user_b]},
],
"user_agents": {"a@test.com": "Mozilla/5.0", "b@test.com": "Mozilla/5.0"},
}
response = admin_client.get("/api/admin/abuse/correlations")
assert response.status_code == 200
data = response.json()
assert len(data["fingerprint_clusters"]) == 1
assert data["fingerprint_clusters"][0]["fingerprint"] == "fp123"
assert data["fingerprint_clusters"][0]["count"] == 2
assert data["fingerprint_clusters"][0]["users"][0]["user_agent"] == "Mozilla/5.0"
assert len(data["ip_clusters"]) == 1
assert data["ip_clusters"][0]["ip"] == "1.2.3.4"
assert data["ip_clusters"][0]["count"] == 2
def test_correlations_endpoint_empty(self, admin_client, mock_user_svc):
mock_user_svc.find_account_correlations.return_value = {
"fingerprint_clusters": [],
"ip_clusters": [],
"user_agents": {},
}
response = admin_client.get("/api/admin/abuse/correlations")
assert response.status_code == 200
data = response.json()
assert data["fingerprint_clusters"] == []
assert data["ip_clusters"] == []
# =============================================================================
# Correlations Service Method Tests
# =============================================================================
class TestFindAccountCorrelations:
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_groups_by_fingerprint_and_ip(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
user_a = User(email="a@gmail.com", signup_ip="1.2.3.4", device_fingerprint="fp123", total_jobs_created=2).model_dump(mode='json')
user_b = User(email="b@gmail.com", signup_ip="1.2.3.4", device_fingerprint="fp123", total_jobs_created=3).model_dump(mode='json')
user_c = User(email="c@gmail.com", signup_ip="5.6.7.8", device_fingerprint="fp999", total_jobs_created=1).model_dump(mode='json')
docs = []
for data in [user_a, user_b, user_c]:
doc = MagicMock()
doc.to_dict.return_value = data
docs.append(doc)
# Mock the users collection stream
mock_db.collection.return_value.stream.return_value = docs
# Mock session lookups (return empty for simplicity)
mock_db.collection.return_value.where.return_value.order_by.return_value.limit.return_value.stream.return_value = []
from backend.services.user_service import UserService
service = UserService()
result = service.find_account_correlations()
# a and b share fp123 → 1 fingerprint cluster
assert len(result["fingerprint_clusters"]) == 1
assert result["fingerprint_clusters"][0]["fingerprint"] == "fp123"
assert len(result["fingerprint_clusters"][0]["users"]) == 2
# a and b share IP 1.2.3.4 → 1 IP cluster
assert len(result["ip_clusters"]) == 1
assert result["ip_clusters"][0]["ip"] == "1.2.3.4"
assert len(result["ip_clusters"][0]["users"]) == 2
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_excludes_internal_accounts(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
real_user = User(email="user@gmail.com", signup_ip="1.2.3.4", device_fingerprint="fp123").model_dump(mode='json')
internal_user = User(email="admin@nomadkaraoke.com", signup_ip="1.2.3.4", device_fingerprint="fp123").model_dump(mode='json')
docs = []
for data in [real_user, internal_user]:
doc = MagicMock()
doc.to_dict.return_value = data
docs.append(doc)
mock_db.collection.return_value.stream.return_value = docs
from backend.services.user_service import UserService
service = UserService()
result = service.find_account_correlations()
# Only 1 non-internal user with fp123, so no cluster (need 2+)
assert len(result["fingerprint_clusters"]) == 0
assert len(result["ip_clusters"]) == 0
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_returns_empty_on_error(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
mock_db.collection.return_value.stream.side_effect = Exception("Firestore down")
from backend.services.user_service import UserService
service = UserService()
result = service.find_account_correlations()
assert result["fingerprint_clusters"] == []
assert result["ip_clusters"] == []
+3 -3
View File
@@ -405,10 +405,10 @@ class TestCreditRefundOnJobDeletion:
class TestWelcomeCredits:
"""Test new user welcome credits."""
def test_new_user_gets_2_welcome_credits(self):
"""Verify NEW_USER_FREE_CREDITS is set to 2."""
def test_new_user_gets_1_welcome_credit(self):
"""Verify NEW_USER_FREE_CREDITS is set to 1."""
from backend.services.user_service import UserService
assert UserService.NEW_USER_FREE_CREDITS == 2
assert UserService.NEW_USER_FREE_CREDITS == 1
class TestInsufficientCreditsError:
+346
View File
@@ -0,0 +1,346 @@
"""
Tests for AI-powered credit evaluation service.
"""
import pytest
from unittest.mock import MagicMock, patch, PropertyMock
import sys
sys.modules.setdefault('google.cloud.firestore', MagicMock())
sys.modules.setdefault('google.cloud.firestore_v1', MagicMock())
from backend.models.user import User
# =============================================================================
# Prompt Building Tests
# =============================================================================
class TestBuildUserPrompt:
def test_builds_prompt_with_all_signals(self):
from backend.services.credit_evaluation_service import _build_user_prompt
prompt = _build_user_prompt(
email="test@example.com",
grant_type="welcome",
user_data={
"device_fingerprint": "fp123",
"signup_ip": "1.2.3.4",
"credits": 0,
"total_jobs_created": 0,
"total_jobs_completed": 0,
"total_spent": 0,
"created_at": "2026-03-23",
},
fingerprint_matches=[
{"email": "other@test.com", "total_jobs_created": 5, "total_spent": 0, "created_at": "2026-03-20"},
],
ip_matches=[],
ip_geo={"status": "success", "country": "US", "country_code": "US", "city": "Portland", "region": "OR", "isp": "Comcast", "org": "Comcast", "as_number": "AS7922", "as_name": "Comcast"},
recent_signups_ip=1,
recent_signups_fp=2,
user_agent="Mozilla/5.0",
)
assert "test@example.com" in prompt
assert "fp123" in prompt
assert "1.2.3.4" in prompt
assert "other@test.com" in prompt
assert "RED FLAG" in prompt
assert "Portland" in prompt
assert "Comcast" in prompt
assert "Mozilla/5.0" in prompt
def test_builds_prompt_without_correlations(self):
from backend.services.credit_evaluation_service import _build_user_prompt
prompt = _build_user_prompt(
email="clean@user.com",
grant_type="welcome",
user_data={"device_fingerprint": "fp999", "signup_ip": "5.6.7.8"},
fingerprint_matches=[],
ip_matches=[],
ip_geo=None,
recent_signups_ip=1,
recent_signups_fp=1,
user_agent=None,
)
assert "None found" in prompt
assert "clean@user.com" in prompt
def test_includes_feedback_content(self):
from backend.services.credit_evaluation_service import _build_user_prompt
prompt = _build_user_prompt(
email="test@example.com",
grant_type="feedback",
user_data={},
fingerprint_matches=[],
ip_matches=[],
ip_geo=None,
recent_signups_ip=0,
recent_signups_fp=0,
user_agent=None,
feedback_content={
"overall_rating": 5,
"what_went_well": "Great audio quality!",
"what_could_improve": "Faster processing",
"additional_comments": "Love it",
},
)
assert "Feedback Submitted" in prompt
assert "Great audio quality!" in prompt
assert "5" in prompt
# =============================================================================
# Response Parsing Tests
# =============================================================================
class TestParseGeminiResponse:
def test_parses_grant_decision(self):
from backend.services.credit_evaluation_service import _parse_gemini_response
result = _parse_gemini_response('{"decision": "grant", "reasoning": "Clean user", "confidence": 0.95}')
assert result.decision == "grant"
assert result.reasoning == "Clean user"
assert result.confidence == 0.95
assert result.error is None
def test_parses_deny_decision(self):
from backend.services.credit_evaluation_service import _parse_gemini_response
result = _parse_gemini_response('{"decision": "deny", "reasoning": "Same fingerprint as 3 other accounts", "confidence": 0.9}')
assert result.decision == "deny"
assert "fingerprint" in result.reasoning
def test_handles_markdown_code_fences(self):
from backend.services.credit_evaluation_service import _parse_gemini_response
result = _parse_gemini_response('```json\n{"decision": "grant", "reasoning": "OK", "confidence": 0.8}\n```')
assert result.decision == "grant"
def test_fails_closed_on_invalid_json(self):
from backend.services.credit_evaluation_service import _parse_gemini_response
result = _parse_gemini_response("I think this user is fine")
assert result.decision == "pending_review"
assert result.error is not None
def test_fails_closed_on_unexpected_decision(self):
from backend.services.credit_evaluation_service import _parse_gemini_response
result = _parse_gemini_response('{"decision": "maybe", "reasoning": "Unsure", "confidence": 0.5}')
assert result.decision == "pending_review" # fail-closed
def test_fails_closed_on_empty_response(self):
from backend.services.credit_evaluation_service import _parse_gemini_response
result = _parse_gemini_response("")
assert result.decision == "pending_review"
assert result.error is not None
# =============================================================================
# Evaluation Service Tests
# =============================================================================
class TestCreditEvaluationService:
@patch('backend.services.credit_evaluation_service.get_settings')
def test_returns_grant_when_disabled(self, mock_settings):
mock_settings.return_value = MagicMock(credit_eval_enabled=False)
from backend.services.credit_evaluation_service import CreditEvaluationService
service = CreditEvaluationService()
result = service.evaluate("test@example.com", "welcome")
assert result.decision == "grant"
assert "disabled" in result.reasoning
@patch('backend.services.credit_evaluation_service.get_settings')
def test_quick_grants_clean_users(self, mock_settings):
mock_settings.return_value = MagicMock(
credit_eval_enabled=True,
credit_eval_model="gemini-3.1-pro-preview",
google_cloud_project="test",
)
from backend.services.credit_evaluation_service import CreditEvaluationService
service = CreditEvaluationService()
with patch.object(service, '_collect_signals', return_value={
"user_data": {"email": "clean@user.com"},
"fingerprint_matches": [],
"ip_matches": [],
"ip_geo": None,
"recent_signups_ip": 1,
"recent_signups_fp": 1,
"user_agent": "Mozilla/5.0",
}), patch.object(service, '_log_evaluation'):
result = service.evaluate("clean@user.com", "welcome")
assert result.decision == "grant"
assert "clean" in result.reasoning.lower()
@patch('backend.services.credit_evaluation_service.get_settings')
def test_calls_gemini_when_correlations_found(self, mock_settings):
mock_settings.return_value = MagicMock(
credit_eval_enabled=True,
credit_eval_model="gemini-3.1-pro-preview",
google_cloud_project="test",
)
from backend.services.credit_evaluation_service import CreditEvaluationService
service = CreditEvaluationService()
with patch.object(service, '_collect_signals', return_value={
"user_data": {"email": "sus@user.com", "device_fingerprint": "fp123", "signup_ip": "1.2.3.4"},
"fingerprint_matches": [{"email": "other@test.com", "total_jobs_created": 5, "total_spent": 0, "created_at": "2026-03-20"}],
"ip_matches": [],
"ip_geo": None,
"recent_signups_ip": 1,
"recent_signups_fp": 2,
"user_agent": None,
}), patch.object(service, '_call_gemini', return_value='{"decision": "deny", "reasoning": "Same fingerprint", "confidence": 0.9}'), \
patch.object(service, '_log_evaluation'):
result = service.evaluate("sus@user.com", "welcome")
assert result.decision == "deny"
@patch('backend.services.credit_evaluation_service.get_settings')
def test_fails_closed_on_gemini_error(self, mock_settings):
mock_settings.return_value = MagicMock(
credit_eval_enabled=True,
credit_eval_model="gemini-3.1-pro-preview",
google_cloud_project="test",
)
from backend.services.credit_evaluation_service import CreditEvaluationService
service = CreditEvaluationService()
with patch.object(service, '_collect_signals', side_effect=Exception("Firestore down")), \
patch.object(service, '_log_evaluation'):
result = service.evaluate("test@example.com", "welcome")
assert result.decision == "pending_review"
assert result.error is not None
# =============================================================================
# Welcome Credit Integration Tests
# =============================================================================
class TestWelcomeCreditsWithEvaluation:
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_grants_credits_when_evaluation_approves(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
user = User(email="new@user.com", welcome_credits_granted=False)
user_doc = MagicMock()
user_doc.exists = True
user_doc.to_dict.return_value = user.model_dump(mode='json')
mock_db.collection.return_value.document.return_value.get.return_value = user_doc
from backend.services.user_service import UserService
from backend.services.credit_evaluation_service import CreditEvaluation
service = UserService()
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval:
mock_eval.return_value.evaluate.return_value = CreditEvaluation(
decision="grant", reasoning="Clean user", confidence=0.95
)
granted, status = service.grant_welcome_credits_if_eligible("new@user.com")
assert granted is True
assert status == "granted"
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_denies_credits_when_evaluation_rejects(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
user = User(email="abuser@test.com", welcome_credits_granted=False)
user_doc = MagicMock()
user_doc.exists = True
user_doc.to_dict.return_value = user.model_dump(mode='json')
mock_db.collection.return_value.document.return_value.get.return_value = user_doc
from backend.services.user_service import UserService
from backend.services.credit_evaluation_service import CreditEvaluation
service = UserService()
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval, \
patch('backend.services.email_service.get_email_service') as mock_email:
mock_eval.return_value.evaluate.return_value = CreditEvaluation(
decision="deny", reasoning="Same fingerprint as 3 accounts", confidence=0.9
)
granted, status = service.grant_welcome_credits_if_eligible("abuser@test.com")
assert granted is False
assert status == "denied"
# Verify rejection email was sent
mock_email.return_value.send_credit_denied_email.assert_called_once_with("abuser@test.com", "welcome")
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_pending_review_when_evaluation_fails(self, mock_fs, mock_settings):
"""Fail-closed: if evaluation crashes, credits are NOT granted, admin notified."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
user = User(email="new@user.com", welcome_credits_granted=False)
user_doc = MagicMock()
user_doc.exists = True
user_doc.to_dict.return_value = user.model_dump(mode='json')
mock_db.collection.return_value.document.return_value.get.return_value = user_doc
from backend.services.user_service import UserService
service = UserService()
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval, \
patch('backend.services.email_service.get_email_service') as mock_email:
mock_eval.return_value.evaluate.side_effect = Exception("Gemini is down")
granted, status = service.grant_welcome_credits_if_eligible("new@user.com")
assert granted is False
assert status == "pending_review"
# Verify admin review email was sent
mock_email.return_value.send_credit_review_needed_email.assert_called_once()
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_skips_already_granted(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
user = User(email="existing@user.com", welcome_credits_granted=True)
user_doc = MagicMock()
user_doc.exists = True
user_doc.to_dict.return_value = user.model_dump(mode='json')
mock_db.collection.return_value.document.return_value.get.return_value = user_doc
from backend.services.user_service import UserService
service = UserService()
granted, status = service.grant_welcome_credits_if_eligible("existing@user.com")
assert granted is False
assert status == "already_granted"
+243
View File
@@ -0,0 +1,243 @@
"""
Tests for IP geolocation service.
"""
import pytest
from unittest.mock import MagicMock, patch
from datetime import datetime
import sys
sys.modules.setdefault('google.cloud.firestore', MagicMock())
sys.modules.setdefault('google.cloud.firestore_v1', MagicMock())
class TestIsPrivateIp:
def test_private_ipv4(self):
from backend.services.ip_geolocation_service import _is_private_ip
assert _is_private_ip("10.0.0.1") is True
assert _is_private_ip("192.168.1.1") is True
assert _is_private_ip("172.16.0.1") is True
assert _is_private_ip("169.254.169.126") is True
assert _is_private_ip("127.0.0.1") is True
def test_public_ipv4(self):
from backend.services.ip_geolocation_service import _is_private_ip
assert _is_private_ip("8.8.8.8") is False
assert _is_private_ip("1.2.3.4") is False
def test_invalid_ip(self):
from backend.services.ip_geolocation_service import _is_private_ip
assert _is_private_ip("not-an-ip") is True
assert _is_private_ip("") is True
def test_ipv6(self):
from backend.services.ip_geolocation_service import _is_private_ip
assert _is_private_ip("::1") is True # loopback
assert _is_private_ip("2001:db8::1") is True # documentation range
assert _is_private_ip("2402:800:63ac::1") is False # public
class TestParseIpApiResponse:
def test_success_response(self):
from backend.services.ip_geolocation_service import _parse_ip_api_response
data = {
"status": "success",
"country": "United States",
"countryCode": "US",
"regionName": "South Carolina",
"city": "Lancaster",
"isp": "Comporium Inc",
"org": "Comporium Inc",
"as": "AS14615 Comporium Inc",
"timezone": "America/New_York",
"query": "8.8.8.8",
}
result = _parse_ip_api_response(data)
assert result["status"] == "success"
assert result["country_code"] == "US"
assert result["city"] == "Lancaster"
assert result["isp"] == "Comporium Inc"
assert result["as_number"] == "AS14615"
assert result["as_name"] == "Comporium Inc"
def test_fail_response(self):
from backend.services.ip_geolocation_service import _parse_ip_api_response
result = _parse_ip_api_response({"status": "fail", "query": "bad"})
assert result["status"] == "fail"
class TestLookupIp:
@patch('backend.services.ip_geolocation_service.get_settings')
@patch('backend.services.ip_geolocation_service.firestore')
def test_private_ip_returns_immediately(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_fs.Client.return_value = MagicMock()
from backend.services.ip_geolocation_service import IpGeolocationService
service = IpGeolocationService()
result = service.lookup_ip("192.168.1.1")
assert result["status"] == "private"
@patch('backend.services.ip_geolocation_service.get_settings')
@patch('backend.services.ip_geolocation_service.firestore')
def test_cache_hit_returns_cached(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
cached_data = {
"status": "success",
"ip": "8.8.8.8",
"country_code": "US",
"cached_at": datetime.utcnow().isoformat(),
}
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = cached_data
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
from backend.services.ip_geolocation_service import IpGeolocationService
service = IpGeolocationService()
result = service.lookup_ip("8.8.8.8")
assert result["status"] == "success"
assert result["country_code"] == "US"
@patch('backend.services.ip_geolocation_service.get_settings')
@patch('backend.services.ip_geolocation_service.firestore')
@patch('backend.services.ip_geolocation_service.httpx')
def test_cache_miss_fetches_from_api(self, mock_httpx, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
# Cache miss
mock_doc = MagicMock()
mock_doc.exists = False
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
# Mock httpx response
mock_response = MagicMock()
mock_response.json.return_value = {
"status": "success",
"country": "Vietnam",
"countryCode": "VN",
"regionName": "Ho Chi Minh",
"city": "Ho Chi Minh City",
"isp": "Viettel",
"org": "Viettel Group",
"as": "AS7552 Viettel Group",
"timezone": "Asia/Ho_Chi_Minh",
"query": "14.191.152.247",
}
mock_client = MagicMock()
mock_client.__enter__ = MagicMock(return_value=mock_client)
mock_client.__exit__ = MagicMock(return_value=False)
mock_client.get.return_value = mock_response
mock_httpx.Client.return_value = mock_client
from backend.services.ip_geolocation_service import IpGeolocationService
service = IpGeolocationService()
result = service.lookup_ip("14.191.152.247")
assert result["status"] == "success"
assert result["country_code"] == "VN"
assert result["isp"] == "Viettel"
# Should have cached the result
mock_db.collection.return_value.document.return_value.set.assert_called_once()
@patch('backend.services.ip_geolocation_service.get_settings')
@patch('backend.services.ip_geolocation_service.firestore')
def test_null_ip_returns_private(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_fs.Client.return_value = MagicMock()
from backend.services.ip_geolocation_service import IpGeolocationService
service = IpGeolocationService()
result = service.lookup_ip("")
assert result["status"] == "private"
result2 = service.lookup_ip(None)
assert result2["status"] == "private"
class TestLookupBatch:
@patch('backend.services.ip_geolocation_service.get_settings')
@patch('backend.services.ip_geolocation_service.firestore')
def test_all_cached(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
cached_data = {
"status": "success",
"ip": "8.8.8.8",
"country_code": "US",
"cached_at": datetime.utcnow().isoformat(),
}
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = cached_data
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
from backend.services.ip_geolocation_service import IpGeolocationService
service = IpGeolocationService()
results = service.lookup_ips_batch(["8.8.8.8"])
assert "8.8.8.8" in results
assert results["8.8.8.8"]["status"] == "success"
@patch('backend.services.ip_geolocation_service.get_settings')
@patch('backend.services.ip_geolocation_service.firestore')
def test_private_ips_in_batch(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_fs.Client.return_value = MagicMock()
from backend.services.ip_geolocation_service import IpGeolocationService
service = IpGeolocationService()
results = service.lookup_ips_batch(["192.168.1.1", "10.0.0.1"])
assert results["192.168.1.1"]["status"] == "private"
assert results["10.0.0.1"]["status"] == "private"
class TestAdminEndpoints:
@pytest.fixture
def admin_client(self):
from backend.main import app
from backend.api.dependencies import require_admin
from fastapi.testclient import TestClient
mock_auth = MagicMock()
mock_auth.is_admin = True
app.dependency_overrides[require_admin] = lambda: mock_auth
yield TestClient(app)
app.dependency_overrides.clear()
@patch('backend.api.routes.admin.get_ip_geolocation_service')
def test_single_ip_endpoint(self, mock_get_svc, admin_client):
mock_svc = MagicMock()
mock_svc.lookup_ip.return_value = {
"status": "success",
"ip": "8.8.8.8",
"country_code": "US",
}
mock_get_svc.return_value = mock_svc
response = admin_client.get("/api/admin/abuse/ip-info/8.8.8.8")
assert response.status_code == 200
assert response.json()["country_code"] == "US"
@patch('backend.api.routes.admin.get_ip_geolocation_service')
def test_batch_endpoint(self, mock_get_svc, admin_client):
mock_svc = MagicMock()
mock_svc.lookup_ips_batch.return_value = {
"8.8.8.8": {"status": "success", "country_code": "US"},
"1.1.1.1": {"status": "success", "country_code": "AU"},
}
mock_get_svc.return_value = mock_svc
response = admin_client.post(
"/api/admin/abuse/ip-info/batch",
json={"ips": ["8.8.8.8", "1.1.1.1"]},
)
assert response.status_code == 200
data = response.json()
assert data["8.8.8.8"]["country_code"] == "US"
assert data["1.1.1.1"]["country_code"] == "AU"
+389
View File
@@ -0,0 +1,389 @@
"""
Tests for Modal → GCP audio separation migration.
Covers:
- Pipeline decoupling: separation no longer gates lyrics review
- Preset-based model configuration
- Custom output filenames (job_id prefix)
- Screens worker prerequisites relaxation
"""
import os
import tempfile
from datetime import datetime, timezone
from unittest.mock import Mock, patch, MagicMock
import pytest
from backend.models.job import Job, JobStatus
from backend.services.job_manager import JobManager
# ==================== Fixtures ====================
@pytest.fixture
def mock_firestore_service():
with patch('backend.services.job_manager.FirestoreService') as mock:
service = Mock()
mock.return_value = service
yield service
@pytest.fixture
def job_manager(mock_firestore_service):
return JobManager()
def _make_job(job_id="test-001", state_data=None, **kwargs):
defaults = dict(
job_id=job_id,
artist="Test Artist",
title="Test Song",
status=JobStatus.DOWNLOADING,
created_at=datetime.now(timezone.utc),
updated_at=datetime.now(timezone.utc),
theme_id="default",
)
defaults.update(kwargs)
if state_data is not None:
defaults["state_data"] = state_data
return Job(**defaults)
# ==================== P0: Pipeline Decoupling ====================
class TestPipelineDecoupling:
"""
Critical: verify separation is decoupled from lyrics review path.
New behavior:
- check_parallel_processing_complete() only checks lyrics_complete
- mark_audio_complete() sets flag but does NOT trigger screens
- mark_lyrics_complete() triggers screens on its own (no audio gate)
"""
def test_check_parallel_only_requires_lyrics(self, job_manager, mock_firestore_service):
"""lyrics_complete=True is sufficient, even without audio_complete."""
job = _make_job(state_data={"lyrics_complete": True, "audio_complete": False})
mock_firestore_service.get_job.return_value = job
assert job_manager.check_parallel_processing_complete("test-001") is True
def test_check_parallel_fails_without_lyrics(self, job_manager, mock_firestore_service):
"""lyrics_complete=False means not ready, even if audio_complete=True."""
job = _make_job(state_data={"lyrics_complete": False, "audio_complete": True})
mock_firestore_service.get_job.return_value = job
assert job_manager.check_parallel_processing_complete("test-001") is False
def test_check_parallel_fails_with_empty_state(self, job_manager, mock_firestore_service):
"""Empty state_data means not ready."""
job = _make_job(state_data={})
mock_firestore_service.get_job.return_value = job
assert job_manager.check_parallel_processing_complete("test-001") is False
def test_mark_audio_complete_does_not_trigger_screens(self, job_manager, mock_firestore_service):
"""Critical: audio completion must NOT trigger screens worker."""
job = _make_job(state_data={"lyrics_complete": True})
mock_firestore_service.get_job.return_value = job
mock_firestore_service.update_job.return_value = True
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
job_manager.mark_audio_complete("test-001")
mock_trigger.assert_not_called()
def test_mark_lyrics_complete_triggers_screens_without_audio(self, job_manager, mock_firestore_service):
"""Critical: lyrics completion triggers screens even if audio isn't done."""
# After update_state_data sets lyrics_complete, get_job returns updated state
job_after_update = _make_job(state_data={"audio_complete": False, "lyrics_complete": True})
mock_firestore_service.get_job.return_value = job_after_update
mock_firestore_service.update_job.return_value = True
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
job_manager.mark_lyrics_complete("test-001")
mock_trigger.assert_called_once_with("test-001")
def test_mark_lyrics_complete_triggers_screens_with_audio(self, job_manager, mock_firestore_service):
"""Lyrics completion triggers screens when audio is already done too."""
job_after_update = _make_job(state_data={"audio_complete": True, "lyrics_complete": True})
mock_firestore_service.get_job.return_value = job_after_update
mock_firestore_service.update_job.return_value = True
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
job_manager.mark_lyrics_complete("test-001")
mock_trigger.assert_called_once_with("test-001")
def test_ordering_audio_first_then_lyrics(self, job_manager, mock_firestore_service):
"""Typical flow: audio finishes first, then lyrics triggers screens."""
mock_firestore_service.update_job.return_value = True
# Audio completes first — get_job returns state without lyrics_complete
job_audio_only = _make_job(state_data={"audio_complete": True})
mock_firestore_service.get_job.return_value = job_audio_only
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
job_manager.mark_audio_complete("test-001")
mock_trigger.assert_not_called()
# Now lyrics completes — get_job returns state with both flags
job_both = _make_job(state_data={"audio_complete": True, "lyrics_complete": True})
mock_firestore_service.get_job.return_value = job_both
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
job_manager.mark_lyrics_complete("test-001")
mock_trigger.assert_called_once()
def test_ordering_lyrics_first_then_audio(self, job_manager, mock_firestore_service):
"""Less common: lyrics finishes first, triggers screens immediately."""
mock_firestore_service.update_job.return_value = True
# Lyrics completes first — get_job returns state with lyrics_complete
job_lyrics_only = _make_job(state_data={"lyrics_complete": True})
mock_firestore_service.get_job.return_value = job_lyrics_only
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
job_manager.mark_lyrics_complete("test-001")
mock_trigger.assert_called_once()
# Audio completes later — should NOT trigger screens again
job_both = _make_job(state_data={"lyrics_complete": True, "audio_complete": True})
mock_firestore_service.get_job.return_value = job_both
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
job_manager.mark_audio_complete("test-001")
mock_trigger.assert_not_called()
# ==================== P0: Preset Configuration ====================
class TestPresetConfiguration:
"""
Test that preset parameters flow through create_audio_processor correctly.
"""
def test_create_audio_processor_sets_presets(self):
"""Presets are set as attributes on the processor."""
with patch('backend.workers.audio_worker.AudioProcessor') as MockProcessor:
from backend.workers.audio_worker import create_audio_processor
with tempfile.TemporaryDirectory() as temp_dir:
processor = create_audio_processor(
temp_dir,
instrumental_preset="instrumental_clean",
karaoke_preset="karaoke",
)
# Verify presets are set on the returned object
assert processor.instrumental_preset == "instrumental_clean"
assert processor.karaoke_preset == "karaoke"
def test_create_audio_processor_default_presets(self):
"""Default presets are used when not explicitly provided."""
with patch('backend.workers.audio_worker.AudioProcessor') as MockProcessor:
from backend.workers.audio_worker import (
create_audio_processor,
DEFAULT_INSTRUMENTAL_PRESET,
DEFAULT_KARAOKE_PRESET,
)
with tempfile.TemporaryDirectory() as temp_dir:
processor = create_audio_processor(temp_dir)
assert processor.instrumental_preset == DEFAULT_INSTRUMENTAL_PRESET
assert processor.karaoke_preset == DEFAULT_KARAOKE_PRESET
def test_default_other_models_is_empty(self):
"""Demucs 6-stem is dropped — DEFAULT_OTHER_MODELS should be empty."""
from backend.workers.audio_worker import DEFAULT_OTHER_MODELS
assert DEFAULT_OTHER_MODELS == []
def test_create_audio_processor_with_explicit_models(self):
"""Explicit model names still work (legacy per-job override)."""
with patch('backend.workers.audio_worker.AudioProcessor') as MockProcessor:
from backend.workers.audio_worker import create_audio_processor
with tempfile.TemporaryDirectory() as temp_dir:
processor = create_audio_processor(
temp_dir,
clean_instrumental_model="custom_model.ckpt",
backing_vocals_models=["custom_bv.ckpt"],
)
call_kwargs = MockProcessor.call_args[1]
assert call_kwargs["clean_instrumental_model"] == "custom_model.ckpt"
assert call_kwargs["backing_vocals_models"] == ["custom_bv.ckpt"]
# ==================== P0: Custom Output Names Contract ====================
class TestCustomOutputNames:
"""
Test that AudioProcessor uses job_id-based custom_output_names
and organizes results by known filenames.
"""
def test_job_id_used_as_file_prefix(self):
"""When job_id is set, it's used as the filename prefix in custom_output_names."""
from karaoke_gen.audio_processor import AudioProcessor
import logging
processor = AudioProcessor(
logger=logging.getLogger("test"),
log_level=logging.INFO,
log_formatter=None,
model_file_dir=None,
lossless_output_format="FLAC",
clean_instrumental_model="test.ckpt",
backing_vocals_models=[], # No stage 2
other_stems_models=[],
ffmpeg_base_command="ffmpeg",
)
processor.instrumental_preset = "instrumental_clean"
processor.karaoke_preset = None # No stage 2
processor.job_id = "abc123"
mock_client = Mock()
with tempfile.TemporaryDirectory() as temp_dir:
stems_dir = os.path.join(temp_dir, "stems")
os.makedirs(stems_dir)
# Create expected output files
for name in ["abc123_mixed_vocals.flac", "abc123_mixed_instrumental.flac"]:
with open(os.path.join(stems_dir, name), "w") as f:
f.write("fake audio")
mock_client.separate_audio_and_wait.return_value = {
"status": "completed",
"downloaded_files": [
os.path.join(stems_dir, "abc123_mixed_vocals.flac"),
os.path.join(stems_dir, "abc123_mixed_instrumental.flac"),
],
"files": {},
}
input_file = os.path.join(temp_dir, "test.flac")
with open(input_file, "w") as f:
f.write("fake input")
with patch.object(processor, '_create_stems_directory', return_value=stems_dir):
with patch.object(processor, '_normalize_audio_files'):
with patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient', return_value=mock_client):
result = processor._process_audio_separation_remote(
input_file, "Test - Song", temp_dir, "http://fake-api",
)
# Verify custom_output_names used job_id prefix
call_kwargs = mock_client.separate_audio_and_wait.call_args[1]
assert call_kwargs["custom_output_names"]["Vocals"] == "abc123_mixed_vocals"
assert call_kwargs["custom_output_names"]["Instrumental"] == "abc123_mixed_instrumental"
# Verify results found by known filenames
assert result["clean_instrumental"]["vocals"].endswith("abc123_mixed_vocals.flac")
assert "abc123_mixed_instrumental" in result["clean_instrumental"]["instrumental"]
def test_stage1_results_found_by_known_filenames(self):
"""Stage 1 results are located by predictable filenames, not parsed from model names."""
from karaoke_gen.audio_processor import AudioProcessor
import logging
processor = AudioProcessor(
logger=logging.getLogger("test"),
log_level=logging.INFO,
log_formatter=None,
model_file_dir=None,
lossless_output_format="FLAC",
clean_instrumental_model="test.ckpt",
backing_vocals_models=[],
other_stems_models=[],
ffmpeg_base_command="ffmpeg",
)
processor.instrumental_preset = "instrumental_clean"
processor.karaoke_preset = None # No stage 2
processor.job_id = "job42"
with tempfile.TemporaryDirectory() as temp_dir:
stems_dir = os.path.join(temp_dir, "stems")
os.makedirs(stems_dir)
# Create the files the API would produce
vocals_path = os.path.join(stems_dir, "job42_mixed_vocals.flac")
instrumental_path = os.path.join(stems_dir, "job42_mixed_instrumental.flac")
with open(vocals_path, "w") as f:
f.write("fake vocals")
with open(instrumental_path, "w") as f:
f.write("fake instrumental")
mock_client = Mock()
mock_client.separate_audio_and_wait.return_value = {
"status": "completed",
"downloaded_files": [vocals_path, instrumental_path],
"files": {},
}
# Write a fake input file
input_file = os.path.join(temp_dir, "input.flac")
with open(input_file, "w") as f:
f.write("fake input")
with patch.object(processor, '_create_stems_directory', return_value=stems_dir):
with patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient', return_value=mock_client):
with patch.object(processor, '_normalize_audio_files'):
result = processor._process_audio_separation_remote(
input_file, "Test - Song", temp_dir, "http://fake-api",
)
# Should find vocals and instrumental by known filenames
assert result["clean_instrumental"]["vocals"] == vocals_path
assert "mixed_instrumental" in result["clean_instrumental"]["instrumental"]
# ==================== P1: Screens Worker Prerequisites ====================
class TestScreensWorkerPrerequisites:
"""
Test that screens worker no longer requires audio_complete.
"""
def test_validate_prerequisites_passes_without_audio(self):
"""Screens can generate with only lyrics_complete (audio still in progress)."""
from backend.workers.screens_worker import _validate_prerequisites
job = _make_job(state_data={"lyrics_complete": True, "audio_complete": False})
assert _validate_prerequisites(job) is True
def test_validate_prerequisites_passes_with_both(self):
"""Normal case: both audio and lyrics complete."""
from backend.workers.screens_worker import _validate_prerequisites
job = _make_job(state_data={"lyrics_complete": True, "audio_complete": True})
assert _validate_prerequisites(job) is True
def test_validate_prerequisites_fails_without_lyrics(self):
"""Missing lyrics_complete should fail."""
from backend.workers.screens_worker import _validate_prerequisites
job = _make_job(state_data={"lyrics_complete": False, "audio_complete": True})
assert _validate_prerequisites(job) is False
def test_validate_prerequisites_fails_with_empty_state(self):
"""Empty state_data should fail."""
from backend.workers.screens_worker import _validate_prerequisites
job = _make_job(state_data={})
assert _validate_prerequisites(job) is False
def test_validate_prerequisites_fails_without_theme(self):
"""Missing theme_id should fail."""
from backend.workers.screens_worker import _validate_prerequisites
job = _make_job(state_data={"lyrics_complete": True}, theme_id=None)
assert _validate_prerequisites(job) is False
def test_validate_prerequisites_fails_without_artist_title(self):
"""Missing artist or title should fail."""
from backend.workers.screens_worker import _validate_prerequisites
job = _make_job(state_data={"lyrics_complete": True}, artist="", title="Test")
assert _validate_prerequisites(job) is False
+1 -1
View File
@@ -36,7 +36,7 @@ def mock_job_manager():
@pytest.fixture
def mock_storage_service():
with patch('backend.api.routes.file_upload.storage_service') as mock:
mock.bucket_name = "test-bucket"
mock.bucket.name = "test-bucket"
yield mock
+2 -2
View File
@@ -621,7 +621,7 @@ class TestAudioWorkerModelConfiguration:
# Should use default models
assert call_kwargs['clean_instrumental_model'] == "model_bs_roformer_ep_317_sdr_12.9755.ckpt"
assert call_kwargs['backing_vocals_models'] == ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"]
assert call_kwargs['other_stems_models'] == ["htdemucs_6s.yaml"]
assert call_kwargs['other_stems_models'] == []
def test_create_audio_processor_with_custom_clean_model(self):
"""Test creating AudioProcessor with custom clean instrumental model."""
@@ -762,7 +762,7 @@ class TestAudioWorkerModelConfiguration:
# Should fall back to defaults
assert call_kwargs['clean_instrumental_model'] == "model_bs_roformer_ep_317_sdr_12.9755.ckpt"
assert call_kwargs['backing_vocals_models'] == ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"]
assert call_kwargs['other_stems_models'] == ["htdemucs_6s.yaml"]
assert call_kwargs['other_stems_models'] == []
class TestDownloadFromUrl:
+23 -1
View File
@@ -1,8 +1,11 @@
"""
Utilities for identifying test data.
Utilities for identifying test data and internal accounts.
Test data is generated by automated E2E tests and should be filterable
in admin dashboards to show only real user data by default.
Internal accounts belong to team members and should be excluded from
abuse investigation views.
"""
# Email domains used by automated testing frameworks
@@ -10,6 +13,12 @@ TEST_EMAIL_DOMAINS = [
"inbox.testmail.app", # Used by E2E happy path tests
]
# Email domains belonging to internal team members
INTERNAL_EMAIL_DOMAINS = [
"nomadkaraoke.com", # Team accounts
"beveridge.uk", # Founder's personal domain
]
def is_test_email(email: str) -> bool:
"""
@@ -25,3 +34,16 @@ def is_test_email(email: str) -> bool:
return False
email_lower = email.lower()
return any(email_lower.endswith(f"@{domain}") for domain in TEST_EMAIL_DOMAINS)
def is_internal_email(email: str) -> bool:
"""Check if an email address belongs to an internal team member."""
if not email:
return False
email_lower = email.lower()
return any(email_lower.endswith(f"@{domain}") for domain in INTERNAL_EMAIL_DOMAINS)
def is_internal_or_test_email(email: str) -> bool:
"""Check if an email is internal or automated test data."""
return is_test_email(email) or is_internal_email(email)
+66 -31
View File
@@ -61,10 +61,15 @@ async def _trigger_lyrics_worker_after_url_download(job_id: str) -> None:
logger.error(f"Job {job_id}: Failed to trigger lyrics worker: {e}")
# Default model names - used by create_audio_processor and stored in state_data
# Default ensemble presets — resolved by audio-separator package into models + algorithm.
# To change models, update ensemble_presets.json in audio-separator and release a new version.
DEFAULT_INSTRUMENTAL_PRESET = "instrumental_clean" # Fv7z + Resurrection, SDR ~17.5
DEFAULT_KARAOKE_PRESET = "karaoke" # 3 karaoke models ensemble, SDR ~10.6
# Legacy model name constants — kept for backward compatibility with per-job overrides
DEFAULT_CLEAN_MODEL = "model_bs_roformer_ep_317_sdr_12.9755.ckpt"
DEFAULT_BACKING_MODELS = ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"]
DEFAULT_OTHER_MODELS = ["htdemucs_6s.yaml"]
DEFAULT_OTHER_MODELS = [] # Demucs 6-stem dropped — no longer separating individual instruments
# Loggers to capture for audio worker
@@ -197,50 +202,59 @@ def create_audio_processor(
temp_dir: str,
clean_instrumental_model: Optional[str] = None,
backing_vocals_models: Optional[list] = None,
other_stems_models: Optional[list] = None
other_stems_models: Optional[list] = None,
instrumental_preset: Optional[str] = None,
karaoke_preset: Optional[str] = None,
) -> AudioProcessor:
"""
Create an AudioProcessor instance configured for remote API processing.
This reuses the karaoke_gen AudioProcessor with settings optimized for Cloud Run:
- Uses remote Modal API (via AUDIO_SEPARATOR_API_URL env var)
- No local models needed (model_file_dir=None)
- FLAC output format for quality
- Model configurations from job or CLI defaults
Supports two modes:
- Preset mode (default): Uses ensemble presets for higher quality separation.
Presets are resolved by the audio-separator API server.
- Model mode (legacy): Uses explicit model filenames for per-job overrides.
Args:
temp_dir: Temporary directory for processing
clean_instrumental_model: Model for clean instrumental separation (optional, uses default if not provided)
backing_vocals_models: List of models for backing vocals separation (optional, uses default if not provided)
other_stems_models: List of models for other stems separation (optional, uses default if not provided)
clean_instrumental_model: Model for clean instrumental (legacy, overrides preset)
backing_vocals_models: Models for backing vocals (legacy, overrides preset)
other_stems_models: Models for other stems (legacy, default empty)
instrumental_preset: Ensemble preset for instrumental separation
karaoke_preset: Ensemble preset for karaoke/BV separation
Returns:
Configured AudioProcessor instance
"""
# Configure logger for AudioProcessor
audio_logger = logging.getLogger("karaoke_gen.audio_processor")
audio_logger.setLevel(logging.INFO)
# Model configurations - use provided values or defaults from module constants
# Determine effective configuration
# If explicit models are provided, use them (legacy per-job override)
# Otherwise use ensemble presets (default)
effective_clean_model = clean_instrumental_model or DEFAULT_CLEAN_MODEL
effective_backing_models = backing_vocals_models or DEFAULT_BACKING_MODELS
effective_other_models = other_stems_models or DEFAULT_OTHER_MODELS # For 6-stem separation (bass, drums, etc.)
# FFmpeg command for combining audio files (must be a string, not a list)
effective_other_models = other_stems_models or DEFAULT_OTHER_MODELS
ffmpeg_base_command = "ffmpeg -hide_banner -loglevel error -nostats -y"
return AudioProcessor(
processor = AudioProcessor(
logger=audio_logger,
log_level=logging.INFO,
log_formatter=None, # Not needed for our use case
log_formatter=None,
model_file_dir=None, # No local models, using remote API
lossless_output_format="FLAC",
clean_instrumental_model=effective_clean_model,
backing_vocals_models=effective_backing_models,
other_stems_models=effective_other_models,
ffmpeg_base_command=ffmpeg_base_command
ffmpeg_base_command=ffmpeg_base_command,
)
# Set preset configuration (used by _process_audio_separation_remote)
processor.instrumental_preset = instrumental_preset or DEFAULT_INSTRUMENTAL_PRESET
processor.karaoke_preset = karaoke_preset or DEFAULT_KARAOKE_PRESET
return processor
async def process_audio_separation(job_id: str) -> bool:
"""
@@ -356,8 +370,9 @@ async def process_audio_separation(job_id: str) -> bool:
temp_dir,
clean_instrumental_model=job.clean_instrumental_model,
backing_vocals_models=job.backing_vocals_models,
other_stems_models=job.other_stems_models
other_stems_models=job.other_stems_models,
)
audio_processor.job_id = job_id # Used as filename prefix (avoids artist/title encoding issues)
# Store effective model names in state_data for video_worker to use in file naming
# This ensures output filenames match local CLI behavior (e.g., "Instrumental model_bs_roformer_ep_317_sdr_12.9755.ckpt")
@@ -387,12 +402,32 @@ async def process_audio_separation(job_id: str) -> bool:
add_span_event("separation_started")
logger.info(f"[job:{job_id}] Calling Modal API for audio separation")
with metrics.time_external_api("modal", job_id):
separation_result = audio_processor.process_audio_separation(
audio_file=audio_path,
artist_title=artist_title,
track_output_dir=temp_dir
)
# Retry with exponential backoff. The audio-separator GPU service
# may be busy processing other jobs for 5-10+ minutes each, so we
# need patience: 60s, 120s, 240s, 480s = ~15 min total wait.
max_retries = 5
for attempt in range(1, max_retries + 1):
try:
with metrics.time_external_api("modal", job_id):
separation_result = audio_processor.process_audio_separation(
audio_file=audio_path,
artist_title=artist_title,
track_output_dir=temp_dir
)
break # Success
except Exception as e:
error_str = str(e)
if attempt < max_retries:
wait_time = 60 * (2 ** (attempt - 1)) # 60s, 120s, 240s, 480s
job_log.warning(
f"Audio separation attempt {attempt}/{max_retries} failed: {error_str}. "
f"Retrying in {wait_time}s..."
)
logger.warning(f"[job:{job_id}] Separation attempt {attempt} failed: {error_str}")
time.sleep(wait_time)
else:
job_log.error(f"Audio separation failed after {max_retries} attempts: {error_str}")
raise
sep_duration = time.time() - sep_start
sep_span.set_attribute("duration_seconds", sep_duration)
+21 -18
View File
@@ -45,6 +45,7 @@ from backend.services.tracing import job_span, add_span_event, add_span_attribut
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.correction.operations import CorrectionOperations
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
# Import from the unified style loader
@@ -161,30 +162,32 @@ async def process_render_video(job_id: str) -> bool:
with open(original_corrections_path, 'r', encoding='utf-8') as f:
original_data = json.load(f)
# 3. Check if there are updated corrections (from review UI)
# The frontend sends only partial data: {corrections, corrected_segments}
# 3. Load base CorrectionResult from original data
base_result = CorrectionResult.from_dict(original_data)
# 4. Apply user corrections if available (from review UI)
# Uses the same method as preview generation to ensure
# identical CorrectionResult construction (DRY).
updated_corrections_gcs = f"jobs/{job_id}/lyrics/corrections_updated.json"
if storage.file_exists(updated_corrections_gcs):
job_log.info("Found updated corrections from review, merging")
logger.info(f"Job {job_id}: Found updated corrections, merging")
job_log.info("Found updated corrections from review, applying via shared method")
logger.info(f"Job {job_id}: Found updated corrections, applying via shared method")
updated_path = os.path.join(temp_dir, "corrections_updated.json")
storage.download_file(updated_corrections_gcs, updated_path)
with open(updated_path, 'r', encoding='utf-8') as f:
updated_data = json.load(f)
# Merge: update the original with the user's corrections
if 'corrections' in updated_data:
original_data['corrections'] = updated_data['corrections']
if 'corrected_segments' in updated_data:
original_data['corrected_segments'] = updated_data['corrected_segments']
job_log.info("Merged user corrections into original data")
logger.info(f"Job {job_id}: Merged user corrections into original data")
# 4. Convert to CorrectionResult
correction_result = CorrectionResult.from_dict(original_data)
# Same construction path as preview — prevents divergence
correction_result = CorrectionOperations.update_correction_result_with_data(
base_result, updated_data
)
job_log.info("Applied user corrections via CorrectionOperations")
logger.info(f"Job {job_id}: Applied user corrections via CorrectionOperations")
else:
correction_result = base_result
job_log.info(f"Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
logger.info(f"Job {job_id}: Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
+8 -6
View File
@@ -258,7 +258,7 @@ async def generate_screens(job_id: str) -> bool:
def _validate_prerequisites(job) -> bool:
"""
Validate that both audio and lyrics processing are complete.
Validate that lyrics processing is complete (audio is no longer required).
Single Responsibility: Validation logic separated from main flow.
@@ -286,17 +286,19 @@ def _validate_prerequisites(job) -> bool:
)
return False
audio_complete = job.state_data.get('audio_complete', False)
lyrics_complete = job.state_data.get('lyrics_complete', False)
if not audio_complete:
logger.error(f"Job {job.job_id}: Audio processing not complete")
return False
audio_complete = job.state_data.get('audio_complete', False)
if not lyrics_complete:
logger.error(f"Job {job.job_id}: Lyrics processing not complete")
return False
# Audio separation is no longer a prerequisite for screens.
# Users can start lyrics review while separation runs in the background.
# The instrumental review page handles waiting for audio_complete.
if not audio_complete:
logger.info(f"Job {job.job_id}: Audio separation still in progress (not blocking screens)")
if not job.artist or not job.title:
logger.error(f"Job {job.job_id}: Missing artist or title")
return False
+155
View File
@@ -0,0 +1,155 @@
# AI-Powered Credit Gating
## Overview
Free credit grants (welcome credits and feedback bonus credits) are evaluated by an AI model before being approved. This prevents multi-account abuse where users create multiple accounts to farm free karaoke generation credits.
The system is **fail-closed**: if anything goes wrong (AI error, unclear response, network issue), credits are NOT granted automatically. Instead, the admin is notified to review manually.
## How It Works
```
User verifies email (or submits feedback)
↓
Collect abuse signals:
• Device fingerprint correlations (other accounts with same fingerprint)
• IP address correlations (other accounts from same IP)
• IP geolocation (country, ISP, VPN detection)
• Recent signup patterns (new accounts from same IP/fingerprint in last 24h)
• User agent string
• For feedback: the submitted feedback content
↓
Clean user? (no correlations, no recent signup spike)
→ YES: Grant credits immediately (no AI call needed)
→ NO: Call Gemini for evaluation
↓
Gemini decision:
• "grant" → Grant credits, user sees celebratory welcome screen
• "deny" → No credits, user gets rejection email (CC'd to Andrew)
• Error/uncertain → No credits, user told "team will review shortly",
Andrew gets review email with admin link
```
## Decision Outcomes
| Scenario | Credits | User Experience | Admin Notification |
|----------|---------|-----------------|-------------------|
| Clean user (no correlations) | Granted | "1 free credit!" interstitial | None |
| AI approves | Granted | Same | None |
| AI denies (abuse detected) | Not granted | "Couldn't grant free credits" + buy CTA | CC on rejection email to user |
| AI error / uncertain | Not granted | "Team will review shortly" + buy CTA | Review email with admin page link |
| Evaluation disabled | Granted | Same as clean | None |
## Frontend Flow
The verify page (`/auth/verify`) shows these states in sequence:
1. **"Verifying your sign-in link..."** — Token validation
2. **"Preparing your account..."** — AI evaluation running (2-5 seconds)
3. One of:
- **Credits granted** — Celebratory screen with credit count, gentle reminder not to abuse, "Start Creating Karaoke" button
- **Credits denied** — "Couldn't grant free credits" with buy credits CTA and link to dashboard
- **Credits pending review** — "Team will review shortly" with buy credits CTA and "Explore the App" button
- **Success** (returning user) — "Welcome back!" with auto-redirect
## Emails
### To User: Credit Denied
- Subject: "About your Nomad Karaoke free credits"
- CC: andrew@beveridge.uk
- Tone: Friendly but firm — explains costs, invites reply if mistake
- Includes buy credits link
### To Admin: Review Needed
- Subject: "Credit review needed: user@example.com (welcome)"
- To: andrew@beveridge.uk
- Includes direct link to user's admin page (`/admin/users/detail?email=...`)
- Explains what to do: grant credits if legitimate, do nothing if not
## Configuration
| Environment Variable | Default | Description |
|---------------------|---------|-------------|
| `CREDIT_EVAL_ENABLED` | `true` | Set to `false` to disable AI evaluation and auto-grant all credits |
| `CREDIT_EVAL_MODEL` | `gemini-3.1-pro-preview` | Gemini model to use for evaluation |
### Emergency Rollback
Set `CREDIT_EVAL_ENABLED=false` in Cloud Run environment variables. This immediately reverts to the old behavior of auto-granting all credits without AI evaluation.
## Audit Trail
Every evaluation is logged to the `credit_evaluations` Firestore collection:
```json
{
"id": "uuid",
"email": "user@example.com",
"grant_type": "welcome",
"decision": "grant",
"reasoning": "No suspicious correlations found — clean user",
"confidence": 1.0,
"error": null,
"model": "gemini-3.1-pro-preview",
"signals_snapshot": {
"fingerprint_match_count": 0,
"ip_match_count": 0,
"recent_signups_ip": 1,
"recent_signups_fp": 1,
"user_ip": "1.2.3.4",
"user_fingerprint": "abc123..."
},
"evaluated_at": "2026-03-23T21:00:00Z"
}
```
## Admin Workflow
When you receive a "Credit review needed" email:
1. Click the "Review User" link to go to their admin page
2. Check their abuse signals: fingerprint matches, IP matches, job history
3. If legitimate: Use the admin credits endpoint to grant 1 credit manually
4. If abusive: No action needed — they already have 0 credits
Note: For `pending_review` cases, the `welcome_credits_granted` flag is NOT set, so the system won't interfere if you grant credits manually later.
## Architecture
### Files
| File | Purpose |
|------|---------|
| `backend/services/credit_evaluation_service.py` | Core service: signal collection, Gemini prompt, response parsing, audit logging |
| `backend/config.py` | `CREDIT_EVAL_ENABLED`, `CREDIT_EVAL_MODEL` config |
| `backend/services/user_service.py` | `grant_welcome_credits_if_eligible()` integration |
| `backend/api/routes/users.py` | Feedback credit flow integration, verify response includes `credit_status` |
| `backend/services/email_service.py` | `send_credit_denied_email()`, `send_credit_review_needed_email()` |
| `backend/models/user.py` | `VerifyMagicLinkResponse.credit_status` field |
| `frontend/app/auth/verify/page.tsx` | 5-state verify flow with interstitials |
| `frontend/lib/types.ts` | `credit_status` type on verify response |
### Signal Collection
The evaluation service calls these existing methods to collect signals:
- `user_service.find_users_by_fingerprint()` — other accounts with same device fingerprint
- `user_service.find_users_by_signup_ip()` — other accounts from same IP
- `user_service.count_recent_signups_from_ip()` — new accounts from same IP in last 24h
- `user_service.count_recent_signups_from_fingerprint()` — new accounts from same fingerprint in last 24h
- `ip_geolocation_service.lookup_ip()` — country, ISP, org info
- Session collection query — latest user agent
### Gemini Prompt
The prompt instructs Gemini to:
- **DENY** if fingerprint matches other accounts (strong multi-accounting signal)
- **DENY** if IP matches + other suspicious patterns (same UA, no spend)
- **GRANT** if appears genuine or insufficient evidence
- **When in doubt, GRANT** — false positives worse than false negatives
The response is structured JSON: `{"decision": "grant"|"deny", "reasoning": "...", "confidence": 0.0-1.0}`
### Quick-Grant Optimization
If no correlations are found at all (no fingerprint matches, no IP matches, recent signup counts ≤ 1), the system skips the AI call entirely and grants immediately. This means most legitimate users experience zero additional latency.
+46 -4
View File
@@ -944,7 +944,7 @@ Credits are checked and deducted at job creation time. The flow:
3. **Deduct** - `user_service.deduct_credit()` atomically deducts 1 credit (with job_id for audit trail)
4. **Refund on failure** - If the job fails, 1 credit is automatically refunded
Admin users bypass credit checks entirely. New users receive 2 welcome credits. Users can earn 2 additional free credits by submitting product feedback after completing 2+ jobs (see [User Feedback for Credits](#user-feedback-for-credits)).
Admin users bypass credit checks entirely. New users receive 1 welcome credit. Users can earn 1 additional free credit by submitting product feedback after completing 2+ jobs (see [User Feedback for Credits](#user-feedback-for-credits)).
#### 402 Response
@@ -969,7 +969,7 @@ Handles `checkout.session.completed` events.
### User Feedback for Credits
Users who have completed 2+ jobs can submit feedback to earn 2 free credits.
Users who have completed 2+ jobs can submit feedback to earn 1 free credit.
#### Check Eligibility
@@ -984,7 +984,7 @@ Response:
"eligible": true,
"has_submitted": false,
"jobs_completed": 3,
"credits_reward": 2
"credits_reward": 1
}
```
@@ -1013,7 +1013,7 @@ Requirements:
- At least one text field must have >50 characters
- User can only submit once (duplicate prevention)
Grants 2 credits on success. Feedback stored in `user_feedback` Firestore collection.
Grants 1 credit on success. Feedback stored in `user_feedback` Firestore collection.
The `/api/users/me` response includes `feedback_eligible: bool` so the frontend can show/hide feedback prompts without an extra API call.
@@ -1699,6 +1699,48 @@ Called by Cloud Tasks 5 minutes after a job enters a blocking state (primarily `
**Note**: With the combined review flow, users complete both lyrics review and instrumental selection in one session. The `awaiting_instrumental_selection` state is only used for finalise-only jobs.
### Admin Feedback
```http
GET /api/admin/feedback
GET /api/admin/feedback?search=user@example.com&exclude_test=true&limit=50&offset=0
Authorization: Bearer ADMIN_TOKEN
```
Lists all user feedback submissions with pagination, search, and aggregate stats.
Response:
```json
{
"items": [
{
"id": "uuid",
"user_email": "user@example.com",
"created_at": "2026-03-01T12:00:00",
"overall_rating": 4,
"ease_of_use_rating": 5,
"lyrics_accuracy_rating": 3,
"correction_experience_rating": 4,
"what_went_well": "...",
"what_could_improve": "...",
"additional_comments": null,
"would_recommend": true,
"would_use_again": true
}
],
"total": 2,
"offset": 0,
"limit": 50,
"has_more": false,
"avg_overall_rating": 4.0,
"avg_ease_of_use_rating": 4.5,
"avg_lyrics_accuracy_rating": 3.5,
"avg_correction_experience_rating": 4.0
}
```
An email notification is also sent to `admin@nomadkaraoke.com` (configurable via `ADMIN_NOTIFICATION_EMAIL` env var) whenever a user submits new feedback.
## Rate Limits & Abuse Prevention
### Usage Control
+4 -4
View File
@@ -16,7 +16,7 @@
│ https://api.nomadkaraoke.com │
│ │
│ Workers: │
│ • Audio Worker - Stem separation via Modal API │
│ • Audio Worker - Stem separation via Cloud Run GPU (L4) │
│ • Lyrics Worker - Transcription via AudioShake │
│ • Screens Worker - Title/end screen generation │
│ • Render Worker - Karaoke video with lyrics │
@@ -48,7 +48,7 @@
2. PARALLEL PROCESSING (with Worker Registry coordination)
┌─────────────────┐ ┌─────────────────┐
│ Audio Worker │ │ Lyrics Worker │
│ Modal API │ │ AudioShake │
│ Cloud Run GPU │ │ AudioShake │
│ 2-stage sep │ │ Auto-correct │
│ ↓ register() │ │ ↓ register() │
│ ↓ unregister() │ │ ↓ unregister() │
@@ -161,7 +161,7 @@ LyricsTranscriber LyricsTranscriber
| Service | Purpose | Required |
|---------|---------|----------|
| Modal | GPU audio separation | Yes |
| Cloud Run GPU (L4) | Audio stem separation (us-east4) | Yes |
| AudioShake | Lyrics transcription | Yes |
| Vertex AI | Agentic AI correction (Gemini 3 Flash) | Default off (SKIP_CORRECTION=false to enable) |
| Genius | Reference lyrics | Yes |
@@ -323,7 +323,7 @@ Audio and lyrics workers run as **Cloud Run Jobs** - standalone batch containers
│ │
│ audio-download-job - 30s-5 min (flacfetch/YouTube) │
│ lyrics-transcription-job - 5-15 min (AudioShake + correction)│
│ audio-separation-job - 10-20 min (Modal API) │
│ audio-separation-job - 10-20 min (Cloud Run GPU) │
│ video-encoding-job - up to 60 min (optional) │
│ │
│ Triggered via: google.cloud.run_v2.JobsClient.run_job() │
+10
View File
@@ -58,6 +58,16 @@ Audio separation and lyrics transcription run in parallel. Both can fail indepen
### GCE Instance Selection for FFmpeg
AMD EPYC (C4D series) significantly outperforms Intel Xeon (C4 series) for CPU-bound FFmpeg encoding with libass. C4D-highcpu-32 is ~5x faster than C4-standard-8. C4D requires `hyperdisk-balanced` disk type.
### Data Types Must Enforce Their Own Invariants (Mar 2026)
When a data type has constraints on its fields (e.g., "word text must not contain newlines"), enforce them in the type's constructor (`__post_init__`), not in callers. This bug was caused by `Word` objects being constructed via two different code paths — one that stripped newlines (preview) and one that didn't (final render). The preview accidentally worked while final renders had corrupted subtitles with silently dropped lyrics. The fix: `Word.__post_init__` strips whitespace so ALL construction paths are safe, plus a defensive strip at the ASS output boundary.
**Key principles:**
- **Single source of truth for data invariants** — the type, not the caller, is responsible for field constraints
- **Defensive output boundaries** — even with clean inputs, validate at system boundaries (ASS file writing) as a safety net
- **Two code paths doing "the same thing" will diverge** — if preview and render both construct CorrectionResult, they must use the same method, not reimplementations
**Detection clue:** If `corrected.txt` shows correct lyrics but the video is missing words, check for embedded newlines in Word text corrupting ASS dialogue events.
### Large Documents: GCS + Firestore Metadata (Mar 2026)
When a document's payload can exceed Firestore's 1MB limit (e.g., CorrectionData at 100KB+ per session), store the payload in GCS and keep only metadata in Firestore. Use SHA-256 hash deduplication to avoid re-uploading identical data. For cross-document queries (e.g., searching sessions across jobs), use Firestore collection group queries on the metadata subcollection with Python-side text filtering — Firestore doesn't support LIKE/substring queries natively.
+1 -1
View File
@@ -61,7 +61,7 @@ Guidelines for how to communicate about Nomad Karaoke to users, in marketing mat
## Free Credits
- All new accounts receive 2 free credits to try the service
- All new accounts receive 1 free credit to try the service
- No payment required to get started
- Credits never expire
- Additional credits available for purchase ($5/credit, bulk discounts available)
+3 -3
View File
@@ -24,7 +24,7 @@
| Token-based auth | Working |
| Magic link auth | Working |
| Payment flow (Stripe) | Working |
| Feedback-for-credits | Working (2+ jobs → 2 free credits) |
| Feedback-for-credits | Working (2+ jobs → 1 free credit) |
| Admin dashboard | Working |
| Abuse prevention & YouTube quota | Working (blocklists, IP/fingerprint rate limiting, credits on verification, quota-aware YouTube uploads) |
| CI/CD self-hosted runner | Working (GCP) |
@@ -74,9 +74,9 @@
- **Song Lookup Autocomplete & Community Version Detection** (2026-03-03): Added song catalog integration to the job creation flow. Two features: (1) **Track autocomplete** on the title field provides canonical artist/title names from MusicBrainz + Spotify data via the karaoke-decide catalog API, improving text consistency for YouTube releases. Autocomplete activates when the artist field has a value; selecting a suggestion overwrites both artist and title with canonical names. (2) **Community version detection** checks karaokenerds.com for existing high-quality karaoke versions — if found, a dismissible green banner suggests the user check those versions first before spending credits. New backend: 3 endpoints (`/api/catalog/artists`, `/api/catalog/tracks`, `/api/catalog/community-check`) with per-user rate limiting (20 req/min) and in-memory TTL caching. New services: `catalog_proxy_service.py` (proxies to karaoke-decide), `karaokenerds_service.py` (scrapes karaokenerds.com). New frontend components: `AutocompleteInput` (reusable), `CommunityVersionBanner`. See [API.md](API.md#catalog-song-lookup).
- **Feedback-for-Credits** (2026-03-01): Added a feedback-for-credits mechanism available to all users (replaces the old beta-only feedback flow). Users who complete 2+ karaoke videos can submit product feedback (star ratings + text) to earn 2 free credits (total possible free credits: 4 — 2 welcome + 2 feedback). New endpoints: `GET /api/users/feedback/eligibility`, `POST /api/users/feedback`. The `/api/users/me` response includes `feedback_eligible: bool` so the frontend can show/hide prompts without an extra API call. Frontend shows a dismissible banner on the dashboard and a "Earn 2 Free Credits" menu item in the user dropdown when eligible. Feedback stored in `user_feedback` Firestore collection with duplicate prevention via `has_submitted_feedback` flag on user model. Welcome email updated with credit-focused messaging and feedback teaser. See [API.md](API.md#user-feedback-for-credits).
- **Feedback-for-Credits** (2026-03-01): Added a feedback-for-credits mechanism available to all users (replaces the old beta-only feedback flow). Users who complete 2+ karaoke videos can submit product feedback (star ratings + text) to earn 1 free credit (total possible free credits: 2 — 1 welcome + 1 feedback). New endpoints: `GET /api/users/feedback/eligibility`, `POST /api/users/feedback`. The `/api/users/me` response includes `feedback_eligible: bool` so the frontend can show/hide prompts without an extra API call. Frontend shows a dismissible banner on the dashboard and a "Earn 1 Free Credit" menu item in the user dropdown when eligible. Feedback stored in `user_feedback` Firestore collection with duplicate prevention via `has_submitted_feedback` flag on user model. Welcome email updated with credit-focused messaging and feedback teaser. See [API.md](API.md#user-feedback-for-credits).
- **Remove Beta Program from Homepage** (2026-03-01): Removed beta enrollment from landing page and replaced with prominent "2 Free Credits" messaging. Beta enrollment endpoint preserved for backward compatibility but no longer actively promoted. See PR #430.
- **Remove Beta Program from Homepage** (2026-03-01): Removed beta enrollment from landing page and replaced with prominent "1 Free Credit" messaging. Beta enrollment endpoint preserved for backward compatibility but no longer actively promoted. See PR #430.
- **Fix Event Loop Blocking in Audio Search Endpoints** (2026-02-28): Fixed `/api/audio-search/{job_id}/select` taking 20-36s to respond (should be <1s) and `/api/audio-search/search` sometimes taking 25-47s. **Root cause**: Async endpoints called sync methods that create new event loops via `loop.run_until_complete()`, blocking the FastAPI event loop — response body was queued but never flushed. **Fix**: RED/OPS and Spotify download paths now call `FlacfetchClient` async methods directly (matching `YouTubeDownloadService` pattern), generic downloads use `asyncio.to_thread()`, search endpoint uses `search_async()`. Also fixed `InsufficientCreditsError` occasionally returning 500 instead of 402 by using `isinstance()` check. Added 14 new tests. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#never-call-sync-over-async-from-fastapi-async-routes-feb-2026).
+3 -3
View File
@@ -151,11 +151,11 @@ python scripts/backfill_gdrive_uploads.py --job-ids JOB1,JOB2
## Job failed: "Audio separation failed: expected str, bytes or os.PathLike object, not NoneType"
**Cause:** Modal API intermittently returned fewer stems than expected from stage 2 (backing vocals) separation. Missing stems caused NoneType crashes in downstream processing.
**Cause (historical):** Modal API intermittently returned fewer stems than expected from stage 2 (backing vocals) separation. Missing stems caused NoneType crashes in downstream processing. This was resolved by migrating to Cloud Run GPU (see `docs/archive/2026-03-22-modal-to-gcp-migration-plan.md`).
**Fix (v0.135+):** Stage 2 now validates that all expected stems are present (matching existing stage 1 validation). Defensive null checks prevent confusing TypeError messages. Full tracebacks are logged with `exc_info=True`.
**Fix (v0.135+):** Stage 2 now validates that all expected stems are present. Defensive null checks prevent confusing TypeError messages. Full tracebacks are logged with `exc_info=True`.
**Recovery:** Retry the job — the failure is transient (Modal API intermittent). Long-term fix: migrate audio separation from Modal to GCP (see `docs/archive/2026-03-21-modal-to-gcp-migration-plan.md`).
**Recovery:** Retry the job. With the Cloud Run GPU deployment, transient API failures are much less frequent than they were with Modal.
---
@@ -1,121 +0,0 @@
# Modal to GCP Audio Separation Migration Plan
**Date:** 2026-03-21
**Status:** Planning seed (not yet started)
**Priority:** Medium - reduces external dependency risk and cost
## Why Migrate
1. **Reliability** - Modal API intermittently fails to return stem files ("no files were downloaded" errors), causing job failures that require manual retries.
2. **Latency** - Round-trip to Modal (upload audio, wait for GPU separation, download stems) adds network overhead. Local GCP processing eliminates cross-provider data transfer.
3. **Cost** - Modal charges for GPU compute on their platform. GCP GPU VMs or spot instances may be cheaper, especially with sustained use discounts.
4. **Dependency reduction** - Modal is the only third-party compute dependency. Removing it means the entire pipeline runs within GCP.
## Current State
### How Modal Is Used
The audio worker (`backend/workers/audio_worker.py`) runs on Cloud Run and calls Modal via the `audio-separator[remote]` Python package:
1. Cloud Run audio worker downloads the source audio from GCS
2. `AudioProcessor.process_audio_separation()` checks `AUDIO_SEPARATOR_API_URL` env var
3. Calls `AudioSeparatorAPIClient.separate_audio()` which POSTs the audio file to Modal's HTTP API
4. Modal runs GPU separation and returns stem files
5. Worker downloads stems, post-processes, and uploads to GCS
**API endpoint:** `https://nomadkaraoke--audio-separator-api.modal.run`
**Configured in:** `infrastructure/modules/cloud_run.py` (env var on Cloud Run service)
### Models Used
- **Stage 1 (Clean instrumental):** `model_bs_roformer_ep_317_sdr_12.9755.ckpt` (BS-Roformer)
- **Stage 1 (Other stems):** `htdemucs_6s.yaml` (Demucs 6-stem)
- **Stage 2 (Backing vocals):** `mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt` (Mel-Band Roformer)
### Processing Time
- Stage 1: ~3-5 minutes
- Stage 2: ~2-3 minutes
- Total audio worker timeout: 30 minutes (includes download/upload overhead)
### Existing GCP Infrastructure
- **Encoding worker VM** (`c4d-highcpu-32`, `us-central1-c`) - CPU-only, handles video encoding
- Packer-based image build, GCS-based deployment (wheel + startup.sh)
- Pulumi IaC in `infrastructure/`
- The `audio-separator` package already supports local processing (just needs GPU + models)
## Target State
Run audio separation on a GCP GPU VM instead of Modal. The `audio-separator` package already supports both local and remote modes - we just need to point it at our own GPU endpoint (or run locally on the GPU VM).
## Options
### Option A: Dedicated GCE GPU VM (Recommended)
Similar pattern to the encoding worker. A persistent VM with GPU that runs the audio-separator API.
- **Pros:** Simple, mirrors existing encoding worker pattern, models stay loaded in memory, fast cold start after first load
- **Cons:** Pays for GPU even when idle, need to handle scaling
- **GPU:** NVIDIA T4 (~$0.35/hr) or L4 (~$0.70/hr) sufficient for these models
- **Cost estimate:** T4 spot instance ~$100-150/month if running 24/7 (vs Modal pay-per-use)
### Option B: GCE Spot GPU VM (Start/Stop)
Same as A but stop the VM when not processing, start on demand.
- **Pros:** Only pay when processing, cheapest option
- **Cons:** Cold start (VM boot + model loading ~2-5 min), spot can be preempted, more complex orchestration
- **Best if:** Job volume is low/bursty
### Option C: Cloud Run Jobs with GPU
Cloud Run now supports GPU (L4) for jobs.
- **Pros:** Serverless, auto-scaling, no idle cost, Cloud Run already used for other workers
- **Cons:** GPU availability can be limited, cold start on each job, 1-hour max timeout, model download on each cold start unless cached
- **Cost estimate:** Pay only for job duration, but model loading adds per-job overhead
### Option D: Run Locally on Audio Worker (Cloud Run)
Run separation directly in the Cloud Run audio worker with a GPU.
- **Pros:** Simplest code change (just remove AUDIO_SEPARATOR_API_URL, models load locally)
- **Cons:** Cloud Run GPU instances are expensive if kept warm, model loading on cold start
## Recommendation
**Option A (dedicated GCE GPU VM)** for initial migration, with a path to Option B if cost is a concern.
Rationale:
- Mirrors the proven encoding worker pattern (Packer image, GCS deploy, Pulumi)
- Models stay loaded = fast separation with no cold start penalty
- Simplest to implement and debug
- Can add start/stop automation later (Option B) if idle cost is too high
## Key Considerations
- **Model storage:** ~2-3 GB total for the three models. Bake into Packer image or download on first start to a persistent disk.
- **GPU memory:** These models fit comfortably in a T4 (16 GB VRAM). L4 (24 GB) provides headroom.
- **API compatibility:** Can reuse the existing `AudioSeparatorAPIClient` by running the audio-separator API server on the GCE VM and updating `AUDIO_SEPARATOR_API_URL` to point to it.
- **Fallback:** Keep Modal config as a fallback during migration. The `AUDIO_SEPARATOR_API_URL` env var swap makes this easy.
- **Networking:** VM needs to accept requests from Cloud Run audio worker. Use internal networking or IAP + auth token (same pattern as encoding worker).
## Migration Steps (High Level)
1. **Spike:** Run audio-separator API server locally with GPU, verify it produces identical output to Modal
2. **Infrastructure:** Create Pulumi resources for GPU VM (instance, disk, firewall, service account) - copy encoding worker pattern
3. **Packer image:** Build image with CUDA, Python, audio-separator, pre-downloaded models
4. **Deploy & test:** Stand up VM, point a test job at it, compare output quality and timing
5. **Cutover:** Update `AUDIO_SEPARATOR_API_URL` in Cloud Run config to point to GCE VM
6. **Monitor:** Watch for errors/quality issues for a week
7. **Decommission:** Remove Modal deployment, remove `audio-separator-api-url` secret, clean up Modal account
## Files to Modify (When Implementing)
- `infrastructure/compute/` - New GPU VM module (similar to `encoding_worker_vm.py`)
- `infrastructure/packer/` - New Packer template for GPU image
- `infrastructure/modules/cloud_run.py` - Update `AUDIO_SEPARATOR_API_URL` value
- `infrastructure/__main__.py` - Wire up new resources
- `infrastructure/config.py` - Add GPU VM machine type/zone constants
- No backend code changes needed if we keep the HTTP API interface
@@ -0,0 +1,339 @@
# Plan: Modal → GCP Audio Separation Migration
**Created:** 2026-03-22
**Branch:** feat/sess-20260321-2314-modal-gcp-migration
**Worktrees:** `karaoke-gen-modal-gcp-migration` (infra + backend), `python-audio-separator-modal-gcp-migration` (server)
**Status:** Draft → Ready for implementation
## Overview
Migrate audio stem separation from Modal to a Cloud Run Service with L4 GPU on GCP. This eliminates the only third-party compute dependency, fixes intermittent Modal API failures ("no files were downloaded"), upgrades to latest ensemble models for better quality, and decouples separation from the lyrics review critical path so users can start reviewing lyrics faster.
### Architecture Decision: Cloud Run GPU Service
| Factor | Cloud Run GPU | GCE VM + auto-stop |
|--------|--------------|-------------------|
| Idle cost | $0 (scales to zero) | $0 (when stopped) |
| Cold start | ~30-60s (model load from GCS) | ~60-120s (VM boot + model load) |
| Ops overhead | None (serverless) | Moderate (start/stop scripts, health monitoring) |
| GPU available | L4 (24GB VRAM) in us-central1 | T4/L4/A100 |
| Scaling | Automatic | Manual orchestration |
| Cost/job (~12 min GPU) | ~$0.13 | ~$0.07-0.10 (T4) |
| Deployment | Docker image push | Packer image + GCS wheel + SSH restart |
Cloud Run GPU wins on simplicity. L4 is faster than T4, cold start is acceptable, and per-job cost well under $1.
### Model Upgrade: Ensemble Presets as Default
**Current models (single-model):**
| Stage | Model | SDR | Notes |
|-------|-------|-----|-------|
| 1 (instrumental) | `model_bs_roformer_ep_317_sdr_12.9755.ckpt` | 12.97 | Older BS-Roformer |
| 1 (other stems) | `htdemucs_6s.yaml` | — | Demucs 6-stem — **dropping** |
| 2 (karaoke/BV) | `mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt` | 10.20 | Single karaoke model |
**New defaults (ensemble presets):**
| Stage | Preset | Models | SDR | Notes |
|-------|--------|--------|-----|-------|
| 1 | `instrumental_clean` | Fv7z + Resurrection | ~17.5 | +35% quality, bleedless |
| 2 | `karaoke` | 3 karaoke models (aufr33+gabox_v2+becruily) | ~10.6 | +4% quality, 3-model ensemble |
**Key design: preset-name references, not model filenames.** karaoke-gen references preset names (`instrumental_clean`, `karaoke`). The audio-separator package resolves preset → models + ensemble algorithm. When better models come out, update presets in audio-separator and release a new version — no karaoke-gen changes needed.
### Pipeline Decoupling: Separation Off Critical Path
**Current flow (both gate review):**
```
Job created
├── Audio worker (separation) ──→ audio_complete=True ─┐
│ ├→ GENERATING_SCREENS → AWAITING_REVIEW
└── Lyrics worker (transcription) → lyrics_complete=True┘
```
**New flow (lyrics gates review, separation runs in background):**
```
Job created
├── Audio worker (separation) ──→ audio_complete=True (background, not gating)
│
└── Lyrics worker (transcription) → lyrics_complete=True → GENERATING_SCREENS → AWAITING_REVIEW
│
User reviews lyrics
│
Instrumental review
(waits for audio_complete
if not ready yet)
```
**Why this works:**
- Lyrics review (`/app/jobs#/{jobId}/review`) only needs transcription output — no stems needed
- Instrumental review (`/app/jobs#/{jobId}/instrumental`) needs stems — but user typically spends 5+ min on lyrics review, buying time for separation to finish
- In the rare case separation isn't done when user reaches instrumental review, show a "Separation in progress..." waiting state
- Screens worker only truly needs lyrics to generate title/end screens
### Estimated Timeline
| Scenario | Stage 1 | Stage 2 | Cold start | Total |
|----------|---------|---------|------------|-------|
| Current (Modal, single models) | 3-5 min | 2-3 min | 0 | 7-11 min |
| New ensemble (Cloud Run L4) | ~4-6 min | ~3-5 min | ~30-60s | ~8-12 min |
| **User-perceived wait** (new) | — | — | — | **0 min** (decoupled) |
Separation takes slightly longer with ensembles, but users never wait for it — they're reviewing lyrics while it runs.
## Requirements
- [ ] Audio separation runs on GCP Cloud Run with L4 GPU
- [ ] Same HTTP API contract as Modal deployment (endpoints, request/response format)
- [ ] `audio-separator-remote` CLI and `AudioSeparatorAPIClient` work unchanged
- [ ] Default models use ensemble presets (`instrumental_clean` + `karaoke`)
- [ ] karaoke-gen references preset names, not model filenames
- [ ] Demucs 6-stem separation dropped from pipeline
- [ ] Scale-to-zero when not processing (no idle GPU cost)
- [ ] Cold start < 60 seconds
- [ ] Per-job cost < $1
- [ ] Models stored in GCS, loaded on container startup
- [ ] Publicly accessible endpoint with auth token (reuse `admin-tokens` secret)
- [ ] Infrastructure managed via Pulumi in karaoke-gen
- [ ] Separation decoupled from lyrics review critical path
- [ ] Instrumental review page handles "separation still in progress" gracefully
- [ ] Docker image CI lives in python-audio-separator repo, pushes to Artifact Registry
## Implementation Steps
### Phase 1: Cloud Run GPU Server (python-audio-separator repo)
#### Step 1.1 — Create Cloud Run-compatible FastAPI server
- [ ] Create `audio_separator/remote/deploy_cloudrun.py` adapted from `deploy_modal.py`
- [ ] Replace Modal-specific code:
- `modal.Dict` → in-memory `dict` (single instance handles one job at a time)
- `modal.Volume` → local `/tmp` storage + GCS for model cache
- `modal.Function.spawn()` → synchronous processing (no background tasks needed)
- `modal.Image` → Dockerfile
- `modal.App` → standard FastAPI + uvicorn
- [ ] Keep all existing API endpoints identical:
- `POST /separate` — submit separation job
- `GET /status/{task_id}` — return job status
- `GET /download/{task_id}/{file_hash}` — download result file
- `GET /models-json`, `GET /models` — list models
- `GET /health` — health check (with model readiness indicator)
- `GET /` — root info
- [ ] Add model download on startup from GCS bucket (`gs://nomadkaraoke-audio-separator-models/`)
- [ ] Add ensemble preset support: accept `preset` parameter in `/separate` that resolves to model list + algorithm
- [ ] Add startup probe endpoint for Cloud Run GPU readiness
**Design:** Make `/separate` effectively synchronous — process inline, store results in-memory dict + local filesystem. Cloud Run instance stays alive for scale-down timeout (600s), so Stage 2 hits the same warm instance. Async polling API contract preserved for client compatibility.
#### Step 1.2 — Create Dockerfile
- [ ] Create `Dockerfile.cloudrun` in repo root
- [ ] Base: `nvidia/cuda:12.6.3-runtime-ubuntu22.04` (matches Cloud Run L4 driver support)
- [ ] Install: Python 3.13, FFmpeg, libsndfile, sox, system audio libs
- [ ] Install: `audio-separator[gpu]` from current repo
- [ ] Entrypoint: `python -m audio_separator.remote.deploy_cloudrun`
- [ ] Expose port 8080
- [ ] Set env: `MODEL_DIR=/models`, `STORAGE_DIR=/tmp/storage`
#### Step 1.3 — Upload models to GCS
- [ ] Create GCS bucket `nomadkaraoke-audio-separator-models` (us-central1, standard storage)
- [ ] Upload all models needed by default ensemble presets:
- `mel_band_roformer_instrumental_fv7z_gabox.ckpt` (instrumental_clean preset)
- `bs_roformer_instrumental_resurrection_unwa.ckpt` (instrumental_clean preset)
- `mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt` (karaoke preset)
- `mel_band_roformer_karaoke_gabox_v2.ckpt` (karaoke preset)
- `mel_band_roformer_karaoke_becruily.ckpt` (karaoke preset)
- [ ] Total: ~1-1.5 GB of models
#### Step 1.4 — Local testing
- [ ] Build Docker image locally
- [ ] Test with `docker run --gpus all` (if local GPU available) or CPU mode
- [ ] Verify API compatibility: submit job with `preset=instrumental_clean`, poll status, download files
- [ ] Verify output filename format matches expected pattern: `filename_(StemType)_modelname.ext`
- [ ] Verify ensemble output: ensembled stems have correct naming
- [ ] Compare output quality with Modal (A/B test on reference songs)
#### Step 1.5 — CI/CD for Docker image
- [ ] Create `.github/workflows/deploy-to-cloudrun.yml` in python-audio-separator repo
- [ ] Triggers: PyPI release, changes to Dockerfile.cloudrun, manual dispatch
- [ ] Steps: build Docker image → push to Artifact Registry (`us-central1-docker.pkg.dev/nomadkaraoke/audio-separator`)
- [ ] Use Workload Identity Federation for GCP auth
### Phase 2: GCP Infrastructure (karaoke-gen repo)
#### Step 2.1 — Artifact Registry
- [ ] Add Artifact Registry Docker repo to Pulumi
- [ ] Repository: `audio-separator` in `us-central1`
#### Step 2.2 — GCS Model Bucket
- [ ] Create `nomadkaraoke-audio-separator-models` bucket via Pulumi
- [ ] Standard storage class, us-central1
- [ ] Grant read access to Cloud Run service account
#### Step 2.3 — Cloud Run GPU Service
- [ ] Create `infrastructure/modules/audio_separator_service.py`
- [ ] Cloud Run Service configuration:
- Image: from Artifact Registry
- GPU: 1x NVIDIA L4
- CPU: 4 vCPU (minimum required for L4)
- Memory: 16 GiB
- Min instances: 0 (scale to zero)
- Max instances: 2 (handle concurrent jobs)
- Request timeout: 1800s (30 min)
- Scale-down delay: 600s (keep warm between Stage 1 → Stage 2)
- Startup probe: HTTP GET /health, 120s initial delay, 10s period
- Env vars:
- `MODEL_BUCKET=nomadkaraoke-audio-separator-models`
- `MODEL_DIR=/models`
- `ADMIN_TOKEN` (from Secret Manager, reuse existing `admin-tokens`)
- Region: us-central1
- Ingress: all traffic (public endpoint with auth)
#### Step 2.4 — Service Account & IAM
- [ ] Create `audio-separator` service account
- [ ] Grant: `storage.objectViewer` on model bucket
- [ ] Grant: `secretmanager.secretAccessor` for admin-tokens
- [ ] Grant: `logging.logWriter`, `monitoring.metricWriter`
#### Step 2.5 — Wire into Pulumi
- [ ] Add to `infrastructure/__main__.py`
- [ ] Add config constants to `infrastructure/config.py`
### Phase 3: Pipeline Decoupling + Model Upgrade (karaoke-gen repo)
#### Step 3.1 — Decouple separation from lyrics review path
- [ ] In `backend/services/job_manager.py`:
- Change `check_parallel_processing_complete()` to only check `lyrics_complete` (not `audio_complete`)
- `mark_lyrics_complete()` triggers screens worker on its own (no need to wait for audio)
- `mark_audio_complete()` no longer triggers screens — just sets the flag
- [ ] In `backend/workers/screens_worker.py`:
- Remove validation that `audio_complete` must be True
- Screens only needs lyrics data to generate title/end screens
- Skip instrumental analysis step if audio isn't complete yet (or make it a no-op)
- [ ] Verify: lyrics review page works without stems present
#### Step 3.2 — Add "waiting for separation" state to instrumental review
- [ ] In frontend instrumental review page (`/app/jobs#/{jobId}/instrumental`):
- Check `state_data.audio_complete` on page load
- If false, show "Audio separation in progress..." with a spinner/progress indicator
- Poll job status every 5-10 seconds until `audio_complete=True`
- Once complete, load and display instrumental options as normal
- [ ] Backend: ensure instrumental review API endpoint returns separation status
#### Step 3.3 — Switch to preset-based model configuration
- [ ] In `backend/workers/audio_worker.py`:
- Replace `DEFAULT_CLEAN_MODEL` with `DEFAULT_INSTRUMENTAL_PRESET = "instrumental_clean"`
- Replace `DEFAULT_BACKING_MODELS` with `DEFAULT_KARAOKE_PRESET = "karaoke"`
- Remove `DEFAULT_OTHER_MODELS` (Demucs dropped)
- Pass `preset=` parameter to API client instead of `models=`
- [ ] In `karaoke_gen/audio_processor.py`:
- Update `_process_audio_separation_remote()` to pass presets
- Stage 1: `api_client.separate_audio_and_wait(audio_file, preset="instrumental_clean", ...)`
- Stage 2: `api_client.separate_audio_and_wait(vocals_file, preset="karaoke", ...)`
- Remove `other_stems_models` parameter (or default to empty)
- Update result organization for ensemble outputs (stem names may include ensemble info)
- [ ] In `audio_separator/remote/api_client.py` (python-audio-separator repo):
- Add `preset` parameter to `separate_audio()` and `separate_audio_and_wait()`
- Client passes `preset` field in multipart form data to API
- API server resolves preset → models + algorithm
#### Step 3.4 — Update tests
- [ ] Update `tests/unit/test_audio_remote.py`:
- Test preset-based separation calls
- Remove Demucs 6-stem references
- Test new default model/preset names
- [ ] Add test for pipeline decoupling:
- Verify `mark_lyrics_complete()` triggers screens without `audio_complete`
- Verify `mark_audio_complete()` sets flag but doesn't trigger screens
- [ ] Add frontend test for instrumental review waiting state
### Phase 4: Cutover & Cleanup
#### Step 4.1 — Deploy and test
- [ ] Deploy Cloud Run GPU service via `pulumi up`
- [ ] Run separation on 3-5 test songs with ensemble presets
- [ ] Compare output quality to Modal (listen test)
- [ ] Verify timing: ensemble separation completes within ~8-12 min
- [ ] Test cold start scenario (wait for scale-down, then submit)
- [ ] Test back-to-back jobs (Stage 1 → Stage 2 hits warm instance)
- [ ] Test pipeline decoupling: verify lyrics review available before separation completes
- [ ] Test instrumental review waiting state
#### Step 4.2 — Update Cloud Run audio worker config
- [ ] Change `AUDIO_SEPARATOR_API_URL` in `infrastructure/modules/cloud_run.py` from Modal URL to Cloud Run URL
- [ ] Deploy via `pulumi up`
- [ ] Run 5-10 production jobs, monitor for errors
#### Step 4.3 — Monitor (1 week)
- [ ] Watch Cloud Run logs for errors
- [ ] Monitor separation timing in job state_data
- [ ] Check Cloud Run billing (verify per-job cost < $1)
- [ ] Verify scale-to-zero works (no idle GPU charges)
- [ ] Watch for users hitting the "waiting for separation" state — measure frequency
#### Step 4.4 — Decommission Modal
- [ ] Remove Modal deployment workflow from python-audio-separator repo
- [ ] Delete Modal app
- [ ] Close Modal account
- [ ] Remove `modal` from python-audio-separator dependencies
- [ ] Update `AUDIO_SEPARATOR_API_URL` env var in local `.envrc` files
## Files to Create/Modify
### python-audio-separator repo (`python-audio-separator-modal-gcp-migration` worktree)
| File | Action | Description |
|------|--------|-------------|
| `audio_separator/remote/deploy_cloudrun.py` | Create | Cloud Run-compatible FastAPI server (adapted from deploy_modal.py) |
| `audio_separator/remote/api_client.py` | Modify | Add `preset` parameter to separate methods |
| `Dockerfile.cloudrun` | Create | Docker image for Cloud Run GPU deployment |
| `.github/workflows/deploy-to-cloudrun.yml` | Create | CI/CD: build image → push to Artifact Registry |
### karaoke-gen repo (`karaoke-gen-modal-gcp-migration` worktree)
| File | Action | Description |
|------|--------|-------------|
| `infrastructure/modules/audio_separator_service.py` | Create | Pulumi: Cloud Run GPU service + model bucket + IAM |
| `infrastructure/__main__.py` | Modify | Wire up audio separator service |
| `infrastructure/config.py` | Modify | Add audio separator constants |
| `infrastructure/modules/cloud_run.py` | Modify | Update `AUDIO_SEPARATOR_API_URL` to Cloud Run URL |
| `backend/services/job_manager.py` | Modify | Decouple: lyrics_complete alone triggers screens |
| `backend/workers/screens_worker.py` | Modify | Remove audio_complete prerequisite |
| `backend/workers/audio_worker.py` | Modify | Switch to preset-based config, drop Demucs |
| `karaoke_gen/audio_processor.py` | Modify | Pass presets instead of model filenames |
| `frontend/` (instrumental review) | Modify | Add "waiting for separation" state |
| `tests/unit/test_audio_remote.py` | Modify | Update for presets, remove Demucs tests |
| `.github/workflows/deploy-audio-separator.yml` | Create | CI: deploy Cloud Run revision on image push |
## Testing Strategy
- **Unit tests:** Preset resolution, pipeline decoupling (lyrics triggers screens alone), model name updates
- **Integration test:** Deploy Cloud Run service, run full separation with ensemble presets, verify output files
- **A/B comparison:** Same songs through Modal (single model) and Cloud Run (ensemble) — quality should be better
- **Pipeline test:** Submit job, verify lyrics review available before separation completes
- **Frontend test:** Playwright E2E for instrumental review waiting state
- **Cold start test:** Wait for scale-down, submit job, measure total time
- **Production E2E:** After cutover, run 10 production jobs through full pipeline
## Cost Estimate
| Scenario | Monthly cost |
|----------|-------------|
| 10 jobs/day × 12 min GPU = 2 hrs/day | ~$40/mo |
| 30 jobs/day × 12 min GPU = 6 hrs/day | ~$120/mo |
| Per-job cost (12 min L4 @ $0.67/hr) | ~$0.13 |
Well under $1/job budget. No idle cost due to scale-to-zero.
## Resolved Questions
- [x] Cloud Run vs GCE VM → **Cloud Run GPU Service** (simplest, scale-to-zero)
- [x] Which GPU → **L4** (only option on Cloud Run, 24GB VRAM)
- [x] Model upgrade → **Ensemble presets as default** (quality > speed)
- [x] Demucs 6-stem → **Drop it**
- [x] Auth → **Reuse existing `admin-tokens` secret**
- [x] Docker CI → **python-audio-separator repo builds + pushes image**
- [x] Ensemble presets UI → **Backend-only; presets defined in audio-separator package**
- [x] Speed vs quality → **Quality wins; decouple separation from critical path so user never waits**
## Rollback Plan
1. **Quick rollback:** Change `AUDIO_SEPARATOR_API_URL` back to Modal URL in Pulumi config, `pulumi up`. Takes ~2 minutes.
2. **Pipeline rollback:** Revert job_manager changes to re-gate screens on `audio_complete`. One commit.
3. **Keep Modal running** during the monitoring period (Phase 4.3). Don't decommission until confident.
4. **Model rollback:** Preset config can be changed back to direct model filenames in one commit.
@@ -0,0 +1,431 @@
# Fix ASS Preview/Render Divergence — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Eliminate the divergence between preview and final render by unifying Word text sanitization and CorrectionResult construction, preventing embedded newlines from corrupting ASS subtitle output.
**Architecture:** Strip whitespace in `Word.__post_init__` (single source of truth for Word invariants), add defensive strip in ASS output, refactor render worker to use the shared `update_correction_result_with_data()` method, and document the lesson learned.
**Tech Stack:** Python dataclasses, ASS subtitle format, FastAPI workers
**Spec:** `docs/superpowers/specs/2026-03-22-fix-ass-preview-render-divergence-design.md`
---
## File Structure
| File | Responsibility | Change |
|------|---------------|--------|
| `karaoke_gen/lyrics_transcriber/types.py` | Word/Segment data types | Add `__post_init__` to strip text |
| `karaoke_gen/lyrics_transcriber/output/ass/lyrics_line.py` | ASS dialogue event generation | Defensive strip in `_create_ass_text()` |
| `backend/workers/render_video_worker.py` | Final video render orchestration | Use `update_correction_result_with_data()` |
| `karaoke_gen/lyrics_transcriber/correction/operations.py` | Shared correction operations | Remove redundant `.strip()` calls |
| `docs/LESSONS-LEARNED.md` | Project knowledge base | Document this bug class |
| `tests/unit/test_word_text_sanitization.py` | New test file | Word stripping + ASS output tests |
---
### Task 1: Add `__post_init__` to Word dataclass
**Files:**
- Modify: `karaoke_gen/lyrics_transcriber/types.py:7-37`
- Create: `tests/unit/test_word_text_sanitization.py`
- [ ] **Step 1: Create test file with failing tests for Word text stripping**
Create `tests/unit/test_word_text_sanitization.py`:
```python
"""Tests for Word text sanitization — ensures embedded newlines never reach ASS output."""
import pytest
from karaoke_gen.lyrics_transcriber.types import Word, LyricsSegment
class TestWordTextSanitization:
"""Word.__post_init__ must strip whitespace/newlines from text."""
def test_trailing_newline_stripped(self):
word = Word(id="w1", text="spell\n", start_time=1.0, end_time=2.0)
assert word.text == "spell"
def test_trailing_double_newline_stripped(self):
word = Word(id="w1", text="end\n\n", start_time=1.0, end_time=2.0)
assert word.text == "end"
def test_leading_whitespace_stripped(self):
word = Word(id="w1", text=" hello", start_time=1.0, end_time=2.0)
assert word.text == "hello"
def test_mixed_whitespace_stripped(self):
word = Word(id="w1", text="\n spell \n", start_time=1.0, end_time=2.0)
assert word.text == "spell"
def test_clean_text_unchanged(self):
word = Word(id="w1", text="hello", start_time=1.0, end_time=2.0)
assert word.text == "hello"
def test_from_dict_strips_text(self):
"""from_dict must also strip — this was the original bug."""
word = Word.from_dict({
"id": "w1",
"text": "spell\n",
"start_time": 1.0,
"end_time": 2.0,
})
assert word.text == "spell"
def test_from_dict_with_double_newline(self):
word = Word.from_dict({
"id": "w1",
"text": "broken\n\n",
"start_time": 1.0,
"end_time": 2.0,
})
assert word.text == "broken"
```
- [ ] **Step 2: Run tests to verify they fail**
Run: `cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run pytest tests/unit/test_word_text_sanitization.py -v`
Expected: 5 FAIL (trailing newlines not stripped), 2 PASS (clean text, leading whitespace might pass by accident)
- [ ] **Step 3: Add `__post_init__` to Word dataclass**
In `karaoke_gen/lyrics_transcriber/types.py`, add after line 17 (after `created_during_correction` field):
```python
def __post_init__(self):
"""Strip whitespace/newlines from text.
Word text from transcription pipelines may contain embedded newline
characters at segment boundaries (e.g., "spell\\n"). These corrupt ASS
subtitle output by splitting dialogue events across file lines, causing
words after the newline to be silently dropped by video renderers.
"""
self.text = self.text.strip()
```
- [ ] **Step 4: Run tests to verify they pass**
Run: `cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run pytest tests/unit/test_word_text_sanitization.py -v`
Expected: All 7 PASS
- [ ] **Step 5: Commit**
```bash
git add karaoke_gen/lyrics_transcriber/types.py tests/unit/test_word_text_sanitization.py
git commit -m "fix: strip whitespace/newlines from Word text in __post_init__
Embedded newlines in word text (e.g. 'spell\n') corrupt ASS subtitle
dialogue events by splitting them across file lines. Words after the
newline are silently dropped by the video renderer.
This was the root cause of lyrics missing in final renders but
appearing correctly in previews (job 0d4b550c)."
```
---
### Task 2: Add defensive strip in ASS output
**Files:**
- Modify: `karaoke_gen/lyrics_transcriber/output/ass/lyrics_line.py:237-262`
- Modify: `tests/unit/test_word_text_sanitization.py`
- [ ] **Step 1: Add test for ASS text generation with newline words**
Append to `tests/unit/test_word_text_sanitization.py`:
```python
from karaoke_gen.lyrics_transcriber.output.ass.lyrics_line import LyricsLine
from karaoke_gen.lyrics_transcriber.output.ass.config import ScreenConfig
class TestASSOutputSanitization:
"""ASS output must never contain literal newlines in dialogue text."""
def _make_segment(self, words_data):
"""Helper to create a LyricsSegment from word tuples (text, start, end)."""
words = [
Word(id=f"w{i}", text=text, start_time=start, end_time=end)
for i, (text, start, end) in enumerate(words_data)
]
text = " ".join(w.text for w in words)
return LyricsSegment(
id="seg1", text=text, words=words,
start_time=words[0].start_time, end_time=words[-1].end_time,
)
def test_ass_text_no_literal_newlines(self):
"""Even if Word.__post_init__ were bypassed, ASS output must not contain newlines."""
segment = self._make_segment([
("the", 54.11, 54.26),
("spell", 54.30, 55.14),
("we're", 55.18, 55.83),
("under", 55.93, 57.24),
])
config = ScreenConfig(line_height=50)
line = LyricsLine(segment=segment, screen_config=config)
# Access the private method to test ASS text generation
from datetime import timedelta
ass_text = line._create_ass_text(timedelta(seconds=54.0))
assert "\n" not in ass_text, f"ASS text contains literal newline: {repr(ass_text)}"
assert "the" in ass_text
assert "spell" in ass_text
assert "we're" in ass_text
assert "under" in ass_text
```
- [ ] **Step 2: Run test to verify it passes (Word.__post_init__ already strips)**
Run: `cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run pytest tests/unit/test_word_text_sanitization.py::TestASSOutputSanitization -v`
Expected: PASS (Word.__post_init__ already strips newlines, so this test passes with current code)
- [ ] **Step 3: Add defensive strip in `_create_ass_text()`**
In `karaoke_gen/lyrics_transcriber/output/ass/lyrics_line.py`, change line 257-258 from:
```python
# Apply case transformation to the word text
transformed_text = self._apply_case_transform(word.text)
```
to:
```python
# Apply case transformation to the word text
# Defensive strip: Word.__post_init__ should already handle this,
# but embedded newlines in ASS dialogue events cause silent word
# loss so we guard against it at the output boundary too.
clean_word_text = word.text.replace("\n", "").strip()
transformed_text = self._apply_case_transform(clean_word_text)
```
- [ ] **Step 4: Run all sanitization tests**
Run: `cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run pytest tests/unit/test_word_text_sanitization.py -v`
Expected: All PASS
- [ ] **Step 5: Commit**
```bash
git add karaoke_gen/lyrics_transcriber/output/ass/lyrics_line.py tests/unit/test_word_text_sanitization.py
git commit -m "fix: defensive strip in ASS output as safety net
Belt-and-suspenders guard at the ASS output boundary. Even though
Word.__post_init__ strips newlines, this prevents any future bypass
from producing corrupted ASS dialogue events."
```
---
### Task 3: Refactor render worker to use shared CorrectionResult construction
**Files:**
- Modify: `backend/workers/render_video_worker.py:153-188`
- [ ] **Step 1: Refactor the merge logic**
In `backend/workers/render_video_worker.py`, add the import at the top (after existing lyrics_transcriber imports around line 47):
```python
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
```
Then replace the merge logic at lines 164-188. Change from:
```python
# 3. Check if there are updated corrections (from review UI)
# The frontend sends only partial data: {corrections, corrected_segments}
updated_corrections_gcs = f"jobs/{job_id}/lyrics/corrections_updated.json"
if storage.file_exists(updated_corrections_gcs):
job_log.info("Found updated corrections from review, merging")
logger.info(f"Job {job_id}: Found updated corrections, merging")
updated_path = os.path.join(temp_dir, "corrections_updated.json")
storage.download_file(updated_corrections_gcs, updated_path)
with open(updated_path, 'r', encoding='utf-8') as f:
updated_data = json.load(f)
# Merge: update the original with the user's corrections
if 'corrections' in updated_data:
original_data['corrections'] = updated_data['corrections']
if 'corrected_segments' in updated_data:
original_data['corrected_segments'] = updated_data['corrected_segments']
job_log.info("Merged user corrections into original data")
logger.info(f"Job {job_id}: Merged user corrections into original data")
# 4. Convert to CorrectionResult
correction_result = CorrectionResult.from_dict(original_data)
job_log.info(f"Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
logger.info(f"Job {job_id}: Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
```
to:
```python
# 3. Load base CorrectionResult from original data
base_result = CorrectionResult.from_dict(original_data)
# 4. Apply user corrections if available (from review UI)
# Uses the same method as preview generation to ensure
# identical CorrectionResult construction (DRY).
updated_corrections_gcs = f"jobs/{job_id}/lyrics/corrections_updated.json"
if storage.file_exists(updated_corrections_gcs):
job_log.info("Found updated corrections from review, applying via shared method")
logger.info(f"Job {job_id}: Found updated corrections, applying via shared method")
updated_path = os.path.join(temp_dir, "corrections_updated.json")
storage.download_file(updated_corrections_gcs, updated_path)
with open(updated_path, 'r', encoding='utf-8') as f:
updated_data = json.load(f)
# Same construction path as preview — prevents divergence
correction_result = CorrectionOperations.update_correction_result_with_data(
base_result, updated_data
)
job_log.info("Applied user corrections via CorrectionOperations")
logger.info(f"Job {job_id}: Applied user corrections via CorrectionOperations")
else:
correction_result = base_result
job_log.info(f"Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
logger.info(f"Job {job_id}: Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
```
- [ ] **Step 2: Run existing tests to check for regressions**
Run: `cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run pytest tests/ -v --timeout=60 -x -q 2>&1 | tail -30`
Expected: All existing tests pass
- [ ] **Step 3: Commit**
```bash
git add backend/workers/render_video_worker.py
git commit -m "refactor: use shared CorrectionResult construction in render worker
Replace manual dict merge + from_dict() with the same
update_correction_result_with_data() method used by preview generation.
This eliminates the code path divergence that caused the preview/render
ASS subtitle discrepancy."
```
---
### Task 4: Clean up redundant `.strip()` in `update_correction_result_with_data()`
**Files:**
- Modify: `karaoke_gen/lyrics_transcriber/correction/operations.py:39-99`
- [ ] **Step 1: Remove redundant `.strip()` from Word text construction only**
In `karaoke_gen/lyrics_transcriber/correction/operations.py`, the `update_correction_result_with_data` method (lines 39-99) has `.strip()` on several text fields. Only the `Word` text strip (line 74) is now redundant thanks to `Word.__post_init__`. The others operate on `WordCorrection` fields or `LyricsSegment` text which don't have `__post_init__` — those must stay.
Change line 74 from:
```python
text=w["text"].strip(),
```
to:
```python
text=w["text"],
```
**Keep** `.strip()` on lines 47, 48, and 70 — those are `WordCorrection.original_word`, `WordCorrection.corrected_word`, and `LyricsSegment.text` respectively, which are not protected by `Word.__post_init__`.
- [ ] **Step 2: Run all tests**
Run: `cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run pytest tests/unit/test_word_text_sanitization.py -v && poetry run pytest tests/ -v --timeout=60 -x -q 2>&1 | tail -30`
Expected: All PASS
- [ ] **Step 3: Commit**
```bash
git add karaoke_gen/lyrics_transcriber/correction/operations.py
git commit -m "refactor: remove redundant .strip() from update_correction_result_with_data
Word.__post_init__ now handles text stripping. Removing the redundant
calls makes it clear that sanitization is Word's responsibility, not
the caller's."
```
---
### Task 5: Document lesson learned
**Files:**
- Modify: `docs/LESSONS-LEARNED.md`
- [ ] **Step 1: Add the lesson to the Architecture Decisions section**
In `docs/LESSONS-LEARNED.md`, add a new subsection after the existing "Architecture Decisions" entries (after line ~58). Insert:
```markdown
### Data Types Must Enforce Their Own Invariants (Mar 2026)
When a data type has constraints on its fields (e.g., "word text must not contain newlines"), enforce them in the type's constructor (`__post_init__`), not in callers. This bug was caused by `Word` objects being constructed via two different code paths — one that stripped newlines (preview) and one that didn't (final render). The preview accidentally worked while final renders had corrupted subtitles with silently dropped lyrics. The fix: `Word.__post_init__` strips whitespace so ALL construction paths are safe, plus a defensive strip at the ASS output boundary.
**Key principles:**
- **Single source of truth for data invariants** — the type, not the caller, is responsible for field constraints
- **Defensive output boundaries** — even with clean inputs, validate at system boundaries (ASS file writing) as a safety net
- **Two code paths doing "the same thing" will diverge** — if preview and render both construct CorrectionResult, they must use the same method, not reimplementations
**Detection clue:** If `corrected.txt` shows correct lyrics but the video is missing words, check for embedded newlines in Word text corrupting ASS dialogue events.
```
- [ ] **Step 2: Commit**
```bash
git add docs/LESSONS-LEARNED.md
git commit -m "docs: document data type invariant enforcement lesson
Records the Word text newline bug, the architectural principle it
violated, and detection clues for similar issues."
```
---
### Task 6: Run full test suite and verify
- [ ] **Step 1: Run the full test suite**
Run: `cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run pytest tests/ -v --timeout=120 -q 2>&1 | tail -40`
Expected: All tests pass, no regressions
- [ ] **Step 2: Verify the fix would solve the original bug**
Run a quick sanity check that Word objects with the problematic data from job `0d4b550c` are now clean:
```python
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run python -c "
from karaoke_gen.lyrics_transcriber.types import Word
# Simulate the exact data from the buggy job
w1 = Word(id='test', text='spell\n', start_time=54.30, end_time=55.14)
w2 = Word.from_dict({'id': 'test', 'text': 'broken\n\n', 'start_time': 59.98, 'end_time': 61.54})
assert w1.text == 'spell', f'Expected spell, got {repr(w1.text)}'
assert w2.text == 'broken', f'Expected broken, got {repr(w2.text)}'
print('PASS: Word text sanitization works correctly')
"
```
Expected: `PASS: Word text sanitization works correctly`
- [ ] **Step 3: Bump version**
In `pyproject.toml`, bump the patch version (this is a bugfix).
- [ ] **Step 4: Final commit with version bump**
```bash
git add pyproject.toml
git commit -m "chore: bump version for ASS preview/render divergence fix"
```
@@ -0,0 +1,99 @@
# Fix ASS Preview/Render Divergence
**Date:** 2026-03-22
**Status:** Approved
**Job that exposed bug:** `0d4b550c` (The Ataris - All Souls Day)
## Problem
Lyrics that render correctly in the preview video are missing words in the final (with_vocals / final) video output. The root cause is that Word objects contain embedded newline characters (e.g., `"spell\n"`, `"broken\n"`) inherited from the transcription pipeline's segment boundary markers. These newlines corrupt ASS subtitle dialogue events by splitting them across file lines, causing the video renderer to silently drop words after the newline.
The preview path accidentally avoids this bug because `CorrectionOperations.update_correction_result_with_data()` calls `.strip()` on word text, while the final render path uses `Word.from_dict()` which does not strip.
## Root Cause Analysis
### Two divergent CorrectionResult construction paths
**Preview** (`review.py` → `CorrectionOperations.generate_preview_video()`):
1. Downloads `corrections.json` → `CorrectionResult.from_dict()`
2. Calls `update_correction_result_with_data(result, updated_data)` which constructs new Word objects with `text=w["text"].strip()` — newlines removed
**Final render** (`render_video_worker.py`):
1. Downloads `corrections.json` + `corrections_updated.json`
2. Manually merges dicts: replaces `corrections` and `corrected_segments` keys
3. Calls `CorrectionResult.from_dict(merged_data)` which constructs Word objects with `text=data["text"]` — newlines preserved
4. Newlines in word text corrupt ASS output in `LyricsLine._create_ass_text()`
### Why only some segments are affected
Newlines appear on words at segment boundaries from the original transcription (e.g., `"spell\n"` where a line break was detected). When the segment resizer splits a long segment, a word with an embedded newline may end up in the middle of a resized segment rather than at the end. When it's at the end, the newline is harmless trailing whitespace. When it's in the middle, it splits the ASS dialogue event.
## Design
### 1. Strip in `Word.__post_init__`
Add text stripping to the Word dataclass `__post_init__` so ALL Word objects are guaranteed clean regardless of construction method:
```python
@dataclass
class Word:
...
def __post_init__(self):
# Strip whitespace/newlines — embedded newlines corrupt ASS subtitle output
self.text = self.text.strip()
```
This is the single-responsibility fix: Word is responsible for its own invariants.
### 2. Defensive strip in `_create_ass_text()`
Belt-and-suspenders safety net in the ASS output layer:
```python
# In LyricsLine._create_ass_text():
transformed_text = self._apply_case_transform(word.text.replace("\n", "").strip())
```
### 3. Refactor render_video_worker to use shared construction method
Replace the manual dict merge + `from_dict()` with `CorrectionOperations.update_correction_result_with_data()` — the same method the preview uses:
```python
# Before (render_video_worker.py):
if 'corrections' in updated_data:
original_data['corrections'] = updated_data['corrections']
if 'corrected_segments' in updated_data:
original_data['corrected_segments'] = updated_data['corrected_segments']
correction_result = CorrectionResult.from_dict(original_data)
# After:
base_result = CorrectionResult.from_dict(original_data)
correction_result = CorrectionOperations.update_correction_result_with_data(
base_result, updated_data
)
```
### 4. Clean up redundant `.strip()` in `update_correction_result_with_data()`
Since `Word.__post_init__` now handles stripping, remove the explicit `.strip()` calls in `update_correction_result_with_data()` to avoid giving the impression that stripping is the caller's responsibility.
### 5. Document the lesson learned
Add to `docs/LESSONS-LEARNED.md` documenting this class of bug and the architectural principle that prevented its recurrence.
## Files Changed
| File | Change |
|------|--------|
| `karaoke_gen/lyrics_transcriber/types.py` | Add `__post_init__` to Word, strip text |
| `karaoke_gen/lyrics_transcriber/output/ass/lyrics_line.py` | Defensive strip in `_create_ass_text()` |
| `backend/workers/render_video_worker.py` | Use `update_correction_result_with_data()` instead of manual merge |
| `karaoke_gen/lyrics_transcriber/correction/operations.py` | Remove redundant `.strip()` calls |
| `docs/LESSONS-LEARNED.md` | Document the bug and fix |
| Tests | Unit tests for Word stripping, integration test for ASS output |
## What This Does NOT Change
- The preview and final render still generate separate ASS files (necessary due to resolution-dependent positioning: 360p vs 4K)
- The data flow: frontend → GCS → worker remains the same
- No changes to the frontend
+325 -6
View File
@@ -6,8 +6,13 @@ import type {
AbuseSuspiciousUser,
AbuseRelatedResponse,
AbuseRelatedUser,
AbuseCorrelationsResponse,
AbuseFingerprintCluster,
AbuseIpCluster,
AbuseClusterUser,
} from "@/lib/api"
import { useToast } from "@/hooks/use-toast"
import { IpInfo } from "@/components/admin/ip-info"
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
@@ -265,8 +270,8 @@ function SuspiciousAccountsTab({
"-"
)}
</TableCell>
<TableCell className="font-mono text-xs">
{truncate(user.signup_ip, 15)}
<TableCell>
<IpInfo ip={user.signup_ip} compact />
</TableCell>
<TableCell className="font-mono text-xs">
{truncate(user.device_fingerprint, 10)}
@@ -295,6 +300,312 @@ function SuspiciousAccountsTab({
)
}
// =============================================================================
// Correlations Tab (primary view)
// =============================================================================
function ClusterUserRow({
user,
highlightUa,
onInvestigate,
}: {
user: AbuseClusterUser
highlightUa: boolean
onInvestigate: (email: string) => void
}) {
return (
<TableRow>
<TableCell className="font-mono text-xs max-w-[200px] truncate">
<a
href={`/admin/users/detail?email=${encodeURIComponent(user.email)}`}
className="hover:underline text-blue-400"
>
{user.email}
</a>
</TableCell>
<TableCell className="text-right font-medium">
{user.total_jobs_created}
{user.total_jobs_completed > 0 && (
<span className="text-muted-foreground text-xs ml-1">
({user.total_jobs_completed} done)
</span>
)}
</TableCell>
<TableCell className="text-right">{user.credits}</TableCell>
<TableCell className="text-right">
{user.total_spent === 0 ? (
<Badge variant="destructive" className="text-xs">$0</Badge>
) : (
formatCents(user.total_spent)
)}
</TableCell>
<TableCell>
<IpInfo ip={user.signup_ip} compact />
</TableCell>
<TableCell className="text-xs max-w-[200px] truncate" title={user.user_agent || undefined}>
{user.user_agent ? (
<span className={highlightUa ? "bg-yellow-500/20 text-yellow-300 px-1 py-0.5 rounded" : ""}>
{truncate(user.user_agent, 30)}
</span>
) : (
<span className="text-muted-foreground">-</span>
)}
</TableCell>
<TableCell className="text-xs text-muted-foreground">
{formatDate(user.created_at)}
</TableCell>
<TableCell>
<Button
variant="ghost"
size="sm"
onClick={() => onInvestigate(user.email)}
title="Investigate related accounts"
>
<ChevronRight className="w-4 h-4" />
</Button>
</TableCell>
</TableRow>
)
}
function hasMatchingUserAgents(users: AbuseClusterUser[]): boolean {
const agents = users.map((u) => u.user_agent).filter(Boolean)
if (agents.length < 2) return false
return new Set(agents).size < agents.length
}
function getMatchingUaSet(users: AbuseClusterUser[]): Set<string> {
const counts: Record<string, number> = {}
for (const u of users) {
if (u.user_agent) {
counts[u.user_agent] = (counts[u.user_agent] || 0) + 1
}
}
return new Set(Object.keys(counts).filter((ua) => counts[ua] > 1))
}
function FingerprintClusterCard({
cluster,
onInvestigate,
}: {
cluster: AbuseFingerprintCluster
onInvestigate: (email: string) => void
}) {
const [expanded, setExpanded] = useState(true)
const uaMatches = hasMatchingUserAgents(cluster.users)
const matchingUas = getMatchingUaSet(cluster.users)
return (
<Card className="border-red-500/30">
<CardHeader className="pb-3 cursor-pointer" onClick={() => setExpanded(!expanded)}>
<CardTitle className="text-base flex items-center gap-2">
<Fingerprint className="w-4 h-4 text-red-500" />
<Badge variant="destructive" className="text-xs">{cluster.count} accounts</Badge>
<code className="text-xs bg-muted px-1.5 py-0.5 rounded font-mono">{cluster.fingerprint}</code>
{uaMatches && (
<Badge className="text-xs bg-yellow-500/20 text-yellow-300 border-yellow-500/30">
matching UA
</Badge>
)}
<ChevronRight className={`w-4 h-4 ml-auto transition-transform ${expanded ? "rotate-90" : ""}`} />
</CardTitle>
</CardHeader>
{expanded && (
<CardContent>
<div className="border rounded-lg overflow-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead>Email</TableHead>
<TableHead className="text-right">Jobs</TableHead>
<TableHead className="text-right">Credits</TableHead>
<TableHead className="text-right">Spent</TableHead>
<TableHead>Signup IP</TableHead>
<TableHead>User Agent</TableHead>
<TableHead>Created</TableHead>
<TableHead></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{cluster.users.map((user) => (
<ClusterUserRow
key={user.email}
user={user}
highlightUa={!!user.user_agent && matchingUas.has(user.user_agent)}
onInvestigate={onInvestigate}
/>
))}
</TableBody>
</Table>
</div>
</CardContent>
)}
</Card>
)
}
function IpClusterCard({
cluster,
onInvestigate,
}: {
cluster: AbuseIpCluster
onInvestigate: (email: string) => void
}) {
const [expanded, setExpanded] = useState(true)
const uaMatches = hasMatchingUserAgents(cluster.users)
const matchingUas = getMatchingUaSet(cluster.users)
return (
<Card className="border-orange-500/30">
<CardHeader className="pb-3 cursor-pointer" onClick={() => setExpanded(!expanded)}>
<CardTitle className="text-base flex items-center gap-2">
<Globe className="w-4 h-4 text-orange-500" />
<Badge className="text-xs bg-orange-500/20 text-orange-300 border-orange-500/30">
{cluster.count} accounts
</Badge>
<IpInfo ip={cluster.ip} compact />
{uaMatches && (
<Badge className="text-xs bg-yellow-500/20 text-yellow-300 border-yellow-500/30">
matching UA
</Badge>
)}
<ChevronRight className={`w-4 h-4 ml-auto transition-transform ${expanded ? "rotate-90" : ""}`} />
</CardTitle>
</CardHeader>
{expanded && (
<CardContent>
<div className="border rounded-lg overflow-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead>Email</TableHead>
<TableHead className="text-right">Jobs</TableHead>
<TableHead className="text-right">Credits</TableHead>
<TableHead className="text-right">Spent</TableHead>
<TableHead>Signup IP</TableHead>
<TableHead>User Agent</TableHead>
<TableHead>Created</TableHead>
<TableHead></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{cluster.users.map((user) => (
<ClusterUserRow
key={user.email}
user={user}
highlightUa={!!user.user_agent && matchingUas.has(user.user_agent)}
onInvestigate={onInvestigate}
/>
))}
</TableBody>
</Table>
</div>
</CardContent>
)}
</Card>
)
}
function CorrelationsTab({
onInvestigate,
}: {
onInvestigate: (email: string) => void
}) {
const { toast } = useToast()
const [data, setData] = useState<AbuseCorrelationsResponse | null>(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
const load = async () => {
try {
setLoading(true)
const result = await adminApi.getAbuseCorrelations()
setData(result)
} catch (err: any) {
toast({ title: "Error", description: err.message, variant: "destructive" })
} finally {
setLoading(false)
}
}
load()
}, [])
if (loading) {
return (
<div className="flex justify-center py-12">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
)
}
if (!data) return null
const totalFpAccounts = data.fingerprint_clusters.reduce((sum: number, c: AbuseFingerprintCluster) => sum + c.count, 0)
const totalIpAccounts = data.ip_clusters.reduce((sum: number, c: AbuseIpCluster) => sum + c.count, 0)
return (
<div className="space-y-6">
{/* Fingerprint clusters */}
<div className="space-y-4">
<div className="flex items-center gap-2">
<Fingerprint className="w-5 h-5 text-red-500" />
<h3 className="text-lg font-semibold">Shared Fingerprints</h3>
<Badge variant="destructive" className="text-xs">
{data.fingerprint_clusters.length} cluster{data.fingerprint_clusters.length !== 1 ? "s" : ""} ({totalFpAccounts} accounts)
</Badge>
</div>
<p className="text-sm text-muted-foreground">
Multiple accounts sharing the same device fingerprint — strong indicator of multi-accounting.
</p>
{data.fingerprint_clusters.length === 0 ? (
<Card>
<CardContent className="py-6 text-center text-muted-foreground">
No shared fingerprint clusters found.
</CardContent>
</Card>
) : (
data.fingerprint_clusters.map((cluster) => (
<FingerprintClusterCard
key={cluster.fingerprint}
cluster={cluster}
onInvestigate={onInvestigate}
/>
))
)}
</div>
{/* IP clusters */}
<div className="space-y-4">
<div className="flex items-center gap-2">
<Globe className="w-5 h-5 text-orange-500" />
<h3 className="text-lg font-semibold">Shared Signup IPs</h3>
<Badge className="text-xs bg-orange-500/20 text-orange-300 border-orange-500/30">
{data.ip_clusters.length} cluster{data.ip_clusters.length !== 1 ? "s" : ""} ({totalIpAccounts} accounts)
</Badge>
</div>
<p className="text-sm text-muted-foreground">
Multiple accounts from the same IP address — suspicious but could be a shared network (school, office, VPN).
</p>
{data.ip_clusters.length === 0 ? (
<Card>
<CardContent className="py-6 text-center text-muted-foreground">
No shared IP clusters found.
</CardContent>
</Card>
) : (
data.ip_clusters.map((cluster) => (
<IpClusterCard
key={cluster.ip}
cluster={cluster}
onInvestigate={onInvestigate}
/>
))
)}
</div>
</div>
)
}
// =============================================================================
// Related Accounts Detail View
// =============================================================================
@@ -381,7 +692,7 @@ function RelatedAccountsView({
</div>
<div className="col-span-2">
<span className="text-muted-foreground">Signup IP:</span>{" "}
<code className="text-xs bg-muted px-1.5 py-0.5 rounded">{user.signup_ip || "unknown"}</code>
<IpInfo ip={user.signup_ip} />
</div>
<div className="col-span-2">
<span className="text-muted-foreground">Fingerprint:</span>{" "}
@@ -390,7 +701,7 @@ function RelatedAccountsView({
</div>
<div className="mt-3">
<Button variant="outline" size="sm" asChild>
<a href={`/admin/users/${encodeURIComponent(email)}`}>
<a href={`/admin/users/detail?email=${encodeURIComponent(email)}`}>
<ExternalLink className="w-3 h-3 mr-1" />
View full user profile
</a>
@@ -623,7 +934,7 @@ function LookupTab({
formatCents(user.total_spent)
)}
</TableCell>
<TableCell className="font-mono text-xs">{truncate(user.signup_ip, 15)}</TableCell>
<TableCell><IpInfo ip={user.signup_ip} compact /></TableCell>
<TableCell className="font-mono text-xs">{truncate(user.device_fingerprint, 10)}</TableCell>
<TableCell className="text-xs text-muted-foreground">
{formatDate(user.created_at)}
@@ -655,7 +966,7 @@ function LookupTab({
// =============================================================================
export default function AbuseInvestigationPage() {
const [activeTab, setActiveTab] = useState("suspicious")
const [activeTab, setActiveTab] = useState("correlations")
const [investigatingEmail, setInvestigatingEmail] = useState<string | null>(null)
const handleInvestigate = (email: string) => {
@@ -688,6 +999,10 @@ export default function AbuseInvestigationPage() {
<Tabs value={activeTab} onValueChange={setActiveTab}>
<TabsList>
<TabsTrigger value="correlations">
<Users className="w-4 h-4 mr-1" />
Correlations
</TabsTrigger>
<TabsTrigger value="suspicious">
<AlertTriangle className="w-4 h-4 mr-1" />
Suspicious
@@ -698,6 +1013,10 @@ export default function AbuseInvestigationPage() {
</TabsTrigger>
</TabsList>
<TabsContent value="correlations" className="space-y-6">
<CorrelationsTab onInvestigate={handleInvestigate} />
</TabsContent>
<TabsContent value="suspicious" className="space-y-6">
<SuspiciousAccountsTab onInvestigate={handleInvestigate} />
</TabsContent>
+320
View File
@@ -0,0 +1,320 @@
"use client"
import { Fragment, useEffect, useState, useCallback } from "react"
import { adminApi, AdminFeedbackItem, AdminFeedbackListResponse } from "@/lib/api"
import { useAdminSettings } from "@/lib/admin-settings"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import {
Search,
Loader2,
RefreshCw,
ChevronLeft,
ChevronRight,
ChevronDown,
ChevronUp,
Star,
ThumbsUp,
ThumbsDown,
} from "lucide-react"
import { toast } from "sonner"
const PAGE_SIZE = 50
function StarRating({ rating }: { rating: number }) {
return (
<span className="inline-flex items-center gap-0.5" title={`${rating}/5`}>
{[1, 2, 3, 4, 5].map((i) => (
<Star
key={i}
className={`w-3.5 h-3.5 ${
i <= rating
? "fill-yellow-400 text-yellow-400"
: "text-muted-foreground/30"
}`}
/>
))}
</span>
)
}
function formatDate(dateStr: string | null) {
if (!dateStr) return "—"
try {
return new Date(dateStr).toLocaleDateString("en-US", {
month: "short",
day: "numeric",
year: "numeric",
hour: "numeric",
minute: "2-digit",
})
} catch {
return dateStr
}
}
function ExpandableText({ label, text }: { label: string; text: string | null }) {
if (!text) return null
return (
<div className="mb-2">
<span className="text-xs font-medium text-muted-foreground">{label}</span>
<p className="text-sm whitespace-pre-wrap">{text}</p>
</div>
)
}
export default function AdminFeedbackPage() {
const { showTestData } = useAdminSettings()
const [data, setData] = useState<AdminFeedbackListResponse | null>(null)
const [loading, setLoading] = useState(true)
const [search, setSearch] = useState("")
const [searchInput, setSearchInput] = useState("")
const [offset, setOffset] = useState(0)
const [expandedId, setExpandedId] = useState<string | null>(null)
const fetchFeedback = useCallback(async () => {
setLoading(true)
try {
const result = await adminApi.listFeedback({
limit: PAGE_SIZE,
offset,
search: search || undefined,
exclude_test: !showTestData,
})
setData(result)
} catch (err) {
toast.error("Failed to load feedback")
console.error(err)
} finally {
setLoading(false)
}
}, [offset, search, showTestData])
useEffect(() => {
fetchFeedback()
}, [fetchFeedback])
const handleSearch = () => {
setOffset(0)
setSearch(searchInput)
}
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === "Enter") handleSearch()
}
const toggleExpand = (id: string) => {
setExpandedId(expandedId === id ? null : id)
}
const hasTextContent = (item: AdminFeedbackItem) =>
item.what_went_well || item.what_could_improve || item.additional_comments
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold">User Feedback</h1>
<Button variant="outline" size="sm" onClick={fetchFeedback} disabled={loading}>
<RefreshCw className={`w-4 h-4 mr-2 ${loading ? "animate-spin" : ""}`} />
Refresh
</Button>
</div>
{/* Aggregate stats */}
{data && data.total > 0 && (
<div className="grid grid-cols-2 md:grid-cols-5 gap-4">
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
Total Responses
</CardTitle>
</CardHeader>
<CardContent>
<p className="text-2xl font-bold">{data.total}</p>
</CardContent>
</Card>
{[
{ label: "Overall", value: data.avg_overall_rating },
{ label: "Ease of Use", value: data.avg_ease_of_use_rating },
{ label: "Lyrics Accuracy", value: data.avg_lyrics_accuracy_rating },
{ label: "Correction Exp.", value: data.avg_correction_experience_rating },
].map(({ label, value }) => (
<Card key={label}>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
Avg {label}
</CardTitle>
</CardHeader>
<CardContent>
<div className="flex items-center gap-2">
<p className="text-2xl font-bold">
{value != null ? value.toFixed(1) : "—"}
</p>
<span className="text-muted-foreground text-sm">/ 5</span>
</div>
</CardContent>
</Card>
))}
</div>
)}
{/* Search */}
<div className="flex gap-2">
<Input
placeholder="Search by email..."
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
onKeyDown={handleKeyDown}
className="max-w-sm"
/>
<Button variant="outline" onClick={handleSearch}>
<Search className="w-4 h-4 mr-2" />
Search
</Button>
</div>
{/* Table */}
<Card>
<CardContent className="p-0">
{loading ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
) : !data || data.items.length === 0 ? (
<div className="text-center py-12 text-muted-foreground">
No feedback submissions found.
</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-8"></TableHead>
<TableHead>User</TableHead>
<TableHead>Date</TableHead>
<TableHead>Overall</TableHead>
<TableHead>Ease of Use</TableHead>
<TableHead>Lyrics</TableHead>
<TableHead>Correction</TableHead>
<TableHead>Recommend</TableHead>
<TableHead>Use Again</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.items.map((item) => (
<Fragment key={item.id}>
<TableRow
className={`cursor-pointer hover:bg-muted/50 ${
expandedId === item.id ? "bg-muted/30" : ""
}`}
onClick={() => toggleExpand(item.id)}
>
<TableCell className="w-8">
{hasTextContent(item) && (
expandedId === item.id
? <ChevronUp className="w-4 h-4 text-muted-foreground" />
: <ChevronDown className="w-4 h-4 text-muted-foreground" />
)}
</TableCell>
<TableCell className="font-mono text-sm">
{item.user_email}
</TableCell>
<TableCell className="text-sm text-muted-foreground whitespace-nowrap">
{formatDate(item.created_at)}
</TableCell>
<TableCell>
<StarRating rating={item.overall_rating} />
</TableCell>
<TableCell>
<StarRating rating={item.ease_of_use_rating} />
</TableCell>
<TableCell>
<StarRating rating={item.lyrics_accuracy_rating} />
</TableCell>
<TableCell>
<StarRating rating={item.correction_experience_rating} />
</TableCell>
<TableCell>
{item.would_recommend ? (
<Badge variant="secondary" className="bg-green-500/10 text-green-600">
<ThumbsUp className="w-3 h-3 mr-1" />
Yes
</Badge>
) : (
<Badge variant="secondary" className="bg-red-500/10 text-red-600">
<ThumbsDown className="w-3 h-3 mr-1" />
No
</Badge>
)}
</TableCell>
<TableCell>
{item.would_use_again ? (
<Badge variant="secondary" className="bg-green-500/10 text-green-600">
<ThumbsUp className="w-3 h-3 mr-1" />
Yes
</Badge>
) : (
<Badge variant="secondary" className="bg-red-500/10 text-red-600">
<ThumbsDown className="w-3 h-3 mr-1" />
No
</Badge>
)}
</TableCell>
</TableRow>
{expandedId === item.id && hasTextContent(item) && (
<TableRow>
<TableCell colSpan={9} className="bg-muted/20 px-8 py-4">
<ExpandableText label="What went well" text={item.what_went_well} />
<ExpandableText label="What could improve" text={item.what_could_improve} />
<ExpandableText label="Additional comments" text={item.additional_comments} />
</TableCell>
</TableRow>
)}
</Fragment>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
{/* Pagination */}
{data && data.total > PAGE_SIZE && (
<div className="flex items-center justify-between">
<p className="text-sm text-muted-foreground">
Showing {offset + 1}–{Math.min(offset + PAGE_SIZE, data.total)} of {data.total}
</p>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
disabled={offset === 0}
onClick={() => setOffset(Math.max(0, offset - PAGE_SIZE))}
>
<ChevronLeft className="w-4 h-4 mr-1" />
Previous
</Button>
<Button
variant="outline"
size="sm"
disabled={!data.has_more}
onClick={() => setOffset(offset + PAGE_SIZE)}
>
Next
<ChevronRight className="w-4 h-4 ml-1" />
</Button>
</div>
</div>
)}
</div>
)
}
@@ -28,6 +28,8 @@ jest.mock("@/lib/api", () => ({
getYouTubeQueue: jest.fn(),
retryYouTubeUpload: jest.fn(),
processYouTubeQueue: jest.fn(),
getIpInfo: jest.fn().mockResolvedValue({ status: "success", ip: "192.168.1.100", country_code: "US", isp: "Test ISP" }),
getIpInfoBatch: jest.fn().mockResolvedValue({}),
},
}))
+2 -1
View File
@@ -38,6 +38,7 @@ import {
X,
} from "lucide-react"
import { useToast } from "@/hooks/use-toast"
import { IpInfo } from "@/components/admin/ip-info"
export default function AdminRateLimitsPage() {
const { toast } = useToast()
@@ -704,7 +705,7 @@ export default function AdminRateLimitsPage() {
<div className="flex flex-wrap gap-2 p-3">
{filteredIPs.map((ip) => (
<Badge key={ip} variant="destructive" className="flex items-center gap-1">
{ip}
<IpInfo ip={ip} compact />
<button
onClick={() => handleRemoveIP(ip)}
className="ml-1 hover:text-white cursor-pointer"
+4 -3
View File
@@ -50,6 +50,7 @@ import {
} from "lucide-react"
import { useToast } from "@/hooks/use-toast"
import { useAuth } from "@/lib/auth"
import { IpInfo } from "@/components/admin/ip-info"
export default function AdminUserDetailPage() {
const searchParams = useSearchParams()
@@ -433,9 +434,9 @@ export default function AdminUserDetailPage() {
<CardTitle>Identity & Security</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div className="flex justify-between">
<div className="flex justify-between items-center">
<span className="text-muted-foreground">Signup IP</span>
<code className="text-xs bg-muted px-1.5 py-0.5 rounded">{user.signup_ip || "unknown"}</code>
<IpInfo ip={user.signup_ip} />
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Device Fingerprint</span>
@@ -453,7 +454,7 @@ export default function AdminUserDetailPage() {
<div className="space-y-2">
{user.recent_sessions.map((s, i) => (
<div key={i} className="text-xs bg-muted rounded p-2 space-y-1">
<div><span className="text-muted-foreground">IP:</span> {s.ip_address || "unknown"}</div>
<div className="flex items-center gap-1"><span className="text-muted-foreground">IP:</span> <IpInfo ip={s.ip_address} compact /></div>
{s.device_fingerprint && <div><span className="text-muted-foreground">Fingerprint:</span> {s.device_fingerprint}</div>}
{s.user_agent && <div className="truncate"><span className="text-muted-foreground">UA:</span> {s.user_agent}</div>}
<div><span className="text-muted-foreground">Last active:</span> {s.last_activity_at ? new Date(s.last_activity_at).toLocaleString() : "unknown"}</div>
+1 -1
View File
@@ -335,7 +335,7 @@ function AppPageContent() {
<div className="flex items-center gap-3 min-w-0">
<Gift className="w-5 h-5 text-green-500 shrink-0" />
<p className="text-sm" style={{ color: 'var(--text)' }}>
<strong>Earn 2 free credits!</strong>{' '}
<strong>Earn 1 free credit!</strong>{' '}
<span style={{ color: 'var(--text-muted)' }}>
Share your feedback on the karaoke creation experience.
</span>
+148 -25
View File
@@ -2,24 +2,24 @@
import { Suspense, useEffect, useState, useRef } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { Loader2, CheckCircle, XCircle } from "lucide-react"
import { Loader2, CheckCircle, XCircle, Gift, ShoppingCart } from "lucide-react"
import { Button } from "@/components/ui/button"
import { useAuth } from "@/lib/auth"
type VerifyState = "loading" | "success" | "error"
type VerifyState = "verifying" | "preparing" | "credits_granted" | "credits_denied" | "credits_pending" | "success" | "error"
function VerifyMagicLinkContent() {
const router = useRouter()
const searchParams = useSearchParams()
const [state, setState] = useState<VerifyState>("loading")
const [state, setState] = useState<VerifyState>("verifying")
const [errorMessage, setErrorMessage] = useState("")
const [creditsGranted, setCreditsGranted] = useState(0)
const [creditStatus, setCreditStatus] = useState<string>("not_applicable")
const hasVerified = useRef(false)
const { verifyMagicLink, user, error } = useAuth()
useEffect(() => {
// Prevent duplicate verification attempts
if (hasVerified.current) return
hasVerified.current = true
@@ -31,36 +31,47 @@ function VerifyMagicLinkContent() {
return
}
// Verify the token
const verify = async () => {
// Show "preparing your account" while the backend runs AI evaluation
setState("preparing")
const success = await verifyMagicLink(token)
if (success) {
setState("success")
// Check verify response for welcome credits and tenant redirect
const lastVerifyResponse = (window as any).__LAST_VERIFY_RESPONSE__
if (lastVerifyResponse?.credits_granted > 0) {
setCreditsGranted(lastVerifyResponse.credits_granted)
}
// Check if the verify response included a tenant subdomain
// If we're on the wrong domain, redirect to the correct tenant portal
const credits = lastVerifyResponse?.credits_granted || 0
const status = lastVerifyResponse?.credit_status || "not_applicable"
setCreditsGranted(credits)
setCreditStatus(status)
// Check for tenant subdomain redirect
if (lastVerifyResponse?.tenant_subdomain) {
const currentHost = window.location.hostname.toLowerCase()
const tenantSubdomain = lastVerifyResponse.tenant_subdomain.toLowerCase()
if (currentHost !== tenantSubdomain) {
// We're on the wrong domain — redirect to the correct tenant portal
setState("success")
setTimeout(() => {
window.location.href = `https://${tenantSubdomain}/app`
}, 1500)
return
}
}
// Same domain or no tenant — redirect normally
setTimeout(() => {
router.push("/app")
}, 2000)
// Show appropriate interstitial based on credit status
if (status === "granted" && credits > 0) {
setState("credits_granted")
} else if (status === "denied") {
setState("credits_denied")
} else if (status === "pending_review") {
setState("credits_pending")
} else {
// Returning user or not applicable — go straight to app
setState("success")
setTimeout(() => {
router.push("/app")
}, 1500)
}
} else {
setState("error")
// Get error from auth store at this point
const authStore = useAuth.getState()
setErrorMessage(authStore.error || "Invalid or expired link")
}
@@ -69,9 +80,13 @@ function VerifyMagicLinkContent() {
verify()
}, [searchParams, verifyMagicLink, router])
const goToApp = () => router.push("/app")
const goToBuy = () => router.push("/app?buy=true")
return (
<div className="max-w-md w-full bg-card border border-border rounded-xl p-8 text-center">
{state === "loading" && (
{/* Verifying token */}
{state === "verifying" && (
<>
<Loader2 className="w-12 h-12 text-primary animate-spin mx-auto mb-4" />
<h1 className="text-xl font-semibold text-foreground mb-2">
@@ -83,6 +98,118 @@ function VerifyMagicLinkContent() {
</>
)}
{/* Preparing account (AI evaluation running) */}
{state === "preparing" && (
<>
<Loader2 className="w-12 h-12 text-primary animate-spin mx-auto mb-4" />
<h1 className="text-xl font-semibold text-foreground mb-2">
Preparing your account...
</h1>
<p className="text-muted-foreground">
Just a moment while we set things up for you.
</p>
</>
)}
{/* Credits granted - celebratory interstitial */}
{state === "credits_granted" && (
<>
<div className="relative mx-auto mb-4 w-16 h-16">
<Gift className="w-16 h-16 text-primary" />
</div>
<h1 className="text-2xl font-bold text-foreground mb-2">
Welcome to Nomad Karaoke!
</h1>
<div className="bg-primary/10 border border-primary/20 rounded-lg p-4 mb-4">
<p className="text-3xl font-bold text-primary">{creditsGranted}</p>
<p className="text-sm font-medium text-primary/80">free credits to get started</p>
</div>
<p className="text-sm text-muted-foreground mb-2">
Each credit creates one professional karaoke video.
</p>
<p className="text-xs text-muted-foreground mb-6">
These credits cost us real money to fulfil, so please use them wisely
and let us know what you think!
</p>
<Button
onClick={goToApp}
className="w-full bg-primary hover:bg-primary/90"
>
Start Creating Karaoke
</Button>
</>
)}
{/* Credits denied - friendly rejection interstitial */}
{state === "credits_denied" && (
<>
<XCircle className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
<h1 className="text-xl font-semibold text-foreground mb-2">
Welcome to Nomad Karaoke
</h1>
<p className="text-muted-foreground mb-4">
We weren&apos;t able to grant free credits this time.
Karaoke generation costs us real money for every job,
so we need to be careful about free credit distribution.
</p>
<p className="text-sm text-muted-foreground mb-6">
If you think this is a mistake, check your email — we&apos;ve sent you
details on how to reach out to get this resolved.
</p>
<div className="space-y-2">
<Button
onClick={goToBuy}
className="w-full bg-primary hover:bg-primary/90"
>
<ShoppingCart className="w-4 h-4 mr-2" />
Buy Credits
</Button>
<Button
onClick={goToApp}
variant="ghost"
className="w-full"
>
Go to Dashboard
</Button>
</div>
</>
)}
{/* Credits pending review - friendly holding message */}
{state === "credits_pending" && (
<>
<Loader2 className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
<h1 className="text-xl font-semibold text-foreground mb-2">
Welcome to Nomad Karaoke!
</h1>
<p className="text-muted-foreground mb-4">
We weren&apos;t able to assign your free credits automatically this time.
Our team will review your signup shortly and assign credits if we&apos;re able to.
</p>
<p className="text-sm text-muted-foreground mb-6">
You can still explore the app while you wait, or purchase credits
to get started right away.
</p>
<div className="space-y-2">
<Button
onClick={goToBuy}
className="w-full bg-primary hover:bg-primary/90"
>
<ShoppingCart className="w-4 h-4 mr-2" />
Buy Credits
</Button>
<Button
onClick={goToApp}
variant="ghost"
className="w-full"
>
Explore the App
</Button>
</div>
</>
)}
{/* Simple success (returning user) */}
{state === "success" && (
<>
<CheckCircle className="w-12 h-12 text-success mx-auto mb-4" />
@@ -90,19 +217,15 @@ function VerifyMagicLinkContent() {
Successfully signed in!
</h1>
<p className="text-muted-foreground mb-4">
Welcome{user?.email ? `, ${user.email}` : ""}!
Welcome back{user?.email ? `, ${user.email}` : ""}!
</p>
{creditsGranted > 0 && (
<p className="text-sm font-medium text-primary mb-4">
You received {creditsGranted} free credits to get started!
</p>
)}
<p className="text-sm text-muted-foreground">
Redirecting you to the app...
</p>
</>
)}
{/* Error */}
{state === "error" && (
<>
<XCircle className="w-12 h-12 text-destructive mx-auto mb-4" />
+28
View File
@@ -67,6 +67,16 @@
--input: var(--secondary);
--ring: var(--primary);
--radius: 0.5rem;
/* Sidebar colors (admin panel) */
--sidebar: #1a1a1a;
--sidebar-foreground: var(--text);
--sidebar-primary: var(--primary);
--sidebar-primary-foreground: #ffffff;
--sidebar-accent: #252525;
--sidebar-accent-foreground: var(--text);
--sidebar-border: var(--card-border);
--sidebar-ring: var(--primary);
}
.light {
@@ -98,6 +108,16 @@
--muted-foreground: var(--text-muted);
--border: var(--card-border);
--input: var(--secondary);
/* Sidebar colors - light mode */
--sidebar: #ffffff;
--sidebar-foreground: var(--text);
--sidebar-primary: var(--primary);
--sidebar-primary-foreground: #ffffff;
--sidebar-accent: #f1f5f9;
--sidebar-accent-foreground: var(--text);
--sidebar-border: var(--card-border);
--sidebar-ring: var(--primary);
}
@theme inline {
@@ -126,6 +146,14 @@
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
}
@layer base {
+3 -3
View File
@@ -262,7 +262,7 @@ function ConsumerLandingPage() {
Create It Yourself
<span className="ml-1 px-2 py-0.5 bg-white/20 rounded-full text-sm">$5</span>
</button>
<span className="text-green-400 text-sm">2 free credits included - no payment required</span>
<span className="text-green-400 text-sm">1 free credit included - no payment required</span>
</div>
<div className="flex flex-col items-center gap-2">
<a
@@ -451,12 +451,12 @@ function ConsumerLandingPage() {
<div className="max-w-4xl mx-auto">
<h2 className="text-3xl font-bold text-center mb-4">Simple Pricing</h2>
<p className="text-dark-400 text-center mb-4 max-w-xl mx-auto">
Start with 2 free credits, then buy more to save more.
Start with 1 free credit, then buy more to save more.
</p>
<div className="bg-green-500/10 border border-green-500/30 rounded-2xl p-6 text-center mb-10 max-w-sm mx-auto">
<div className="text-sm text-green-400 font-medium mb-1">Every new account includes</div>
<div className="text-4xl font-bold text-green-400 mb-1">2 Free Credits</div>
<div className="text-4xl font-bold text-green-400 mb-1">1 Free Credit</div>
<div className="text-sm text-dark-400 mb-4">No payment required</div>
<button
onClick={() => setShowAuthDialog(true)}
@@ -14,6 +14,7 @@ import {
BookOpenCheck,
Scissors,
Fingerprint,
MessageSquare,
} from "lucide-react"
import {
@@ -71,6 +72,11 @@ const navItems = [
href: "/admin/audio-edits",
icon: Scissors,
},
{
title: "Feedback",
href: "/admin/feedback",
icon: MessageSquare,
},
{
title: "Abuse Investigation",
href: "/admin/abuse",
+149
View File
@@ -0,0 +1,149 @@
"use client"
import { useEffect, useState } from "react"
import { fetchIpInfo, countryCodeToFlag } from "@/lib/ip-geolocation"
import type { IpGeoInfo } from "@/lib/api"
import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
} from "@/components/ui/hover-card"
import { Globe } from "lucide-react"
/**
* Inline IP address display with geolocation enrichment.
*
* Shows the raw IP plus a compact summary (flag + country + ISP).
* Hover to see full details (city, region, ASN, timezone).
*
* Usage: <IpInfo ip="8.8.8.8" />
*/
export function IpInfo({
ip,
compact = false,
}: {
ip: string | null | undefined
compact?: boolean
}) {
const [geo, setGeo] = useState<IpGeoInfo | null>(null)
const [loading, setLoading] = useState(false)
useEffect(() => {
if (!ip) return
setLoading(true)
fetchIpInfo(ip).then((result) => {
setGeo(result)
setLoading(false)
})
}, [ip])
if (!ip) {
return <span className="text-muted-foreground text-xs">-</span>
}
const hasGeo = geo && geo.status === "success"
const flag = hasGeo ? countryCodeToFlag(geo.country_code || "") : ""
const ispShort = hasGeo && geo.isp ? truncateIsp(geo.isp) : ""
// Inline summary
const summary = hasGeo ? (
<span className="text-muted-foreground text-xs ml-1">
{flag} {geo.country_code}
{ispShort && <span className="hidden sm:inline"> · {ispShort}</span>}
</span>
) : loading ? (
<span className="text-muted-foreground text-xs ml-1 animate-pulse">...</span>
) : null
if (compact) {
// Compact mode: just flag + country code, no IP shown
if (!hasGeo) return <span className="font-mono text-xs">{ip}</span>
return (
<HoverCard openDelay={200}>
<HoverCardTrigger asChild>
<span className="cursor-help font-mono text-xs">
{ip} {summary}
</span>
</HoverCardTrigger>
<HoverCardContent className="w-72" side="top">
<IpGeoDetails ip={ip} geo={geo} />
</HoverCardContent>
</HoverCard>
)
}
return (
<HoverCard openDelay={200}>
<HoverCardTrigger asChild>
<span className="cursor-help inline-flex items-center gap-0.5">
<code className="text-xs bg-muted px-1.5 py-0.5 rounded font-mono">{ip}</code>
{summary}
</span>
</HoverCardTrigger>
<HoverCardContent className="w-72" side="top">
<IpGeoDetails ip={ip} geo={geo} />
</HoverCardContent>
</HoverCard>
)
}
function IpGeoDetails({
ip,
geo,
}: {
ip: string
geo: IpGeoInfo | null
}) {
if (!geo || geo.status !== "success") {
return (
<div className="text-sm">
<div className="flex items-center gap-2 mb-2">
<Globe className="w-4 h-4 text-muted-foreground" />
<span className="font-medium">{ip}</span>
</div>
<p className="text-xs text-muted-foreground">
{geo?.status === "private" ? "Private/reserved IP" :
geo?.status === "error" ? "Lookup failed" :
"No geolocation data available"}
</p>
</div>
)
}
const flag = countryCodeToFlag(geo.country_code || "")
return (
<div className="text-sm space-y-1.5">
<div className="flex items-center gap-2 mb-2">
<Globe className="w-4 h-4 text-muted-foreground" />
<span className="font-medium font-mono">{ip}</span>
</div>
<DetailRow label="Country" value={`${flag} ${geo.country} (${geo.country_code})`} />
{geo.region && <DetailRow label="Region" value={geo.region} />}
{geo.city && <DetailRow label="City" value={geo.city} />}
{geo.isp && <DetailRow label="ISP" value={geo.isp} />}
{geo.org && geo.org !== geo.isp && <DetailRow label="Org" value={geo.org} />}
{geo.as_number && (
<DetailRow label="ASN" value={`${geo.as_number}${geo.as_name ? ` (${geo.as_name})` : ""}`} />
)}
{geo.timezone && <DetailRow label="Timezone" value={geo.timezone} />}
</div>
)
}
function DetailRow({ label, value }: { label: string; value: string }) {
return (
<div className="flex justify-between gap-2">
<span className="text-muted-foreground text-xs">{label}</span>
<span className="text-xs text-right">{value}</span>
</div>
)
}
function truncateIsp(isp: string): string {
// Remove common suffixes to keep it short
const cleaned = isp
.replace(/,?\s*(Inc|LLC|Ltd|Corp|Corporation|Co\.|Company|Telecommunications|Telecom)\.?$/i, "")
.trim()
return cleaned.length > 20 ? cleaned.slice(0, 20) + "..." : cleaned
}
+1 -1
View File
@@ -114,7 +114,7 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
className="text-green-500 focus:text-green-400 focus:bg-secondary"
>
<Gift className="w-4 h-4 mr-2" />
<span>Earn 2 Free Credits</span>
<span>Earn 1 Free Credit</span>
</DropdownMenuItem>
)}
{(user.role === "admin" || user.email?.endsWith("@nomadkaraoke.com")) && (
@@ -156,7 +156,7 @@ export function FeedbackDialog({ open, onClose }: FeedbackDialogProps) {
<DialogHeader>
<DialogTitle className="text-foreground flex items-center gap-2">
<Gift className="w-5 h-5 text-green-500" />
Share Your Feedback — Earn 2 Free Credits
Share Your Feedback — Earn 1 Free Credit
</DialogTitle>
<DialogDescription className="text-muted-foreground">
Tell us about your experience creating karaoke videos. Your feedback directly shapes what we build next.
@@ -268,7 +268,7 @@ export function FeedbackDialog({ open, onClose }: FeedbackDialogProps) {
Submitting...
</>
) : (
'Submit Feedback & Earn 2 Credits'
'Submit Feedback & Earn 1 Credit'
)}
</Button>
</div>
@@ -112,8 +112,32 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
}
}, [isPlaying])
// Fetch data on mount
// Check if audio separation is complete
const audioComplete = job.state_data?.audio_complete ?? true // Default true for legacy jobs
const [waitingForAudio, setWaitingForAudio] = useState(!audioComplete)
// Poll for audio completion if separation is still in progress
useEffect(() => {
if (!waitingForAudio) return
const pollInterval = setInterval(async () => {
try {
const updatedJob = await api.getJob(job.job_id)
if (updatedJob?.state_data?.audio_complete) {
setWaitingForAudio(false)
}
} catch {
// Ignore poll errors, keep trying
}
}, 5000) // Poll every 5 seconds
return () => clearInterval(pollInterval)
}, [waitingForAudio, job.job_id])
// Fetch data on mount (only when audio is ready)
useEffect(() => {
if (waitingForAudio) return
async function fetchData() {
try {
// Use different API based on mode:
@@ -151,7 +175,7 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
}
fetchData()
}, [job.job_id, isLocalMode])
}, [job.job_id, isLocalMode, waitingForAudio])
// Keyboard shortcuts
useEffect(() => {
@@ -488,6 +512,22 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
return () => clearInterval(interval)
}, [showSuccess, isLocalMode, router])
// Waiting for audio separation to complete
if (waitingForAudio) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center max-w-md">
<Spinner className="w-8 h-8 mx-auto mb-4" />
<h2 className="text-lg font-semibold mb-2">Audio Separation In Progress</h2>
<p className="text-muted-foreground">
The audio stems are still being separated. This usually takes a few minutes.
This page will automatically update when the separation is complete.
</p>
</div>
</div>
)
}
// Loading state
if (isLoading) {
return (
+44 -1
View File
@@ -1,12 +1,13 @@
"use client";
import { useEffect, useState } from "react";
import { api, EncodingWorkerHealth, FlacfetchHealth } from "@/lib/api";
import { api, EncodingWorkerHealth, FlacfetchHealth, AudioSeparatorHealth } from "@/lib/api";
export function VersionFooter() {
const [backendVersion, setBackendVersion] = useState<string | null>(null);
const [encodingWorker, setEncodingWorker] = useState<EncodingWorkerHealth | null>(null);
const [flacfetch, setFlacfetch] = useState<FlacfetchHealth | null>(null);
const [audioSeparator, setAudioSeparator] = useState<AudioSeparatorHealth | null>(null);
// Frontend version is injected at build time from pyproject.toml
const frontendVersion = process.env.NEXT_PUBLIC_APP_VERSION || "dev";
@@ -41,9 +42,20 @@ export function VersionFooter() {
}
};
const fetchAudioSeparatorHealth = async () => {
try {
const health = await api.getAudioSeparatorHealth();
setAudioSeparator(health);
} catch (error) {
console.error("Failed to fetch audio separator health:", error);
setAudioSeparator(null);
}
};
fetchBackendVersion();
fetchEncodingWorkerHealth();
fetchFlacfetchHealth();
fetchAudioSeparatorHealth();
}, []);
// Render encoding worker status indicator
@@ -113,6 +125,36 @@ export function VersionFooter() {
);
};
// Render audio separator status indicator
const renderAudioSeparatorStatus = () => {
if (!audioSeparator) {
return null;
}
if (audioSeparator.status === "not_configured") {
return null;
}
const isHealthy = audioSeparator.available && audioSeparator.status === "ok";
const statusColor = isHealthy ? "text-green-500" : "text-red-500";
const statusDot = isHealthy ? "●" : "○";
let statusText = isHealthy ? "Separator" : "Separator offline";
if (isHealthy && audioSeparator.version) {
statusText = `Separator: v${audioSeparator.version}`;
}
return (
<>
{" | "}
<span className={statusColor} title={isHealthy ? "Audio separator healthy" : audioSeparator.error || "Audio separator offline"}>
{statusDot}
</span>{" "}
{statusText}
</>
);
};
return (
<footer className="border-t mt-12 py-6" style={{ borderColor: 'var(--card-border)' }}>
<div className="px-4 text-center text-sm" style={{ color: 'var(--text-muted)' }}>
@@ -132,6 +174,7 @@ export function VersionFooter() {
)}
{renderEncodingWorkerStatus()}
{renderFlacfetchStatus()}
{renderAudioSeparatorStatus()}
</p>
</div>
</footer>
+1 -1
View File
@@ -115,7 +115,7 @@ test.describe('Landing Page', () => {
await page.goto('/');
await page.waitForLoadState('networkidle');
await expect(page.getByText('2 Free Credits', { exact: true })).toBeVisible();
await expect(page.getByText('1 Free Credit', { exact: true })).toBeVisible();
await expect(page.getByRole('button', { name: /sign up free/i })).toBeVisible();
});
+1 -1
View File
@@ -49,7 +49,7 @@ test.describe('Smoke Tests', () => {
await page.goto('/');
await page.waitForLoadState('networkidle');
await expect(page.getByText('2 Free Credits', { exact: true })).toBeVisible();
await expect(page.getByText('1 Free Credit', { exact: true })).toBeVisible();
await expect(page.getByRole('button', { name: /sign up free/i })).toBeVisible();
});
});
+136
View File
@@ -297,6 +297,13 @@ export interface FlacfetchHealth {
error?: string;
}
export interface AudioSeparatorHealth {
available: boolean;
status: string; // 'ok' | 'offline' | 'not_configured'
version?: string | null;
error?: string;
}
// Signed URL upload types
export interface SignedUploadUrl {
file_type: string;
@@ -1305,6 +1312,14 @@ export const api = {
return handleResponse(response);
},
/**
* Get audio separator service health status
*/
async getAudioSeparatorHealth(): Promise<AudioSeparatorHealth> {
const response = await fetch(`${API_BASE_URL}/api/health/audio-separator`);
return handleResponse(response);
},
// ==========================================================================
// Credits/Payment API endpoints
// ==========================================================================
@@ -2348,6 +2363,14 @@ export const adminApi = {
},
// Anti-abuse investigation endpoints
async getAbuseCorrelations(): Promise<AbuseCorrelationsResponse> {
const response = await fetch(
`${API_BASE_URL}/api/admin/abuse/correlations`,
{ headers: getAuthHeaders() }
);
return handleResponse(response);
},
async getAbuseSuspicious(params?: { min_jobs?: number; max_spend?: number }): Promise<AbuseSuspiciousResponse> {
const searchParams = new URLSearchParams();
if (params?.min_jobs) searchParams.set('min_jobs', String(params.min_jobs));
@@ -2380,6 +2403,45 @@ export const adminApi = {
);
return handleResponse(response);
},
async getIpInfo(ip: string): Promise<IpGeoInfo> {
const response = await fetch(
`${API_BASE_URL}/api/admin/abuse/ip-info/${encodeURIComponent(ip)}`,
{ headers: getAuthHeaders() }
);
return handleResponse(response);
},
async getIpInfoBatch(ips: string[]): Promise<Record<string, IpGeoInfo>> {
const response = await fetch(
`${API_BASE_URL}/api/admin/abuse/ip-info/batch`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ ips }),
}
);
return handleResponse(response);
},
async listFeedback(params?: {
limit?: number;
offset?: number;
search?: string;
exclude_test?: boolean;
}): Promise<AdminFeedbackListResponse> {
const searchParams = new URLSearchParams();
if (params?.limit) searchParams.set('limit', String(params.limit));
if (params?.offset) searchParams.set('offset', String(params.offset));
if (params?.search) searchParams.set('search', params.search);
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
const url = `${API_BASE_URL}/api/admin/feedback${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
const response = await fetch(url, {
headers: getAuthHeaders()
});
return handleResponse(response);
},
};
export interface EditReviewSummary {
@@ -3213,5 +3275,79 @@ export interface AbuseByFingerprintResponse {
users: AbuseRelatedUser[];
}
// Correlation cluster types
export interface AbuseClusterUser {
email: string;
signup_ip: string | null;
device_fingerprint: string | null;
credits: number;
total_jobs_created: number;
total_jobs_completed: number;
total_spent: number;
created_at: string;
user_agent?: string | null;
}
export interface AbuseFingerprintCluster {
fingerprint: string;
count: number;
users: AbuseClusterUser[];
}
export interface AbuseIpCluster {
ip: string;
count: number;
users: AbuseClusterUser[];
}
export interface AbuseCorrelationsResponse {
fingerprint_clusters: AbuseFingerprintCluster[];
ip_clusters: AbuseIpCluster[];
}
// IP geolocation types
export interface IpGeoInfo {
status: string;
ip: string;
country?: string;
country_code?: string;
region?: string;
city?: string;
isp?: string;
org?: string;
as_number?: string;
as_name?: string;
timezone?: string;
cached_at?: string;
}
// Admin feedback types
export interface AdminFeedbackItem {
id: string;
user_email: string;
created_at: string | null;
overall_rating: number;
ease_of_use_rating: number;
lyrics_accuracy_rating: number;
correction_experience_rating: number;
what_went_well: string | null;
what_could_improve: string | null;
additional_comments: string | null;
would_recommend: boolean;
would_use_again: boolean;
}
export interface AdminFeedbackListResponse {
items: AdminFeedbackItem[];
total: number;
offset: number;
limit: number;
has_more: boolean;
avg_overall_rating: number | null;
avg_ease_of_use_rating: number | null;
avg_lyrics_accuracy_rating: number | null;
avg_correction_experience_rating: number | null;
}
export { ApiError };
+1
View File
@@ -81,6 +81,7 @@ export const useAuth = create<AuthStore>()(
(window as any).__LAST_VERIFY_RESPONSE__ = {
tenant_subdomain: response.tenant_subdomain,
credits_granted: response.credits_granted || 0,
credit_status: response.credit_status || "not_applicable",
}
}
+85
View File
@@ -0,0 +1,85 @@
/**
* Client-side IP geolocation cache and fetch utilities.
*
* Caches results in memory for the browser session to avoid
* redundant API calls when the same IP appears multiple times.
*/
import { adminApi } from "./api"
import type { IpGeoInfo } from "./api"
// In-memory cache for the current session
const cache = new Map<string, IpGeoInfo>()
// Pending fetches to deduplicate concurrent requests for the same IP
const pending = new Map<string, Promise<IpGeoInfo>>()
export async function fetchIpInfo(ip: string): Promise<IpGeoInfo> {
if (!ip) return { status: "private", ip: "" }
const cached = cache.get(ip)
if (cached) return cached
// Deduplicate concurrent requests
const existing = pending.get(ip)
if (existing) return existing
const promise = adminApi.getIpInfo(ip).then((result) => {
cache.set(ip, result)
pending.delete(ip)
return result
}).catch(() => {
pending.delete(ip)
return { status: "error", ip } as IpGeoInfo
})
pending.set(ip, promise)
return promise
}
export async function fetchIpInfoBatch(ips: string[]): Promise<Record<string, IpGeoInfo>> {
const unique = [...new Set(ips.filter(Boolean))]
// Split into cached and uncached
const results: Record<string, IpGeoInfo> = {}
const uncached: string[] = []
for (const ip of unique) {
const cached = cache.get(ip)
if (cached) {
results[ip] = cached
} else {
uncached.push(ip)
}
}
if (uncached.length === 0) return results
try {
const batchResults = await adminApi.getIpInfoBatch(uncached)
for (const [ip, info] of Object.entries(batchResults)) {
cache.set(ip, info)
results[ip] = info
}
} catch {
// Mark all as error
for (const ip of uncached) {
results[ip] = { status: "error", ip }
}
}
return results
}
/**
* Convert a 2-letter country code to a flag emoji.
* e.g., "US" -> "🇺🇸", "VN" -> "🇻🇳"
*/
export function countryCodeToFlag(code: string): string {
if (!code || code.length !== 2) return ""
const offset = 0x1F1E6 - 65 // 'A' = 65
return String.fromCodePoint(
code.charCodeAt(0) + offset,
code.charCodeAt(1) + offset
)
}
+1
View File
@@ -33,6 +33,7 @@ export interface VerifyMagicLinkResponse {
message: string
tenant_subdomain?: string | null
credits_granted?: number
credit_status?: string // "granted", "denied", "already_granted", "not_applicable"
}
export interface UserProfileResponse {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "karaoke-gen-frontend",
"version": "0.85.7",
"version": "0.85.8",
"private": true,
"scripts": {
"build": "next build && node scripts/spa-redirect-404.js",
+55 -2
View File
@@ -39,8 +39,9 @@ from config import (
from modules import database, storage as storage_module, artifact_registry, secrets
from modules import cloud_tasks, cloud_run, monitoring, networking, runner_manager
from modules import divebar_mirror, kn_data_sync, divebar_lookup
from modules import audio_separator_service
from modules.iam import backend_sa, github_actions_sa, claude_automation_sa, worker_sas
from compute import encoding_worker_vm, github_runners
from compute import encoding_worker_vm, github_runners, divebar_sync_vm
# ==================== Core Infrastructure ====================
@@ -186,7 +187,7 @@ gdrive_validator_function = cloudfunctionsv2.Function(
service_account_email=gdrive_validator_sa.email,
environment_variables={
"GDRIVE_FOLDER_ID": GDRIVE_FOLDER_ID,
"NOTIFY_ON_SUCCESS": "true",
"NOTIFY_ON_SUCCESS": "false",
"EMAIL_TO": "gen@nomadkaraoke.com",
"EMAIL_FROM": "gen@nomadkaraoke.com",
},
@@ -391,6 +392,50 @@ kn_data_sync_resources = kn_data_sync.create_kn_data_sync_resources(all_secrets)
divebar_lookup_resources = divebar_lookup.create_divebar_lookup_resources(all_secrets)
# ==================== Divebar File Sync VM ====================
# Divebar File Sync VM (downloads karaoke files from Drive to GCS)
divebar_sync_instance = divebar_sync_vm.create_divebar_sync_vm(
divebar_mirror_resources["service_account"]
)
# Cloud Scheduler to start the sync VM daily (uses compute.instances.start API)
divebar_sync_scheduler = cloudscheduler.Job(
"divebar-sync-vm-scheduler", # Must match Pulumi state
name="divebar-sync-vm-daily",
description="Start Divebar file sync VM daily to download new files from Drive to GCS",
region=REGION,
schedule="0 3 * * *", # 3:00 AM ET (after index refresh at 2 AM)
time_zone="America/New_York",
http_target=cloudscheduler.JobHttpTargetArgs(
uri=divebar_sync_instance.self_link.apply(
lambda link: f"https://compute.googleapis.com/compute/v1/{link}/start"
),
http_method="POST",
oidc_token=cloudscheduler.JobHttpTargetOidcTokenArgs(
service_account_email=divebar_mirror_resources["service_account"].email,
),
),
retry_config=cloudscheduler.JobRetryConfigArgs(
retry_count=1,
min_backoff_duration="60s",
max_backoff_duration="300s",
),
)
# Grant the SA permission to start/stop its own VM
divebar_sync_compute_admin = gcp.projects.IAMMember(
"divebar-mirror-compute-instance-admin", # Must match Pulumi state
project=PROJECT_ID,
role="roles/compute.instanceAdmin.v1",
member=divebar_mirror_resources["service_account"].email.apply(
lambda email: f"serviceAccount:{email}"
),
)
# ==================== Audio Separator GPU Service ====================
# Cloud Run GPU (L4) service for audio stem separation — replaces Modal
audio_separator_resources = audio_separator_service.create_all_resources()
# ==================== Compute VMs ====================
# Encoding Worker VM (video encoding service)
@@ -547,3 +592,11 @@ pulumi.export("kn_data_bucket", kn_data_sync_resources["data_bucket"].name)
# Divebar lookup API (Phase 3)
pulumi.export("divebar_lookup_function_url", divebar_lookup_resources["function"].url)
# Divebar file sync VM
pulumi.export("divebar_sync_vm_name", divebar_sync_instance.name)
pulumi.export("divebar_sync_scheduler_name", divebar_sync_scheduler.name)
# Audio separator GPU service
pulumi.export("audio_separator_service_url", audio_separator_resources["service"].uri)
pulumi.export("audio_separator_service_account", audio_separator_resources["service_account"].email)
+63
View File
@@ -0,0 +1,63 @@
"""
Divebar File Sync VM resources.
Creates a small GCE VM that downloads karaoke files from Google Drive
to GCS. The VM starts, runs the sync, and shuts itself down.
Design:
- e2-medium (2 vCPU, 4 GB) — enough for 4 concurrent downloads
- 10 GB boot disk (minimal — files go to GCS, not local disk)
- Preemptible/Spot for cost savings (~$10/mo if running 24/7, but
it only runs for ~1-2 hours daily for incremental sync)
- Auto-shutdown after sync completes
- Cloud Scheduler starts the VM daily at 3 AM ET (after index refresh at 2 AM)
"""
import pulumi
from pulumi_gcp import compute, serviceaccount
from config import REGION, ZONE, PROJECT_ID
from .startup_scripts import read_script
def create_divebar_sync_vm(
service_account: serviceaccount.Account,
) -> compute.Instance:
"""Create the Divebar file sync VM instance."""
startup_script = read_script("divebar_sync.sh")
return compute.Instance(
"divebar-sync-vm",
name="divebar-sync",
machine_type="e2-medium",
zone=ZONE,
boot_disk=compute.InstanceBootDiskArgs(
initialize_params=compute.InstanceBootDiskInitializeParamsArgs(
image="debian-cloud/debian-12",
size=10,
type="pd-standard",
),
),
network_interfaces=[compute.InstanceNetworkInterfaceArgs(
network="default",
# Needs internet access for Drive API and GCS
access_configs=[compute.InstanceNetworkInterfaceAccessConfigArgs()],
)],
service_account=compute.InstanceServiceAccountArgs(
email=service_account.email,
# drive.readonly for downloading files, cloud-platform for GCS + BigQuery
scopes=[
"https://www.googleapis.com/auth/drive.readonly",
"https://www.googleapis.com/auth/cloud-platform",
],
),
metadata_startup_script=startup_script,
tags=["divebar-sync"],
allow_stopping_for_update=True,
scheduling=compute.InstanceSchedulingArgs(
automatic_restart=False, # Don't restart after self-shutdown
),
# VM is started daily by Cloud Scheduler; may be RUNNING or TERMINATED
# depending on sync status. Use RUNNING to avoid Pulumi trying to stop it.
desired_status="RUNNING",
)
@@ -0,0 +1,56 @@
#!/bin/bash
# Divebar File Sync VM startup script
#
# Downloads karaoke files from Google Drive to GCS using the BigQuery index.
# Auto-shuts down after sync completes. Designed to be started daily by
# Cloud Scheduler or manually for initial bulk sync.
#
# Logs: journalctl -u divebar-sync -f
# OR: /var/log/divebar-sync.log
set -euo pipefail
LOG_FILE="/var/log/divebar-sync.log"
REPO_DIR="/opt/nomad/divebar-sync"
SCRIPT="infrastructure/scripts/divebar_file_sync.py"
log() {
echo "$(date '+%Y-%m-%d %H:%M:%S') $*" | tee -a "$LOG_FILE"
}
log "=== Divebar file sync starting ==="
# Install dependencies (idempotent)
if ! command -v pip3 &>/dev/null; then
log "Installing Python3 and pip..."
apt-get update -qq && apt-get install -y -qq python3-pip python3-venv git
fi
# Clone or update the repo
if [ -d "$REPO_DIR" ]; then
log "Updating repo..."
cd "$REPO_DIR" && git pull origin main --quiet
else
log "Cloning repo..."
git clone --depth 1 https://github.com/nomadkaraoke/karaoke-gen.git "$REPO_DIR"
fi
cd "$REPO_DIR"
log "Installing Python dependencies..."
# Pin google-auth<2.28 to avoid MTLS metadata server issue on GCE
# See: https://github.com/googleapis/google-auth-library-python/issues/1474
# Use --break-system-packages since Debian 12 enforces PEP 668
pip3 install -q --break-system-packages 'google-auth<2.28' google-api-python-client google-cloud-storage google-cloud-bigquery requests
# Force metadata server to use HTTP (not HTTPS) — required for GCE VMs
# See: https://github.com/googleapis/google-auth-library-python/issues/1474
export GCE_METADATA_HOST="169.254.169.254"
export GOOGLE_CLOUD_PROJECT="nomadkaraoke"
# Run the sync
log "Starting file sync (workers=4)..."
python3 "$SCRIPT" --workers 4 2>&1 | tee -a "$LOG_FILE"
# The script handles shutdown itself after completion
log "=== Divebar file sync script exited ==="
@@ -45,11 +45,67 @@ apt-get install -y \
gnupg \
lsb-release
# ==================== NVIDIA drivers ====================
# ==================== Kernel + NVIDIA drivers ====================
# Strategy:
# The base debian-cloud/debian-12 image ships an older kernel (e.g., 6.1.0-43)
# but Debian repos drop old kernel headers once a new point release lands.
# If headers aren't available for the running kernel, we upgrade the kernel,
# reboot ONCE (tracked via metadata flag), and then install headers + NVIDIA.
#
# On subsequent stop/start cycles the kernel stays current and headers match,
# so the script just ensures DKMS has built the nvidia module.
RUNNING_KERNEL="$(uname -r)"
REBOOT_FLAG="/var/lib/gpu-runner-kernel-upgraded"
echo "Running kernel: $RUNNING_KERNEL"
# Check if headers are available for the running kernel
if ! apt-cache show "linux-headers-$RUNNING_KERNEL" &>/dev/null; then
if [ -f "$REBOOT_FLAG" ]; then
echo "ERROR: Headers still unavailable after kernel upgrade + reboot. Giving up."
echo "Running kernel: $RUNNING_KERNEL"
apt-cache search linux-headers | grep cloud | tail -5
exit 1
fi
echo "Headers for $RUNNING_KERNEL not in repos — upgrading kernel and rebooting..."
# Upgrade kernel to latest available version (headers will match after reboot)
apt-get install -y linux-image-cloud-amd64 linux-headers-cloud-amd64
# Mark that we've upgraded so we don't loop forever
touch "$REBOOT_FLAG"
echo "Kernel upgraded. Rebooting to load new kernel..."
reboot
# Script exits here; startup script re-runs after reboot with the new kernel
exit 0
fi
# If we got here after a reboot, clean up the flag
rm -f "$REBOOT_FLAG"
# 1. Install headers + DKMS for the running kernel
echo "Installing kernel headers for $RUNNING_KERNEL..."
apt-get install -y "linux-headers-$RUNNING_KERNEL" dkms
# 2. Clean up headers for kernels we're no longer running (prevents disk bloat)
for old_headers in /usr/src/linux-headers-*; do
header_ver="$(basename "$old_headers" | sed 's/^linux-headers-//')"
# Skip the running kernel's headers and the -common package
if [ "$header_ver" = "$RUNNING_KERNEL" ] || echo "$header_ver" | grep -q "common"; then
continue
fi
pkg="linux-headers-$header_ver"
if dpkg -l "$pkg" 2>/dev/null | grep -q '^ii'; then
echo "Removing stale kernel headers: $pkg"
apt-get remove -y "$pkg" 2>/dev/null || true
fi
done
# 3. Install NVIDIA packages if not yet present
if ! command -v nvidia-smi &>/dev/null; then
echo "Installing NVIDIA drivers..."
# Install kernel headers (required for driver build)
apt-get install -y linux-headers-$(uname -r)
# Add NVIDIA CUDA repository for Debian 12
install_gpg_key \
@@ -63,22 +119,40 @@ if ! command -v nvidia-smi &>/dev/null; then
# Installing cuda-toolkit gives us nvidia-smi and full CUDA support.
apt-get install -y cuda-drivers cuda-toolkit-12-4
else
echo "NVIDIA drivers already installed, skipping"
echo "NVIDIA packages already installed"
fi
# Verify GPU is accessible (retry up to 30 times with 10s delay — driver may need time after install)
# 4. If the kernel module isn't loaded (e.g., kernel upgraded since last boot),
# rebuild via DKMS and load it. This is the common failure mode: packages are
# installed but the module was built against an older kernel.
if ! lsmod | grep -q '^nvidia '; then
echo "NVIDIA kernel module not loaded for $RUNNING_KERNEL — rebuilding with DKMS..."
echo "DKMS status before rebuild:"
dkms status || true
dkms autoinstall
modprobe nvidia
echo "DKMS status after rebuild:"
dkms status || true
fi
# 5. Verify GPU is accessible
echo "Verifying GPU..."
for attempt in $(seq 1 30); do
for attempt in $(seq 1 10); do
if nvidia-smi; then
echo "GPU verified successfully on attempt $attempt"
break
fi
if [ "$attempt" -eq 30 ]; then
echo "ERROR: nvidia-smi failed after 30 attempts — GPU not available"
if [ "$attempt" -eq 10 ]; then
echo "ERROR: nvidia-smi failed after 10 attempts — GPU not available"
echo "Diagnostic info:"
dkms status || true
ls /lib/modules/"$RUNNING_KERNEL"/updates/dkms/ 2>/dev/null || echo "No DKMS modules found for $RUNNING_KERNEL"
exit 1
fi
echo "nvidia-smi attempt $attempt failed, retrying in 10s..."
sleep 10
echo "nvidia-smi attempt $attempt failed, retrying in 5s..."
sleep 5
done
# ==================== FFmpeg + audio libraries ====================
@@ -110,6 +184,10 @@ if [ ! -f "$PYTHON_PREFIX/bin/python3.13" ]; then
make install
rm -rf /tmp/Python-3.13.0*
# Bootstrap pip — ensurepip is bundled but pip may not be installed into
# site-packages by make install. setup-python@v5 requires a working pip.
"$PYTHON_PREFIX/bin/python3.13" -m ensurepip --upgrade
# Create convenience symlinks
ln -sf "$PYTHON_PREFIX/bin/python3.13" /usr/local/bin/python3.13
ln -sf "$PYTHON_PREFIX/bin/python3" /usr/local/bin/python3
@@ -121,8 +199,12 @@ fi
# ==================== Poetry ====================
if ! command -v poetry &>/dev/null; then
echo "Installing Poetry..."
# Install Poetry to /opt/poetry (shared location) so the runner user can access it.
# The default installer puts everything under ~/.local which is /root/.local — the
# runner user can't follow symlinks into /root/ (mode 700).
export POETRY_HOME="/opt/poetry"
curl -sSL https://install.python-poetry.org | python3 -
ln -sf /root/.local/bin/poetry /usr/local/bin/poetry
ln -sf /opt/poetry/bin/poetry /usr/local/bin/poetry
else
echo "Poetry already installed, skipping"
fi
+5 -1
View File
@@ -87,8 +87,12 @@ fi
echo "Downloaded wheel as: ${WHEEL_NAME}"
# 4. Install the wheel
# Use --no-deps because the encoding worker venv has runtime deps pre-installed.
# The wheel only needs to update the karaoke-gen code itself.
# Full dependency resolution on the complex dep graph (langchain, CUDA, etc.)
# can hit pip's "resolution-too-deep" error and prevent the service from starting.
echo "[4/5] Installing wheel..."
"${VENV}/bin/pip" install --upgrade --quiet --force-reinstall "${WHEEL_PATH}"
"${VENV}/bin/pip" install --upgrade --quiet --force-reinstall --no-deps "${WHEEL_PATH}"
# 5. Verify installed version
echo "[5/5] Verifying installed version..."
@@ -287,6 +287,98 @@ def _get_download_url(file_id: str) -> dict:
}
def _get_full_stats() -> dict:
"""Get comprehensive Divebar mirror statistics."""
client = bigquery.Client(project=GCP_PROJECT_ID)
sql = f"""
WITH catalog_stats AS (
SELECT
COUNT(*) as total_files,
COUNT(DISTINCT brand) as total_brands,
COUNTIF(gcs_path IS NOT NULL) as gcs_synced,
COUNTIF(gcs_path IS NULL) as gcs_pending,
COUNTIF(artist IS NOT NULL AND title IS NOT NULL) as with_metadata,
ROUND(SUM(file_size) / 1024/1024/1024, 1) as total_gb,
ROUND(SUM(CASE WHEN gcs_path IS NOT NULL THEN file_size ELSE 0 END) / 1024/1024/1024, 1) as gcs_synced_gb,
ROUND(SUM(CASE WHEN gcs_path IS NULL THEN file_size ELSE 0 END) / 1024/1024/1024, 1) as gcs_pending_gb,
MAX(synced_at) as last_index_sync
FROM `{GCP_PROJECT_ID}.{DATASET}.divebar_catalog`
),
format_stats AS (
SELECT format, COUNT(*) as count,
ROUND(SUM(file_size) / 1024/1024/1024, 1) as gb,
COUNTIF(gcs_path IS NOT NULL) as in_gcs
FROM `{GCP_PROJECT_ID}.{DATASET}.divebar_catalog`
GROUP BY format
ORDER BY count DESC
),
xref_stats AS (
SELECT
COUNT(*) as total_matches,
COUNT(DISTINCT kn_id) as unique_kn_songs,
COUNT(DISTINCT divebar_file_id) as unique_divebar_files,
MAX(matched_at) as last_xref_rebuild
FROM `{GCP_PROJECT_ID}.{DATASET}.kn_divebar_xref`
),
kn_stats AS (
SELECT
(SELECT COUNT(*) FROM `{GCP_PROJECT_ID}.{DATASET}.karaokenerds_raw`) as kn_songs,
(SELECT COUNT(*) FROM `{GCP_PROJECT_ID}.{DATASET}.karaokenerds_community`) as kn_community
)
SELECT
c.*, x.total_matches, x.unique_kn_songs, x.unique_divebar_files,
x.last_xref_rebuild, k.kn_songs, k.kn_community
FROM catalog_stats c, xref_stats x, kn_stats k
"""
row = list(client.query(sql).result())[0]
# Get format breakdown
fmt_sql = f"""
SELECT format, COUNT(*) as count,
ROUND(SUM(file_size) / 1024/1024/1024, 1) as gb,
COUNTIF(gcs_path IS NOT NULL) as in_gcs
FROM `{GCP_PROJECT_ID}.{DATASET}.divebar_catalog`
GROUP BY format ORDER BY count DESC
"""
formats = {}
for fmt_row in client.query(fmt_sql).result():
formats[fmt_row.format] = {
"count": fmt_row.count,
"gb": fmt_row.gb,
"in_gcs": fmt_row.in_gcs,
}
return {
"catalog": {
"total_files": row.total_files,
"total_brands": row.total_brands,
"with_metadata": row.with_metadata,
"total_gb": row.total_gb,
"last_index_sync": row.last_index_sync.isoformat() if row.last_index_sync else None,
},
"gcs_mirror": {
"synced": row.gcs_synced,
"pending": row.gcs_pending,
"synced_gb": row.gcs_synced_gb,
"pending_gb": row.gcs_pending_gb,
"percent": round(row.gcs_synced / row.total_files * 100, 1) if row.total_files else 0,
},
"formats": formats,
"cross_reference": {
"total_matches": row.total_matches,
"unique_kn_songs": row.unique_kn_songs,
"unique_divebar_files": row.unique_divebar_files,
"last_rebuild": row.last_xref_rebuild.isoformat() if row.last_xref_rebuild else None,
},
"karaoke_nerds": {
"songs": row.kn_songs,
"community_tracks": row.kn_community,
},
}
@functions_framework.http
def divebar_lookup(request):
"""HTTP Cloud Function entry point."""
@@ -338,6 +430,10 @@ def divebar_lookup(request):
"source": result["source"],
})
elif action == "stats":
stats = _get_full_stats()
return _json_response({"status": "ok", **stats})
else:
return _json_response({"status": "error", "message": f"Unknown action: {action}"}, 400)
+24 -19
View File
@@ -311,7 +311,8 @@ def _get_instance_age_hours(instance: compute_v1.Instance) -> float:
def check_github_for_pending_jobs() -> bool:
"""
Check GitHub API for any pending/queued/in-progress workflow runs.
Check GitHub API for any pending/queued/in-progress workflow runs
across all org repos that use self-hosted runners.
Returns True if there are runs that might need our self-hosted runners.
"""
@@ -320,25 +321,29 @@ def check_github_for_pending_jobs() -> bool:
pat = get_github_pat()
org = "nomadkaraoke"
for status in ["queued", "in_progress"]:
url = f"https://api.github.com/repos/{org}/karaoke-gen/actions/runs?status={status}"
req = urllib.request.Request(
url,
headers={
"Authorization": f"Bearer {pat}",
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
},
)
# All repos that have workflows using self-hosted runners
repos = ["karaoke-gen", "python-audio-separator"]
try:
with urllib.request.urlopen(req, timeout=10) as response:
data = json.loads(response.read().decode("utf-8"))
if data.get("total_count", 0) > 0:
print(f"Found {data['total_count']} {status} runs in karaoke-gen")
return True
except Exception as e:
print(f"Error checking GitHub API ({status}): {e}")
for repo in repos:
for status in ["queued", "in_progress"]:
url = f"https://api.github.com/repos/{org}/{repo}/actions/runs?status={status}"
req = urllib.request.Request(
url,
headers={
"Authorization": f"Bearer {pat}",
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
},
)
try:
with urllib.request.urlopen(req, timeout=10) as response:
data = json.loads(response.read().decode("utf-8"))
if data.get("total_count", 0) > 0:
print(f"Found {data['total_count']} {status} runs in {repo}")
return True
except Exception as e:
print(f"Error checking GitHub API ({repo}/{status}): {e}")
return False
@@ -0,0 +1,197 @@
"""
Audio Separator Cloud Run GPU Service.
Deploys the audio-separator API as a Cloud Run service with L4 GPU acceleration.
Replaces the Modal deployment for audio stem separation.
Resources created:
- Artifact Registry repository for audio-separator Docker images
- Cloud Run GPU service (L4, scale-to-zero)
- Service account with minimal permissions
"""
import pulumi
import pulumi_gcp as gcp
from pulumi_gcp import artifactregistry, cloudrunv2, serviceaccount
from pulumi_gcp.cloudrunv2 import ServiceTemplateNodeSelectorArgs, ServiceTemplateContainerPortsArgs
from config import PROJECT_ID, REGION
# Audio separator uses us-east4 due to L4 GPU quota availability.
# Can be moved to us-central1 once quota is approved there.
AUDIO_SEPARATOR_REGION = "us-east4"
def create_audio_separator_artifact_repo() -> artifactregistry.Repository:
"""Create Artifact Registry repo for audio-separator Docker images."""
return artifactregistry.Repository(
"audio-separator-artifact-repo",
repository_id="audio-separator",
location=AUDIO_SEPARATOR_REGION,
format="DOCKER",
description="Docker repository for audio-separator GPU service",
)
def create_service_account() -> serviceaccount.Account:
"""Create service account for the audio separator Cloud Run service."""
return serviceaccount.Account(
"audio-separator-sa",
account_id="audio-separator",
display_name="Audio Separator Service Account",
description="Service account for audio separator Cloud Run GPU service",
)
def grant_permissions(
sa: serviceaccount.Account,
) -> dict:
"""Grant permissions to the audio separator service account."""
bindings = {}
# Read admin-tokens secret for API auth
bindings["secrets_access"] = gcp.projects.IAMMember(
"audio-separator-secrets-access",
project=PROJECT_ID,
role="roles/secretmanager.secretAccessor",
member=sa.email.apply(lambda email: f"serviceAccount:{email}"),
)
# Write logs
bindings["logging"] = gcp.projects.IAMMember(
"audio-separator-logging",
project=PROJECT_ID,
role="roles/logging.logWriter",
member=sa.email.apply(lambda email: f"serviceAccount:{email}"),
)
# Write metrics
bindings["monitoring"] = gcp.projects.IAMMember(
"audio-separator-monitoring",
project=PROJECT_ID,
role="roles/monitoring.metricWriter",
member=sa.email.apply(lambda email: f"serviceAccount:{email}"),
)
return bindings
def create_service(
sa: serviceaccount.Account,
artifact_repo: artifactregistry.Repository,
) -> cloudrunv2.Service:
"""
Create the Cloud Run GPU service for audio separation.
Uses L4 GPU for fast inference. Scales to zero when idle.
Models are baked into the Docker image (no GCS download needed).
"""
service = cloudrunv2.Service(
"audio-separator-service",
name="audio-separator",
location=AUDIO_SEPARATOR_REGION,
ingress="INGRESS_TRAFFIC_ALL",
template=cloudrunv2.ServiceTemplateArgs(
scaling=cloudrunv2.ServiceTemplateScalingArgs(
min_instance_count=0,
max_instance_count=5, # Cloud Run GPU services limited to 5 max instances
),
max_instance_request_concurrency=1, # Each separation uses the full GPU; route new requests to new instances
gpu_zonal_redundancy_disabled=True, # Not needed for batch workloads
# Keep instances warm for 600s (10 min) between Stage 1 → Stage 2
session_affinity=True,
timeout="1800s", # 30 min max per request
service_account=sa.email,
containers=[
cloudrunv2.ServiceTemplateContainerArgs(
# Initial placeholder image - will be updated by CI/CD
image=artifact_repo.name.apply(
lambda name: f"{AUDIO_SEPARATOR_REGION}-docker.pkg.dev/{PROJECT_ID}/audio-separator/api:latest"
),
ports=ServiceTemplateContainerPortsArgs(
container_port=8080,
),
resources=cloudrunv2.ServiceTemplateContainerResourcesArgs(
limits={
"cpu": "4",
"memory": "16Gi",
"nvidia.com/gpu": "1",
},
startup_cpu_boost=True,
),
envs=[
cloudrunv2.ServiceTemplateContainerEnvArgs(
name="MODEL_DIR",
value="/models",
),
cloudrunv2.ServiceTemplateContainerEnvArgs(
name="STORAGE_DIR",
value="/tmp/storage",
),
],
startup_probe=cloudrunv2.ServiceTemplateContainerStartupProbeArgs(
http_get=cloudrunv2.ServiceTemplateContainerStartupProbeHttpGetArgs(
path="/health",
port=8080,
),
initial_delay_seconds=5,
period_seconds=5,
timeout_seconds=5,
failure_threshold=12, # Models baked in, startup is fast
),
liveness_probe=cloudrunv2.ServiceTemplateContainerLivenessProbeArgs(
http_get=cloudrunv2.ServiceTemplateContainerLivenessProbeHttpGetArgs(
path="/health",
port=8080,
),
period_seconds=30,
timeout_seconds=5,
failure_threshold=3,
),
),
],
# L4 GPU node selector
node_selector=ServiceTemplateNodeSelectorArgs(
accelerator="nvidia-l4",
),
),
)
return service
def allow_unauthenticated_access(service: cloudrunv2.Service) -> cloudrunv2.ServiceIamMember:
"""
Allow unauthenticated access to the audio separator service.
Auth is handled at the application level via admin-tokens,
matching the pattern used by the encoding worker.
"""
return cloudrunv2.ServiceIamMember(
"audio-separator-allow-unauthenticated",
project=PROJECT_ID,
location=AUDIO_SEPARATOR_REGION,
name=service.name,
role="roles/run.invoker",
member="allUsers",
)
def create_all_resources() -> dict:
"""
Create all audio separator infrastructure resources.
Returns dict of all created resources for export.
"""
artifact_repo = create_audio_separator_artifact_repo()
sa = create_service_account()
iam_bindings = grant_permissions(sa)
service = create_service(sa, artifact_repo)
unauthenticated_access = allow_unauthenticated_access(service)
return {
"artifact_repo": artifact_repo,
"service_account": sa,
"service": service,
"iam_bindings": iam_bindings,
}
+181 -181
View File
@@ -70,22 +70,15 @@ def create_lyrics_transcription_job(
},
),
envs=[
# Basic configuration
# Admin token for Cloud Tasks auth header
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GOOGLE_CLOUD_PROJECT",
value=PROJECT_ID,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCS_BUCKET_NAME",
value=bucket.name,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENVIRONMENT",
value="production",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCP_REGION",
value=REGION,
name="ADMIN_TOKENS",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/admin-tokens",
version="latest",
),
),
),
# AudioShake API token (required for transcription)
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
@@ -97,36 +90,6 @@ def create_lyrics_transcription_job(
),
),
),
# Genius API token (for lyrics fetching)
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GENIUS_API_TOKEN",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/genius-api-key",
version="latest",
),
),
),
# Spotify cookie (for Spotify lyrics)
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="SPOTIFY_COOKIE_SP_DC",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/spotify-cookie",
version="latest",
),
),
),
# RapidAPI key (for Musixmatch lyrics)
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="RAPIDAPI_KEY",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/rapidapi-key",
version="latest",
),
),
),
# Cloud Run service URL for Cloud Tasks targeting
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="CLOUD_RUN_SERVICE_URL",
@@ -137,12 +100,49 @@ def create_lyrics_transcription_job(
name="ENABLE_CLOUD_TASKS",
value="true",
),
# Admin token for Cloud Tasks auth header
# Basic configuration
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ADMIN_TOKENS",
name="ENVIRONMENT",
value="production",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCP_REGION",
value=REGION,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCS_BUCKET_NAME",
value=bucket.name,
),
# Genius API token (for lyrics fetching)
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GENIUS_API_TOKEN",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/admin-tokens",
secret=f"projects/{PROJECT_ID}/secrets/genius-api-key",
version="latest",
),
),
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GOOGLE_CLOUD_PROJECT",
value=PROJECT_ID,
),
# RapidAPI key (for Musixmatch lyrics)
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="RAPIDAPI_KEY",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/rapidapi-key",
version="latest",
),
),
),
# Spotify cookie (for Spotify lyrics)
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="SPOTIFY_COOKIE_SP_DC",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/spotify-cookie",
version="latest",
),
),
@@ -197,27 +197,20 @@ def create_audio_separation_job(
},
),
envs=[
# Basic configuration
# Admin token for Cloud Tasks auth header
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GOOGLE_CLOUD_PROJECT",
value=PROJECT_ID,
name="ADMIN_TOKENS",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/admin-tokens",
version="latest",
),
),
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCS_BUCKET_NAME",
value=bucket.name,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENVIRONMENT",
value="production",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCP_REGION",
value=REGION,
),
# Modal API URL for GPU audio separation
# Audio separator API (Cloud Run GPU service in us-east4)
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="AUDIO_SEPARATOR_API_URL",
value="https://nomadkaraoke--audio-separator-api.modal.run",
value="https://audio-separator-718638054799.us-east4.run.app",
),
# Cloud Run service URL for Cloud Tasks targeting
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
@@ -229,15 +222,22 @@ def create_audio_separation_job(
name="ENABLE_CLOUD_TASKS",
value="true",
),
# Admin token for Cloud Tasks auth header
# Basic configuration
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ADMIN_TOKENS",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/admin-tokens",
version="latest",
),
),
name="ENVIRONMENT",
value="production",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCP_REGION",
value=REGION,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCS_BUCKET_NAME",
value=bucket.name,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GOOGLE_CLOUD_PROJECT",
value=PROJECT_ID,
),
],
)
@@ -300,39 +300,12 @@ def create_audio_download_job(
},
),
envs=[
# Basic configuration
# Admin token for worker auth
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GOOGLE_CLOUD_PROJECT",
value=PROJECT_ID,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCS_BUCKET_NAME",
value=bucket.name,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENVIRONMENT",
value="production",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCP_REGION",
value=REGION,
),
# Flacfetch API URL (internal VPC address)
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="FLACFETCH_API_URL",
name="ADMIN_TOKENS",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/flacfetch-api-url",
version="latest",
),
),
),
# Flacfetch API key
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="FLACFETCH_API_KEY",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/flacfetch-api-key",
secret=f"projects/{PROJECT_ID}/secrets/admin-tokens",
version="latest",
),
),
@@ -347,16 +320,43 @@ def create_audio_download_job(
name="ENABLE_CLOUD_TASKS",
value="true",
),
# Admin token for worker auth
# Basic configuration
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ADMIN_TOKENS",
name="ENVIRONMENT",
value="production",
),
# Flacfetch API key
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="FLACFETCH_API_KEY",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/admin-tokens",
secret=f"projects/{PROJECT_ID}/secrets/flacfetch-api-key",
version="latest",
),
),
),
# Flacfetch API URL (internal VPC address)
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="FLACFETCH_API_URL",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/flacfetch-api-url",
version="latest",
),
),
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCP_REGION",
value=REGION,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCS_BUCKET_NAME",
value=bucket.name,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GOOGLE_CLOUD_PROJECT",
value=PROJECT_ID,
),
],
)
],
@@ -410,81 +410,6 @@ def create_video_encoding_job(
},
),
envs=[
# Core configuration
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GOOGLE_CLOUD_PROJECT",
value=PROJECT_ID,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCS_BUCKET_NAME",
value=bucket.name,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENVIRONMENT",
value="production",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCP_REGION",
value=REGION,
),
# GCE encoding worker
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="USE_GCE_ENCODING",
value="true",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENCODING_WORKER_URL",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/encoding-worker-url",
version="latest",
),
),
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENCODING_WORKER_API_KEY",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/encoding-worker-api-key",
version="latest",
),
),
),
# Distribution defaults
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_ENABLE_YOUTUBE_UPLOAD",
value="true",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_BRAND_PREFIX",
value="NOMAD",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_PRIVATE_BRAND_PREFIX",
value="NOMADNP",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_DROPBOX_PATH",
value="/MediaUnsynced/Karaoke/Tracks-Organized",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_PRIVATE_DROPBOX_PATH",
value="/MediaUnsynced/Karaoke/Tracks-NonPublished",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_GDRIVE_FOLDER_ID",
value="1laRKAyxo0v817SstfM5XkpbWiNKNAMSX",
),
# Discord webhook for release notifications
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_DISCORD_WEBHOOK_URL",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/discord-releases-webhook",
version="latest",
),
),
),
# Admin token for worker-to-service auth
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ADMIN_TOKENS",
@@ -500,10 +425,81 @@ def create_video_encoding_job(
name="CLOUD_RUN_SERVICE_URL",
value="https://api.nomadkaraoke.com",
),
# Distribution defaults
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_BRAND_PREFIX",
value="NOMAD",
),
# Discord webhook for release notifications
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_DISCORD_WEBHOOK_URL",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/discord-releases-webhook",
version="latest",
),
),
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_DROPBOX_PATH",
value="/MediaUnsynced/Karaoke/Tracks-Organized",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_ENABLE_YOUTUBE_UPLOAD",
value="true",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_GDRIVE_FOLDER_ID",
value="1laRKAyxo0v817SstfM5XkpbWiNKNAMSX",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_PRIVATE_BRAND_PREFIX",
value="NOMADNP",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_PRIVATE_DROPBOX_PATH",
value="/MediaUnsynced/Karaoke/Tracks-NonPublished",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENABLE_CLOUD_TASKS",
value="true",
),
# GCE encoding worker
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENCODING_WORKER_API_KEY",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/encoding-worker-api-key",
version="latest",
),
),
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENCODING_WORKER_URL",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/encoding-worker-url",
version="latest",
),
),
),
# Core configuration
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENVIRONMENT",
value="production",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCP_REGION",
value=REGION,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCS_BUCKET_NAME",
value=bucket.name,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GOOGLE_CLOUD_PROJECT",
value=PROJECT_ID,
),
# SendGrid for completion emails
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="SENDGRID_API_KEY",
@@ -514,6 +510,10 @@ def create_video_encoding_job(
),
),
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="USE_GCE_ENCODING",
value="true",
),
],
)
],
+1 -2
View File
@@ -1,3 +1,2 @@
pulumi>=3.0.0,<4.0.0
pulumi-gcp>=7.0.0,<8.0.0
pulumi-gcp>=9.0.0,<10.0.0
+129 -100
View File
@@ -179,16 +179,21 @@ class AudioProcessor:
return self._process_audio_separation_remote(audio_file, artist_title, track_output_dir, remote_api_url)
except Exception as e:
error_str = str(e)
# Don't fall back for download failures - these indicate API issues that should be fixed
if ("no files were downloaded" in error_str or
"failed to produce essential" in error_str):
self.logger.error(f"Remote API processing failed with download/file organization issue: {error_str}")
self.logger.error("This indicates an audio-separator API issue that should be fixed. Not falling back to local processing.")
raise e
else:
# Fall back for other types of errors (network issues, etc.)
self.logger.error(f"Remote API processing failed: {error_str}")
self.logger.info("Falling back to local audio separation")
self.logger.error(f"Remote API processing failed: {error_str}")
# Never fall back for API processing errors (download failures,
# missing files, etc.) — retrying locally won't help.
# Only fall back for transient network errors AND only when
# local processing is possible (model_file_dir is configured).
is_api_error = (
"no files were downloaded" in error_str
or "failed to produce essential" in error_str
or "missing" in error_str.lower()
)
if is_api_error or not self.model_file_dir:
if not self.model_file_dir:
self.logger.error("No local model directory configured — cannot fall back to local processing.")
raise
self.logger.info("Falling back to local audio separation")
else:
self.logger.info("AUDIO_SEPARATOR_API_URL not set, using local audio separation. "
"Set this environment variable to use remote GPU processing.")
@@ -315,108 +320,132 @@ class AudioProcessor:
if os.environ.get("KARAOKE_GEN_SKIP_AUDIO_SEPARATION"):
return result
# Derive a safe file prefix — use job_id if available (avoids artist/title encoding issues)
job_id = getattr(self, 'job_id', None)
file_prefix = job_id if job_id else artist_title.replace("/", "_").replace("\\", "_")
try:
# Stage 1: Process original song with clean instrumental model + other stems models
stage1_models = []
if self.clean_instrumental_model:
stage1_models.append(self.clean_instrumental_model)
stage1_models.extend(self.other_stems_models)
self.logger.info(f"Stage 1: Submitting audio separation job with models: {stage1_models}")
# Submit the first stage job
# Stage 1: Separate into mixed_instrumental + mixed_vocals
instrumental_preset = getattr(self, 'instrumental_preset', None)
stage1_kwargs = {
"timeout": 1800, # 30 minutes
"poll_interval": 15,
"download": True,
"output_dir": stems_dir,
"output_format": self.lossless_output_format.lower(),
"custom_output_names": {"Vocals": f"{file_prefix}_mixed_vocals", "Instrumental": f"{file_prefix}_mixed_instrumental"},
}
if instrumental_preset:
self.logger.info(f"Stage 1: Using ensemble preset '{instrumental_preset}'")
stage1_kwargs["preset"] = instrumental_preset
else:
stage1_models = []
if self.clean_instrumental_model:
stage1_models.append(self.clean_instrumental_model)
stage1_models.extend(self.other_stems_models)
self.logger.info(f"Stage 1: Using explicit models: {stage1_models}")
stage1_kwargs["models"] = stage1_models
stage1_result = api_client.separate_audio_and_wait(
audio_file,
models=stage1_models,
timeout=1800, # 30 minutes timeout
poll_interval=15, # Check every 15 seconds
download=True,
output_dir=stems_dir,
output_format=self.lossless_output_format.lower()
**stage1_kwargs,
)
if stage1_result["status"] != "completed":
raise Exception(f"Stage 1 remote audio separation failed: {stage1_result.get('error', 'Unknown error')}")
self.logger.info(f"Stage 1 completed. Downloaded {len(stage1_result['downloaded_files'])} files")
# Check if we actually got the expected files for Stage 1
if len(stage1_result["downloaded_files"]) == 0:
error_msg = ("Stage 1 audio separation completed successfully but no files were downloaded. "
"This indicates a filename encoding or API issue in the audio-separator remote service. "
f"Expected files for models {stage1_models} but got 0.")
self.logger.error(error_msg)
raise Exception(error_msg)
# Organize the stage 1 results
result = self._organize_stage1_remote_results(
stage1_result["downloaded_files"], artist_title, track_output_dir, stems_dir
)
# Validate that we got the essential clean instrumental outputs
if not result["clean_instrumental"].get("vocals") or not result["clean_instrumental"].get("instrumental"):
missing = []
if not result["clean_instrumental"].get("vocals"):
missing.append("clean vocals")
if not result["clean_instrumental"].get("instrumental"):
missing.append("clean instrumental")
error_msg = (f"Stage 1 completed but failed to produce essential clean instrumental outputs: {', '.join(missing)}. "
"This may indicate a model naming or file organization issue in the remote API.")
self.logger.error(error_msg)
raise Exception(error_msg)
# Stage 2: Process clean vocals with backing vocals models (if we have both)
if result["clean_instrumental"].get("vocals") and self.backing_vocals_models:
self.logger.info(f"Stage 2: Processing clean vocals for backing vocals separation...")
self.logger.info(f"Stage 1 completed. Downloaded {len(stage1_result.get('downloaded_files', []))} files")
if len(stage1_result.get("downloaded_files", [])) == 0:
raise Exception("Stage 1 completed but no files were downloaded.")
# Organize Stage 1 results by known filenames
fmt = self.lossless_output_format.lower()
mixed_vocals_path = os.path.join(stems_dir, f"{file_prefix}_mixed_vocals.{fmt}")
mixed_instrumental_path = os.path.join(stems_dir, f"{file_prefix}_mixed_instrumental.{fmt}")
result = {"clean_instrumental": {}, "other_stems": {}, "backing_vocals": {}, "combined_instrumentals": {}}
if os.path.exists(mixed_vocals_path):
result["clean_instrumental"]["vocals"] = mixed_vocals_path
if os.path.exists(mixed_instrumental_path):
# Move instrumental to track_output_dir (not stems_dir) per existing convention
final_instrumental_path = os.path.join(track_output_dir, f"{file_prefix}_mixed_instrumental.{fmt}")
if mixed_instrumental_path != final_instrumental_path:
shutil.move(mixed_instrumental_path, final_instrumental_path)
result["clean_instrumental"]["instrumental"] = final_instrumental_path
# Validate essential outputs
missing = []
if not result["clean_instrumental"].get("vocals"):
missing.append("mixed_vocals")
if not result["clean_instrumental"].get("instrumental"):
missing.append("mixed_instrumental")
if missing:
downloaded = [os.path.basename(f) for f in stage1_result.get("downloaded_files", [])]
raise Exception(f"Stage 1 missing: {', '.join(missing)}. Downloaded: {downloaded}")
# Stage 2: Separate vocals into lead_vocals + backing_vocals
karaoke_preset = getattr(self, 'karaoke_preset', None)
has_backing_config = karaoke_preset or self.backing_vocals_models
if result["clean_instrumental"].get("vocals") and has_backing_config:
self.logger.info(f"Stage 2: Processing mixed vocals for backing vocals separation...")
vocals_path = result["clean_instrumental"]["vocals"]
stage2_kwargs = {
"timeout": 900, # 15 minutes
"poll_interval": 10,
"download": True,
"output_dir": stems_dir,
"output_format": self.lossless_output_format.lower(),
"custom_output_names": {"Vocals": f"{file_prefix}_lead_vocals", "Instrumental": f"{file_prefix}_backing_vocals"},
}
if karaoke_preset:
self.logger.info(f"Stage 2: Using ensemble preset '{karaoke_preset}'")
stage2_kwargs["preset"] = karaoke_preset
else:
self.logger.info(f"Stage 2: Using explicit models: {self.backing_vocals_models}")
stage2_kwargs["models"] = self.backing_vocals_models
stage2_result = api_client.separate_audio_and_wait(
vocals_path,
models=self.backing_vocals_models,
timeout=900, # 15 minutes timeout for backing vocals
poll_interval=10,
download=True,
output_dir=stems_dir,
output_format=self.lossless_output_format.lower()
**stage2_kwargs,
)
if stage2_result["status"] == "completed":
self.logger.info(f"Stage 2 completed. Downloaded {len(stage2_result['downloaded_files'])} files")
# Check if we actually got the expected files
if len(stage2_result["downloaded_files"]) == 0:
error_msg = ("Stage 2 backing vocals separation completed successfully but no files were downloaded. "
"This indicates a filename encoding or API issue in the audio-separator remote service. "
"Expected 2 files (lead vocals + backing vocals) but got 0.")
self.logger.error(error_msg)
raise Exception(error_msg)
# Organize the stage 2 results (backing vocals)
backing_vocals_result = self._organize_stage2_remote_results(
stage2_result["downloaded_files"], artist_title, stems_dir
)
# Validate stage 2 outputs — each model should produce both lead_vocals and backing_vocals
for bv_model, paths in backing_vocals_result.items():
missing = []
if not paths.get("lead_vocals"):
missing.append("lead_vocals")
if not paths.get("backing_vocals"):
missing.append("backing_vocals")
if missing:
error_msg = (
f"Stage 2 completed but model {bv_model} is missing: {', '.join(missing)}. "
f"Got keys: {list(paths.keys())}. Downloaded {len(stage2_result['downloaded_files'])} files. "
"This may indicate an intermittent issue with the remote separation API."
)
self.logger.error(error_msg)
raise Exception(error_msg)
if stage2_result["status"] != "completed":
raise Exception(f"Stage 2 failed: {stage2_result.get('error', 'Unknown error')}")
result["backing_vocals"] = backing_vocals_result
else:
error_msg = f"Stage 2 backing vocals separation failed: {stage2_result.get('error', 'Unknown error')}"
self.logger.error(error_msg)
raise Exception(error_msg)
self.logger.info(f"Stage 2 completed. Downloaded {len(stage2_result.get('downloaded_files', []))} files")
if len(stage2_result.get("downloaded_files", [])) == 0:
raise Exception("Stage 2 completed but no files were downloaded.")
# Organize Stage 2 results by known filenames
lead_vocals_path = os.path.join(stems_dir, f"{file_prefix}_lead_vocals.{fmt}")
backing_vocals_path = os.path.join(stems_dir, f"{file_prefix}_backing_vocals.{fmt}")
# Use a generic key for the backing vocals model (preset name or first model)
bv_key = karaoke_preset or (self.backing_vocals_models[0] if self.backing_vocals_models else "karaoke")
result["backing_vocals"][bv_key] = {}
if os.path.exists(lead_vocals_path):
result["backing_vocals"][bv_key]["lead_vocals"] = lead_vocals_path
if os.path.exists(backing_vocals_path):
result["backing_vocals"][bv_key]["backing_vocals"] = backing_vocals_path
# Validate
missing = []
if not result["backing_vocals"][bv_key].get("lead_vocals"):
missing.append("lead_vocals")
if not result["backing_vocals"][bv_key].get("backing_vocals"):
missing.append("backing_vocals")
if missing:
downloaded = [os.path.basename(f) for f in stage2_result.get("downloaded_files", [])]
raise Exception(f"Stage 2 missing: {', '.join(missing)}. Downloaded: {downloaded}")
else:
result["backing_vocals"] = {}
@@ -71,7 +71,7 @@ class CorrectionOperations:
words=[
Word(
id=w["id"],
text=w["text"].strip(),
text=w["text"],
start_time=w["start_time"],
end_time=w["end_time"],
confidence=w.get("confidence"),
@@ -254,7 +254,11 @@ class LyricsLine:
# Add the word with its duration
duration = int(round((word.end_time - word.start_time) * 100))
# Apply case transformation to the word text
transformed_text = self._apply_case_transform(word.text)
# Defensive strip: Word.__post_init__ should already handle this,
# but embedded newlines in ASS dialogue events cause silent word
# loss so we guard against it at the output boundary too.
clean_word_text = word.text.replace("\n", "").strip()
transformed_text = self._apply_case_transform(clean_word_text)
text += r"{\kf" + str(duration) + r"}" + transformed_text + " "
prev_end_time = word.end_time # Track the actual end time of the word
+10
View File
@@ -16,6 +16,16 @@ class Word:
# New: Track if this word was created during correction
created_during_correction: bool = False
def __post_init__(self):
"""Strip whitespace/newlines from text.
Word text from transcription pipelines may contain embedded newline
characters at segment boundaries (e.g., "spell\\n"). These corrupt ASS
subtitle output by splitting dialogue events across file lines, causing
words after the newline to be silently dropped by video renderers.
"""
self.text = self.text.strip()
def to_dict(self) -> Dict[str, Any]:
"""Convert Word to dictionary for JSON serialization."""
d = asdict(self)
Generated
+59 -84
View File
@@ -350,14 +350,14 @@ files = [
[[package]]
name = "audio-separator"
version = "0.40.0"
version = "0.43.0"
description = "Easy to use audio stem separation, using various models from UVR trained primarily by @Anjok07"
optional = false
python-versions = ">=3.10"
groups = ["main"]
files = [
{file = "audio_separator-0.40.0-py3-none-any.whl", hash = "sha256:aa67f6bc5625b7c5362f6fd5a4faba2d5b8a5ab8aff1205c0b4f06d35c2f7ac9"},
{file = "audio_separator-0.40.0.tar.gz", hash = "sha256:956dceb7f3eba342ca2278c241ca7b86a04c015afd890b7c580d74af00226363"},
{file = "audio_separator-0.43.0-py3-none-any.whl", hash = "sha256:7315f26fd0715e5cb3ddd02532565f2b63f77f208391463ad6bccd7cf4583454"},
{file = "audio_separator-0.43.0.tar.gz", hash = "sha256:4628c2f1c43fc2d17a93e5451921bd6f5f720791d2bbf4bb6b70bda7114ac633"},
]
[package.dependencies]
@@ -702,18 +702,6 @@ dev = ["cachecontrol[filecache,redis]", "cheroot (>=11.1.2)", "cherrypy", "codes
filecache = ["filelock (>=3.8.0)"]
redis = ["redis (>=2.10.5)"]
[[package]]
name = "cachetools"
version = "6.2.4"
description = "Extensible memoizing collections and decorators"
optional = false
python-versions = ">=3.9"
groups = ["main"]
files = [
{file = "cachetools-6.2.4-py3-none-any.whl", hash = "sha256:69a7a52634fed8b8bf6e24a050fb60bff1c9bd8f6d24572b99c32d4e71e62a51"},
{file = "cachetools-6.2.4.tar.gz", hash = "sha256:82c5c05585e70b6ba2d3ae09ea60b79548872185d2f24ae1f2709d37299fd607"},
]
[[package]]
name = "catalogue"
version = "2.0.10"
@@ -2477,14 +2465,14 @@ grpcio-gcp = ["grpcio-gcp (>=0.2.2,<1.0.0)"]
[[package]]
name = "google-api-python-client"
version = "2.187.0"
version = "2.193.0"
description = "Google API Client Library for Python"
optional = false
python-versions = ">=3.7"
groups = ["main"]
files = [
{file = "google_api_python_client-2.187.0-py3-none-any.whl", hash = "sha256:d8d0f6d85d7d1d10bdab32e642312ed572bdc98919f72f831b44b9a9cebba32f"},
{file = "google_api_python_client-2.187.0.tar.gz", hash = "sha256:e98e8e8f49e1b5048c2f8276473d6485febc76c9c47892a8b4d1afa2c9ec8278"},
{file = "google_api_python_client-2.193.0-py3-none-any.whl", hash = "sha256:c42aa324b822109901cfecab5dc4fc3915d35a7b376835233c916c70610322db"},
{file = "google_api_python_client-2.193.0.tar.gz", hash = "sha256:8f88d16e89d11341e0a8b199cafde0fb7e6b44260dffb88d451577cbd1bb5d33"},
]
[package.dependencies]
@@ -2496,31 +2484,31 @@ uritemplate = ">=3.0.1,<5"
[[package]]
name = "google-auth"
version = "2.46.0"
version = "2.49.1"
description = "Google Authentication Library"
optional = false
python-versions = ">=3.7"
python-versions = ">=3.8"
groups = ["main"]
files = [
{file = "google_auth-2.46.0-py3-none-any.whl", hash = "sha256:fa51659c3745cb7024dd073f4ab766222767ea5f7dee2472110eaa03c9dbd2cb"},
{file = "google_auth-2.46.0.tar.gz", hash = "sha256:cb04c071a73394a6e3b9e48c1a7f48506001175b33e9679587a0f5320a21a34d"},
{file = "google_auth-2.49.1-py3-none-any.whl", hash = "sha256:195ebe3dca18eddd1b3db5edc5189b76c13e96f29e73043b923ebcf3f1a860f7"},
{file = "google_auth-2.49.1.tar.gz", hash = "sha256:16d40da1c3c5a0533f57d268fe72e0ebb0ae1cc3b567024122651c045d879b64"},
]
[package.dependencies]
cachetools = ">=2.0.0,<7.0"
cryptography = ">=38.0.3"
pyasn1-modules = ">=0.2.1"
requests = {version = ">=2.20.0,<3.0.0", optional = true, markers = "extra == \"requests\""}
rsa = ">=3.1.4,<5"
[package.extras]
aiohttp = ["aiohttp (>=3.6.2,<4.0.0)", "requests (>=2.20.0,<3.0.0)"]
cryptography = ["cryptography (<39.0.0) ; python_version < \"3.8\"", "cryptography (>=38.0.3)"]
enterprise-cert = ["cryptography", "pyopenssl"]
pyjwt = ["cryptography (<39.0.0) ; python_version < \"3.8\"", "cryptography (>=38.0.3)", "pyjwt (>=2.0)"]
pyopenssl = ["cryptography (<39.0.0) ; python_version < \"3.8\"", "cryptography (>=38.0.3)", "pyopenssl (>=20.0.0)"]
cryptography = ["cryptography (>=38.0.3)"]
enterprise-cert = ["pyopenssl"]
pyjwt = ["pyjwt (>=2.0)"]
pyopenssl = ["pyopenssl (>=20.0.0)"]
reauth = ["pyu2f (>=0.1.5)"]
requests = ["requests (>=2.20.0,<3.0.0)"]
testing = ["aiohttp (<3.10.0)", "aiohttp (>=3.6.2,<4.0.0)", "aioresponses", "cryptography (<39.0.0) ; python_version < \"3.8\"", "cryptography (<39.0.0) ; python_version < \"3.8\"", "cryptography (>=38.0.3)", "cryptography (>=38.0.3)", "flask", "freezegun", "grpcio", "oauth2client", "packaging", "pyjwt (>=2.0)", "pyopenssl (<24.3.0)", "pyopenssl (>=20.0.0)", "pytest", "pytest-asyncio", "pytest-cov", "pytest-localserver", "pyu2f (>=0.1.5)", "requests (>=2.20.0,<3.0.0)", "responses", "urllib3"]
rsa = ["rsa (>=3.1.4,<5)"]
testing = ["aiohttp (<3.10.0)", "aiohttp (>=3.6.2,<4.0.0)", "aioresponses", "flask", "freezegun", "grpcio", "packaging", "pyjwt (>=2.0)", "pyopenssl (<24.3.0)", "pyopenssl (>=20.0.0)", "pytest", "pytest-asyncio", "pytest-cov", "pytest-localserver", "pyu2f (>=0.1.5)", "requests (>=2.20.0,<3.0.0)", "responses", "urllib3"]
urllib3 = ["packaging", "urllib3"]
[[package]]
@@ -2541,18 +2529,18 @@ httplib2 = ">=0.19.0,<1.0.0"
[[package]]
name = "google-auth-oauthlib"
version = "1.2.2"
version = "1.3.0"
description = "Google Authentication Library"
optional = false
python-versions = ">=3.6"
python-versions = ">=3.7"
groups = ["main"]
files = [
{file = "google_auth_oauthlib-1.2.2-py3-none-any.whl", hash = "sha256:fd619506f4b3908b5df17b65f39ca8d66ea56986e5472eb5978fd8f3786f00a2"},
{file = "google_auth_oauthlib-1.2.2.tar.gz", hash = "sha256:11046fb8d3348b296302dd939ace8af0a724042e8029c1b872d87fabc9f41684"},
{file = "google_auth_oauthlib-1.3.0-py3-none-any.whl", hash = "sha256:386b3fb85cf4a5b819c6ad23e3128d975216b4cac76324de1d90b128aaf38f29"},
{file = "google_auth_oauthlib-1.3.0.tar.gz", hash = "sha256:cd39e807ac7229d6b8b9c1e297321d36fcc8a9e4857dff4301870985df51a528"},
]
[package.dependencies]
google-auth = ">=2.15.0"
google-auth = ">=2.15.0,<2.43.0 || >2.43.0,<2.44.0 || >2.44.0,<2.45.0 || >2.45.0,<3.0.0"
requests-oauthlib = ">=0.7.0"
[package.extras]
@@ -2579,26 +2567,26 @@ grpc = ["grpcio (>=1.38.0,<2.0.0) ; python_version < \"3.14\"", "grpcio (>=1.75.
[[package]]
name = "google-cloud-firestore"
version = "2.22.0"
version = "2.26.0"
description = "Google Cloud Firestore API client library"
optional = false
python-versions = ">=3.7"
groups = ["main"]
files = [
{file = "google_cloud_firestore-2.22.0-py3-none-any.whl", hash = "sha256:47652ca74a77903c192fe194f646871ca2f881e56c30e7f573a9782d3bdbb610"},
{file = "google_cloud_firestore-2.22.0.tar.gz", hash = "sha256:9d6a5bdefb30ed5ca94a7cb3560873352a3dbf868957ef789e6e74d086d52d82"},
{file = "google_cloud_firestore-2.26.0-py3-none-any.whl", hash = "sha256:307e6d3aed1a15e7083d9bac1871cb439be17620e035de960225bb00acc771de"},
{file = "google_cloud_firestore-2.26.0.tar.gz", hash = "sha256:103fc2bdedcb801a31590fef9a0d50754ee63b803946f9afc904817c85bd935d"},
]
[package.dependencies]
google-api-core = {version = ">=1.34.0,<2.0.dev0 || >=2.11.dev0,<3.0.0", extras = ["grpc"]}
google-api-core = {version = ">=1.34.1,<2.0.dev0 || >=2.11.dev0,<3.0.0", extras = ["grpc"]}
google-auth = ">=2.14.1,<2.24.0 || >2.24.0,<2.25.0 || >2.25.0,<3.0.0"
google-cloud-core = ">=1.4.1,<3.0.0"
grpcio = ">=1.33.2,<2.0.0"
proto-plus = [
{version = ">=1.25.0,<2.0.0", markers = "python_version >= \"3.13\""},
{version = ">=1.22.2,<2.0.0", markers = "python_version >= \"3.11\""},
{version = ">=1.22.0,<2.0.0"},
{version = ">=1.22.3,<2.0.0"},
]
protobuf = ">=3.20.2,<4.21.0 || >4.21.0,<4.21.1 || >4.21.1,<4.21.2 || >4.21.2,<4.21.3 || >4.21.3,<4.21.4 || >4.21.4,<4.21.5 || >4.21.5,<7.0.0dev"
protobuf = ">=3.20.2,<4.21.0 || >4.21.0,<4.21.1 || >4.21.1,<4.21.2 || >4.21.2,<4.21.3 || >4.21.3,<4.21.4 || >4.21.4,<4.21.5 || >4.21.5,<7.0.0"
[[package]]
name = "google-cloud-monitoring"
@@ -2627,14 +2615,14 @@ pandas = ["pandas (>=0.23.2)"]
[[package]]
name = "google-cloud-run"
version = "0.13.0"
version = "0.15.0"
description = "Google Cloud Run API client library"
optional = false
python-versions = ">=3.7"
groups = ["main"]
files = [
{file = "google_cloud_run-0.13.0-py3-none-any.whl", hash = "sha256:ec61a8ec2e38e04d482643ef8a6f371630c8a7d6173ab6c69c1d80ad9754220f"},
{file = "google_cloud_run-0.13.0.tar.gz", hash = "sha256:97534ad76d3a2c2047d124c0a0a294a4822fcc24331eba0f294cadfb193c49ad"},
{file = "google_cloud_run-0.15.0-py3-none-any.whl", hash = "sha256:e457ecb1f7ff9ec2a64aed99611383adbf89fe9e02f3dd268874122b23d22601"},
{file = "google_cloud_run-0.15.0.tar.gz", hash = "sha256:158f264643f982bfa4f4f18f9e28c56ea00ea95c248bc8a746e159b538afab57"},
]
[package.dependencies]
@@ -2673,14 +2661,14 @@ protobuf = ">=3.20.2,<4.21.0 || >4.21.0,<4.21.1 || >4.21.1,<4.21.2 || >4.21.2,<4
[[package]]
name = "google-cloud-storage"
version = "3.7.0"
version = "3.10.1"
description = "Google Cloud Storage API client library"
optional = false
python-versions = ">=3.7"
python-versions = ">=3.10"
groups = ["main"]
files = [
{file = "google_cloud_storage-3.7.0-py3-none-any.whl", hash = "sha256:469bc9540936e02f8a4bfd1619e9dca1e42dec48f95e4204d783b36476a15093"},
{file = "google_cloud_storage-3.7.0.tar.gz", hash = "sha256:9ce59c65f4d6e372effcecc0456680a8d73cef4f2dc9212a0704799cb3d69237"},
{file = "google_cloud_storage-3.10.1-py3-none-any.whl", hash = "sha256:a72f656759b7b99bda700f901adcb3425a828d4a29f911bc26b3ea79c5b1217f"},
{file = "google_cloud_storage-3.10.1.tar.gz", hash = "sha256:97db9aa4460727982040edd2bd13ff3d5e2260b5331ad22895802da1fc2a5286"},
]
[package.dependencies]
@@ -2694,18 +2682,19 @@ requests = ">=2.22.0,<3.0.0"
[package.extras]
grpc = ["google-api-core[grpc] (>=2.27.0,<3.0.0)", "grpc-google-iam-v1 (>=0.14.0,<1.0.0)", "grpcio (>=1.33.2,<2.0.0) ; python_version < \"3.14\"", "grpcio (>=1.75.1,<2.0.0) ; python_version >= \"3.14\"", "grpcio-status (>=1.76.0,<2.0.0)", "proto-plus (>=1.22.3,<2.0.0) ; python_version < \"3.13\"", "proto-plus (>=1.25.0,<2.0.0) ; python_version >= \"3.13\"", "protobuf (>=3.20.2,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5,<7.0.0)"]
protobuf = ["protobuf (>=3.20.2,<7.0.0)"]
testing = ["PyYAML", "black", "brotli", "coverage", "flake8", "google-cloud-iam", "google-cloud-kms", "google-cloud-pubsub", "google-cloud-testutils", "google-cloud-testutils", "mock", "numpy", "opentelemetry-sdk", "psutil", "py-cpuinfo", "pyopenssl", "pytest", "pytest-asyncio", "pytest-benchmark", "pytest-cov", "pytest-rerunfailures", "pytest-xdist"]
tracing = ["opentelemetry-api (>=1.1.0,<2.0.0)"]
[[package]]
name = "google-cloud-tasks"
version = "2.20.0"
version = "2.21.0"
description = "Google Cloud Tasks API client library"
optional = false
python-versions = ">=3.7"
groups = ["main"]
files = [
{file = "google_cloud_tasks-2.20.0-py3-none-any.whl", hash = "sha256:3d261a8d1f3ab90454b3e2780f484373031b0b6061506571190dc5c300768422"},
{file = "google_cloud_tasks-2.20.0.tar.gz", hash = "sha256:733cf440a25d34fe1cdb4e6c946d173bd83a2c22c3d7b2c76a24591f3c160412"},
{file = "google_cloud_tasks-2.21.0-py3-none-any.whl", hash = "sha256:4bf288876892a0afac30658fc42925ccb732d3c4433a8ea568de1d67fde738f2"},
{file = "google_cloud_tasks-2.21.0.tar.gz", hash = "sha256:d28f33248553faf0ff029e1981aab56cd13bd933635c3bc33aa187675e7e14d1"},
]
[package.dependencies]
@@ -2946,20 +2935,20 @@ protobuf = ["grpcio-tools (>=1.76.0)"]
[[package]]
name = "grpcio-status"
version = "1.76.0"
version = "1.71.2"
description = "Status proto mapping for gRPC"
optional = false
python-versions = ">=3.9"
groups = ["main"]
files = [
{file = "grpcio_status-1.76.0-py3-none-any.whl", hash = "sha256:380568794055a8efbbd8871162df92012e0228a5f6dffaf57f2a00c534103b18"},
{file = "grpcio_status-1.76.0.tar.gz", hash = "sha256:25fcbfec74c15d1a1cb5da3fab8ee9672852dc16a5a9eeb5baf7d7a9952943cd"},
{file = "grpcio_status-1.71.2-py3-none-any.whl", hash = "sha256:803c98cb6a8b7dc6dbb785b1111aed739f241ab5e9da0bba96888aa74704cfd3"},
{file = "grpcio_status-1.71.2.tar.gz", hash = "sha256:c7a97e176df71cdc2c179cd1847d7fc86cca5832ad12e9798d7fed6b7a1aab50"},
]
[package.dependencies]
googleapis-common-protos = ">=1.5.5"
grpcio = ">=1.76.0"
protobuf = ">=6.31.1,<7.0.0"
grpcio = ">=1.71.2"
protobuf = ">=5.26.1,<6.0dev"
[[package]]
name = "h11"
@@ -6748,22 +6737,23 @@ testing = ["google-api-core (>=1.31.5)"]
[[package]]
name = "protobuf"
version = "6.33.2"
version = "5.29.6"
description = ""
optional = false
python-versions = ">=3.9"
python-versions = ">=3.8"
groups = ["main"]
files = [
{file = "protobuf-6.33.2-cp310-abi3-win32.whl", hash = "sha256:87eb388bd2d0f78febd8f4c8779c79247b26a5befad525008e49a6955787ff3d"},
{file = "protobuf-6.33.2-cp310-abi3-win_amd64.whl", hash = "sha256:fc2a0e8b05b180e5fc0dd1559fe8ebdae21a27e81ac77728fb6c42b12c7419b4"},
{file = "protobuf-6.33.2-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:d9b19771ca75935b3a4422957bc518b0cecb978b31d1dd12037b088f6bcc0e43"},
{file = "protobuf-6.33.2-cp39-abi3-manylinux2014_aarch64.whl", hash = "sha256:b5d3b5625192214066d99b2b605f5783483575656784de223f00a8d00754fc0e"},
{file = "protobuf-6.33.2-cp39-abi3-manylinux2014_s390x.whl", hash = "sha256:8cd7640aee0b7828b6d03ae518b5b4806fdfc1afe8de82f79c3454f8aef29872"},
{file = "protobuf-6.33.2-cp39-abi3-manylinux2014_x86_64.whl", hash = "sha256:1f8017c48c07ec5859106533b682260ba3d7c5567b1ca1f24297ce03384d1b4f"},
{file = "protobuf-6.33.2-cp39-cp39-win32.whl", hash = "sha256:7109dcc38a680d033ffb8bf896727423528db9163be1b6a02d6a49606dcadbfe"},
{file = "protobuf-6.33.2-cp39-cp39-win_amd64.whl", hash = "sha256:2981c58f582f44b6b13173e12bb8656711189c2a70250845f264b877f00b1913"},
{file = "protobuf-6.33.2-py3-none-any.whl", hash = "sha256:7636aad9bb01768870266de5dc009de2d1b936771b38a793f73cbbf279c91c5c"},
{file = "protobuf-6.33.2.tar.gz", hash = "sha256:56dc370c91fbb8ac85bc13582c9e373569668a290aa2e66a590c2a0d35ddb9e4"},
{file = "protobuf-5.29.6-cp310-abi3-win32.whl", hash = "sha256:62e8a3114992c7c647bce37dcc93647575fc52d50e48de30c6fcb28a6a291eb1"},
{file = "protobuf-5.29.6-cp310-abi3-win_amd64.whl", hash = "sha256:7e6ad413275be172f67fdee0f43484b6de5a904cc1c3ea9804cb6fe2ff366eda"},
{file = "protobuf-5.29.6-cp38-abi3-macosx_10_9_universal2.whl", hash = "sha256:b5a169e664b4057183a34bdc424540e86eea47560f3c123a0d64de4e137f9269"},
{file = "protobuf-5.29.6-cp38-abi3-manylinux2014_aarch64.whl", hash = "sha256:a8866b2cff111f0f863c1b3b9e7572dc7eaea23a7fae27f6fc613304046483e6"},
{file = "protobuf-5.29.6-cp38-abi3-manylinux2014_x86_64.whl", hash = "sha256:e3387f44798ac1106af0233c04fb8abf543772ff241169946f698b3a9a3d3ab9"},
{file = "protobuf-5.29.6-cp38-cp38-win32.whl", hash = "sha256:36ade6ff88212e91aef4e687a971a11d7d24d6948a66751abc1b3238648f5d05"},
{file = "protobuf-5.29.6-cp38-cp38-win_amd64.whl", hash = "sha256:831e2da16b6cc9d8f1654c041dd594eda43391affd3c03a91bea7f7f6da106d6"},
{file = "protobuf-5.29.6-cp39-cp39-win32.whl", hash = "sha256:cb4c86de9cd8a7f3a256b9744220d87b847371c6b2f10bde87768918ef33ba49"},
{file = "protobuf-5.29.6-cp39-cp39-win_amd64.whl", hash = "sha256:76e07e6567f8baf827137e8d5b8204b6c7b6488bbbff1bf0a72b383f77999c18"},
{file = "protobuf-5.29.6-py3-none-any.whl", hash = "sha256:6b9edb641441b2da9fa8f428760fc136a49cf97a52076010cf22a2ff73438a86"},
{file = "protobuf-5.29.6.tar.gz", hash = "sha256:da9ee6a5424b6b30fd5e45c5ea663aef540ca95f9ad99d1e887e819cdf9b8723"},
]
[[package]]
@@ -7872,21 +7862,6 @@ files = [
einops = ">=0.7"
torch = ">=2.0"
[[package]]
name = "rsa"
version = "4.9.1"
description = "Pure-Python RSA implementation"
optional = false
python-versions = "<4,>=3.6"
groups = ["main"]
files = [
{file = "rsa-4.9.1-py3-none-any.whl", hash = "sha256:68635866661c6836b8d39430f97a996acbd61bfa49406748ea243539fe239762"},
{file = "rsa-4.9.1.tar.gz", hash = "sha256:e7bdbfdb5497da4c07dfd35530e1a902659db6ff241e39d9953cad06ebd0ae75"},
]
[package.dependencies]
pyasn1 = ">=0.1.3"
[[package]]
name = "rtfde"
version = "0.1.2.2"
@@ -10705,4 +10680,4 @@ local-whisper = ["whisper-timestamped"]
[metadata]
lock-version = "2.1"
python-versions = ">=3.10,<3.14"
content-hash = "7acf9e306a9ac7b7a4547eb130be6747cb522cb80f16b0c914467e4a252d3dcd"
content-hash = "bfb710412104ada6da5504e2afb3181da05cac4d6ed1238d08e9a712c254f22d"
+12 -12
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.147.0"
version = "0.150.4"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"
@@ -30,13 +30,13 @@ lyricsgenius = ">=3"
fetch-lyrics-from-genius = ">=0.1"
pillow = ">=10.1"
pyinstaller = ">=6.3"
google-api-python-client = "*"
google-auth = "*"
google-auth-oauthlib = "*"
google-auth-httplib2 = "*"
google-api-python-client = "2.193.0"
google-auth = "2.49.1"
google-auth-oauthlib = "1.3.0"
google-auth-httplib2 = "0.3.0"
thefuzz = ">=0.22"
numpy = ">=2"
audio-separator = { version = ">=0.34.0", extras = ["cpu"] }
audio-separator = { version = ">=0.43.0", extras = ["cpu"] }
lyrics-converter = ">=0.2.1"
# lyrics_transcriber is now a subpackage of karaoke_gen (karaoke_gen/lyrics_transcriber/)
# Dependencies from vendored lyrics_transcriber:
@@ -87,12 +87,12 @@ pydantic = ">=2.5.0"
pydantic-settings = ">=2.1.0"
httpx = ">=0.25.0"
tenacity = "^8.2.0" # Retry logic for external service calls
google-cloud-firestore = ">=2.14.0"
google-cloud-storage = ">=2.14.0"
google-cloud-secret-manager = ">=2.18.0"
google-cloud-monitoring = ">=2.19.0" # Cloud Monitoring for YouTube API quota metrics
google-cloud-tasks = ">=2.16.0" # Cloud Tasks for worker coordination (Phase 1 scalability)
google-cloud-run = ">=0.10.0" # Cloud Run Jobs for long-running video encoding (Phase 2 scalability)
google-cloud-firestore = "2.26.0"
google-cloud-storage = "3.10.1"
google-cloud-secret-manager = "2.26.0"
google-cloud-monitoring = "2.29.1" # Cloud Monitoring for YouTube API quota metrics
google-cloud-tasks = "2.21.0" # Cloud Tasks for worker coordination (Phase 1 scalability)
google-cloud-run = "0.15.0" # Cloud Run Jobs for long-running video encoding (Phase 2 scalability)
python-dotenv = ">=1.0.0"
pydub = ">=0.25.1"
# Payment and email services
+59 -58
View File
@@ -37,67 +37,71 @@ class TestRemoteAudioSeparation(unittest.TestCase):
@patch('karaoke_gen.audio_processor.REMOTE_API_AVAILABLE', True)
@patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient')
def test_remote_api_detection(self, mock_client_class):
"""Test that remote API is detected when environment variable is set."""
"""Test that remote API is detected and two-stage separation works with custom_output_names."""
mock_client = MagicMock()
mock_client_class.return_value = mock_client
# Mock the API responses for the two-stage approach
mock_client.separate_audio_and_wait.side_effect = [
# Stage 1: Clean instrumental + other stems
{
"status": "completed",
"downloaded_files": [
"/tmp/test_file_(Vocals)_model_bs_roformer_ep_317_sdr_12.9755.flac",
"/tmp/test_file_(Instrumental)_model_bs_roformer_ep_317_sdr_12.9755.flac",
"/tmp/test_file_(Drums)_htdemucs_6s.flac",
"/tmp/test_file_(Bass)_htdemucs_6s.flac",
"/tmp/test_file_(Other)_htdemucs_6s.flac"
]
},
# Stage 2: Backing vocals
{
"status": "completed",
"downloaded_files": [
"/tmp/test_vocals_(Vocals)_mel_band_roformer_karaoke_aufr33_viperx_sdr_10.flac",
"/tmp/test_vocals_(Instrumental)_mel_band_roformer_karaoke_aufr33_viperx_sdr_10.flac"
]
}
]
# Mock file operations
with patch('os.path.exists', return_value=True), \
patch('shutil.move'), \
patch('os.makedirs'), \
patch('builtins.open', create=True) as mock_open, \
patch('os.path.abspath', side_effect=lambda x: x), \
patch('sys.platform', 'darwin'), \
patch('os.system'), \
patch.object(self.audio_processor, '_generate_combined_instrumentals', return_value={"mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt": "/tmp/combined.flac"}), \
# Create stems dir and expected output files
stems_dir = os.path.join(self.temp_dir, "stems")
os.makedirs(stems_dir, exist_ok=True)
# File prefix uses artist_title (no job_id set on this processor)
prefix = "Test Artist - Test Song"
fmt = "flac"
vocals_path = os.path.join(stems_dir, f"{prefix}_mixed_vocals.{fmt}")
instrumental_path = os.path.join(stems_dir, f"{prefix}_mixed_instrumental.{fmt}")
lead_vocals_path = os.path.join(stems_dir, f"{prefix}_lead_vocals.{fmt}")
backing_vocals_path = os.path.join(stems_dir, f"{prefix}_backing_vocals.{fmt}")
# Create fake files that the API would "download"
for path in [vocals_path, instrumental_path]:
with open(path, "w") as f:
f.write("fake")
# Stage 1 response
stage1_response = {
"status": "completed",
"downloaded_files": [vocals_path, instrumental_path],
}
# Stage 2 response — create the files too
for path in [lead_vocals_path, backing_vocals_path]:
with open(path, "w") as f:
f.write("fake")
stage2_response = {
"status": "completed",
"downloaded_files": [lead_vocals_path, backing_vocals_path],
}
mock_client.separate_audio_and_wait.side_effect = [stage1_response, stage2_response]
# Create a fake input file
input_file = os.path.join(self.temp_dir, "test_audio.wav")
with open(input_file, "w") as f:
f.write("fake input")
with patch.object(self.audio_processor, '_generate_combined_instrumentals', return_value={}), \
patch.object(self.audio_processor, '_normalize_audio_files'):
result = self.audio_processor.process_audio_separation(
"/tmp/test_audio.wav",
"Test Artist - Test Song",
self.temp_dir
input_file,
"Test Artist - Test Song",
self.temp_dir,
)
# Verify remote API was called twice (stage 1 and stage 2)
self.assertTrue(mock_client_class.called)
self.assertEqual(mock_client.separate_audio_and_wait.call_count, 2)
# Verify stage 1 call parameters (original song with clean + other stems models)
stage1_call_args = mock_client.separate_audio_and_wait.call_args_list[0]
self.assertEqual(stage1_call_args[0][0], "/tmp/test_audio.wav") # original audio file
self.assertIn("model_bs_roformer_ep_317_sdr_12.9755.ckpt", stage1_call_args[1]["models"])
self.assertIn("htdemucs_6s.yaml", stage1_call_args[1]["models"])
# Stage 1 should NOT include backing vocals models
self.assertNotIn("mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt", stage1_call_args[1]["models"])
# Verify stage 2 call parameters (clean vocals with backing vocals models)
stage2_call_args = mock_client.separate_audio_and_wait.call_args_list[1]
# Stage 2 should process the vocals file from stage 1
self.assertTrue(stage2_call_args[0][0].endswith("(Vocals model_bs_roformer_ep_317_sdr_12.9755.ckpt).FLAC"))
self.assertEqual(stage2_call_args[1]["models"], ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"])
# Verify stage 1 used custom_output_names
stage1_kwargs = mock_client.separate_audio_and_wait.call_args_list[0][1]
self.assertIn("custom_output_names", stage1_kwargs)
self.assertIn("mixed_vocals", stage1_kwargs["custom_output_names"]["Vocals"])
self.assertIn("mixed_instrumental", stage1_kwargs["custom_output_names"]["Instrumental"])
# Verify stage 2 used custom_output_names
stage2_kwargs = mock_client.separate_audio_and_wait.call_args_list[1][1]
self.assertIn("custom_output_names", stage2_kwargs)
self.assertIn("lead_vocals", stage2_kwargs["custom_output_names"]["Vocals"])
self.assertIn("backing_vocals", stage2_kwargs["custom_output_names"]["Instrumental"])
@patch.dict(os.environ, {}, clear=True) # Clear AUDIO_SEPARATOR_API_URL
def test_local_fallback_when_no_env_var(self):
@@ -298,9 +302,7 @@ class TestRemoteAudioSeparation(unittest.TestCase):
# Verify the exception message is clear and helpful
error_message = str(context.exception)
self.assertIn("Stage 2 backing vocals separation completed successfully but no files were downloaded", error_message)
self.assertIn("filename encoding or API issue", error_message)
self.assertIn("Expected 2 files", error_message)
self.assertIn("Stage 2 completed but no files were downloaded", error_message)
@patch.dict(os.environ, {'AUDIO_SEPARATOR_API_URL': 'https://test-api.com'})
@@ -331,8 +333,7 @@ class TestRemoteAudioSeparation(unittest.TestCase):
# Verify the exception message is clear and helpful
error_message = str(context.exception)
self.assertIn("Stage 1 audio separation completed successfully but no files were downloaded", error_message)
self.assertIn("filename encoding or API issue", error_message)
self.assertIn("Stage 1 completed but no files were downloaded", error_message)
if __name__ == '__main__':
+98
View File
@@ -0,0 +1,98 @@
"""Tests for Word text sanitization — ensures embedded newlines never reach ASS output."""
import pytest
from karaoke_gen.lyrics_transcriber.types import Word, LyricsSegment
from karaoke_gen.lyrics_transcriber.output.ass.lyrics_line import LyricsLine
from karaoke_gen.lyrics_transcriber.output.ass.config import ScreenConfig
class TestWordTextSanitization:
"""Word.__post_init__ must strip whitespace/newlines from text."""
def test_trailing_newline_stripped(self):
word = Word(id="w1", text="spell\n", start_time=1.0, end_time=2.0)
assert word.text == "spell"
def test_trailing_double_newline_stripped(self):
word = Word(id="w1", text="end\n\n", start_time=1.0, end_time=2.0)
assert word.text == "end"
def test_leading_whitespace_stripped(self):
word = Word(id="w1", text=" hello", start_time=1.0, end_time=2.0)
assert word.text == "hello"
def test_mixed_whitespace_stripped(self):
word = Word(id="w1", text="\n spell \n", start_time=1.0, end_time=2.0)
assert word.text == "spell"
def test_clean_text_unchanged(self):
word = Word(id="w1", text="hello", start_time=1.0, end_time=2.0)
assert word.text == "hello"
def test_from_dict_strips_text(self):
"""from_dict must also strip — this was the original bug."""
word = Word.from_dict({
"id": "w1",
"text": "spell\n",
"start_time": 1.0,
"end_time": 2.0,
})
assert word.text == "spell"
def test_from_dict_with_double_newline(self):
word = Word.from_dict({
"id": "w1",
"text": "broken\n\n",
"start_time": 1.0,
"end_time": 2.0,
})
assert word.text == "broken"
class TestASSOutputSanitization:
"""ASS output must never contain literal newlines in dialogue text."""
def _make_segment(self, words_data):
"""Helper to create a LyricsSegment from word tuples (text, start, end)."""
words = [
Word(id=f"w{i}", text=text, start_time=start, end_time=end)
for i, (text, start, end) in enumerate(words_data)
]
text = " ".join(w.text for w in words)
return LyricsSegment(
id="seg1", text=text, words=words,
start_time=words[0].start_time, end_time=words[-1].end_time,
)
def test_ass_text_no_literal_newlines(self):
"""Defensive strip in _create_ass_text catches newlines that bypass __post_init__.
Word.__post_init__ normally strips newlines, but this test verifies the
defensive strip at the ASS output boundary by injecting newlines directly
into Word.text after construction (bypassing __post_init__).
"""
from datetime import timedelta
# Build words normally first (clean text)
words = [
Word(id="w0", text="the", start_time=54.11, end_time=54.26),
Word(id="w1", text="spell", start_time=54.30, end_time=55.14),
Word(id="w2", text="we're", start_time=55.18, end_time=55.83),
Word(id="w3", text="under", start_time=55.93, end_time=57.24),
]
# Inject newlines directly, bypassing __post_init__
object.__setattr__(words[1], "text", "spell\n")
object.__setattr__(words[3], "text", "under\n")
segment = LyricsSegment(
id="seg1", text="the spell we're under",
words=words, start_time=54.11, end_time=57.24,
)
config = ScreenConfig(line_height=50)
line = LyricsLine(segment=segment, screen_config=config)
ass_text = line._create_ass_text(timedelta(seconds=54.0))
assert "\n" not in ass_text, f"ASS text contains literal newline: {repr(ass_text)}"
assert "the" in ass_text
assert "spell" in ass_text
assert "we're" in ass_text
assert "under" in ass_text