Compare commits

..
Author SHA1 Message Date
Andrew BeveridgeandClaude Opus 4.6 3b848f696d docs: add error monitor operational reference
Comprehensive reference doc covering: how it works, monitored resources,
infrastructure, Firestore collections, code structure, slash commands,
common operations, configuration, and troubleshooting.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 18:06:36 -04:00
Andrew BeveridgeandClaude Opus 4.6 e8e68b0261 fix(error-monitor): suppress Discord link preview embeds
Add flags=4 (SUPPRESS_EMBEDS) to webhook POST to prevent Discord from
generating link preview cards for URLs in error messages.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 18:06:25 -04:00
Andrew BeveridgeandClaude Opus 4.6 2d54d0c0b6 fix(error-monitor): Gen2 Cloud Functions log as cloud_run_revision
Gen2 Cloud Functions (gdrive-validator, backup-to-aws, etc.) appear as
cloud_run_revision in Cloud Logging, not cloud_function. Moved their
service names into MONITORED_CLOUD_RUN_SERVICES with correct hyphenated
names matching actual Cloud Run service names.

This fixes the monitor finding 0 errors when there were real errors in
karaoke-backend (Dropbox token expired, invalid state transitions) and
encoding-worker-idle-shutdown (memory limit exceeded every 5 min).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 16:49:39 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 e60ce8e479 fix: flyer dialog layout, SVG gradient export, full-size capture (#709)
## Summary

Follow-up fixes to #708 (referral flyer customisation):

- Widen dialog from `max-w-4xl` to `max-w-6xl`, constrain flyer preview
to 240px
- Replace CSS `background-clip: text` with inline SVG `<text>` +
`<linearGradient>` for export compatibility
- Swap `html2canvas` for `html-to-image` (better CSS support)
- Capture flyer at full 816x1056 size by resetting scale transform
before export

## Testing

- [x] 743/743 tests pass
- [x] PNG export verified — gradient text renders correctly at full
resolution
- [x] Preview matches export output

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 16:26:35 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 d4242c78a8 feat(e2e): daily payment + happy path production test (#715)
@coderabbitai ignore

## Summary

- **New daily E2E test** that purchases credits via **real Stripe
Checkout** ($3/day with 70% referral discount), then uses the credit for
the existing happy path karaoke generation test
- Motivated by the April 10 payment webhook outage — the existing
simulated-webhook test would never have caught the Stripe SDK v14 bug
- Adds Discord + email alerts for both stages

## Changes

- **New:** `frontend/e2e/helpers/stripe-checkout.ts` — Playwright helper
for Stripe's hosted checkout page
- **New:** `frontend/e2e/production/credit-purchase-real.spec.ts` — Real
Stripe payment test
- **New:** `.github/workflows/e2e-daily.yml` — Two-stage daily workflow:
credit purchase → happy path
- **Deleted:** `.github/workflows/e2e-happy-path.yml` — Replaced by
combined workflow
- **Docs:** Design spec + implementation plan

## Verified

- Tested locally 15 iterations to get Stripe Checkout selectors right
- Full payment flow works end-to-end: signup → referral discount →
Stripe → credits → email
- $3 real charge processed successfully each test run

## Test plan

- [x] Local test passes (real $3 Stripe payment)
- [ ] Merge and trigger e2e-daily workflow manually
- [ ] Verify Discord notification
- [ ] Monitor first automated daily run (6 AM UTC)

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 10:57:08 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 9a5c9d497a feat: production error monitor — log collection, LLM analysis, Discord alerts (#713)
## Summary

- Add a production error monitoring service that runs as a Cloud Run Job
every 15 minutes
- Queries Cloud Logging across all NK services (Cloud Run, Jobs,
Functions, GCE VMs), normalizes/deduplicates errors, uses Gemini Flash
for incident grouping, sends Discord alerts, and auto-resolves silent
patterns
- Updates all `/prod-*` slash commands to use pre-computed Firestore
patterns as primary data source

## Architecture

Based on the proven Aquarius error bot system, adapted for Nomad
Karaoke's multi-service architecture (20+ resources across 4 resource
types).

**New backend modules** (`backend/services/error_monitor/`):
- `config.py` — constants, monitored services, env var overrides
- `normalizer.py` — regex normalization + SHA-256 pattern hashing
- `known_issues.py` — 8 ignore patterns for infrastructure noise
- `firestore_adapter.py` — CRUD for `error_patterns`, `error_incidents`,
`discord_alerts`
- `discord.py` — webhook client with 5 alert formatters (new pattern,
incident, spike, auto-resolved, daily digest)
- `llm_analysis.py` — Gemini Flash incident grouping + near-duplicate
detection
- `monitor.py` — orchestrator entry point (`python -m
backend.services.error_monitor.monitor`)

**New infrastructure** (`infrastructure/modules/error_monitor.py`):
- Cloud Run Job (`nomad-error-monitor`) sharing karaoke-backend image
- Cloud Scheduler: every 15 min monitor + 08:00 UTC daily digest
- Scheduler service account with `roles/run.invoker`
- Backend SA gets `roles/logging.viewer`

**New CLI scripts:**
- `scripts/query-error-patterns.py` — query patterns from Firestore
- `scripts/resolve-error-pattern.py` — mark patterns as fixed with PR
reference

## Testing

- 310 unit tests across 7 test modules (all passing)
- Covers: config, normalizer, known issues, Firestore adapter, Discord
formatting, LLM analysis, monitor orchestrator
- P0/P1 caller-callee contract tests for monitor integration points
- All tests use mocked external dependencies (no GCP calls)

## Review

- [x] CodeRabbit CLI review completed locally (1 cycle, 3 issues fixed)
- [x] Test review completed (P0/P1 gaps addressed)
- [x] Documentation updated (README, ARCHITECTURE)
- [x] Version bumped (0.168.2 → 0.169.0)

## Design Spec

`docs/archive/2026-04-12-error-monitor-design.md`

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 01:02:08 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 b847dba411 fix: Stripe webhook crash — payments not crediting users (#712)
@coderabbitai ignore

## Summary

- **Critical production fix**: All Stripe payment webhooks have been
returning 500 since ~April 9, meaning users pay but don't receive
credits or confirmation emails
- **Root cause**: Stripe SDK v14+ `Event` objects don't support `.get()`
(unlike older versions that inherited from `dict`). The webhook handler
calls `event.get("type")` at line 1020, which raises `AttributeError:
get`
- **Fix**: Convert Stripe Event to plain dict via
`json.loads(str(event))` in `verify_webhook_signature()`, before the
event reaches the handler
- **Secondary fix**: Narrow `except Exception` to `except AlreadyExists`
in `add_credits` idempotency check — was masking permission/network
errors as "already processed"
- **Pin stripe to `^14.1.0`** (was `>=7.0.0`) to prevent unexpected
major upgrades in Docker builds

## Impact

- **3 payments ($59.50 total) for 2 users** affected since April 9
- Stripe retries failed webhooks for 3 days — all affected payments are
within the retry window and will be processed automatically after deploy
- No manual intervention needed for credits or emails

## Test plan

- [x] All 59 existing payment/credit tests pass
- [x] Verified fix with Stripe v14 Event objects (unicode, empty
metadata, refund events)
- [ ] After deploy: monitor logs for successful webhook processing
- [ ] Verify affected users receive credits via Stripe webhook retries

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 11:18:09 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 f0e9a06c44 fix: brighter lime-green highlight for user-edited words (#711)
## Summary
- Changes user-edited word highlight from subtle violet
(`bg-violet-500/25`) to bright lime green (`bg-lime-400/40`)
- Much more visible and obvious which words have been edited
- Distinct from AI-corrected words which use `bg-green-500/25`

## Test plan
- [x] All 743 tests pass
- [ ] Edit a word in lyrics review → bright green background appears

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 00:16:32 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 ce24df53d9 feat: highlight user-edited words in lyrics review (#710)
## Summary
- Words edited by the user in lyrics review now show a **violet
background** (`bg-violet-500/25`) so it's immediately obvious which
words have been modified
- Compares current word text against initial state (`history[0]`), so
undo/redo correctly updates highlights
- New words added by the user are also highlighted

## Changes
- `Word.tsx` — accepts `isUserEdited` prop, renders violet highlight
- `LyricsAnalyzer.tsx` — computes `editedWordIds` via `useMemo`
comparing current vs initial data
- `TranscriptionView.tsx` / `HighlightedText.tsx` — thread
`editedWordIds` set through to Word component
- `constants.ts` / `types.ts` — add `userEdited` highlight class and
`isUserEdited` prop

## Color priority (highest → lowest)
1. Currently playing (blue solid)
2. Anchor (blue tint)
3. **User-edited (violet tint)** ← new
4. Corrected gap (green tint)
5. Uncorrected gap (orange tint)

## Test plan
- [x] All 743 existing tests pass
- [x] Frontend build succeeds
- [ ] Manually verify: edit a word in lyrics review → violet background
appears
- [ ] Manually verify: undo the edit → violet background disappears
- [ ] Manually verify: add a new word → violet background appears on new
word

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 23:49:16 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 3fac565c76 feat: referral flyer customisation with tabbed QR/flyer dialog (#708)
## Summary

- Expand the QR Code Generator dialog into a tabbed **Referral Tools**
dialog with **QR Code** and **Printable Flyer** tabs
- Add a live flyer preview with extensive customisation: colors, text
overrides, section visibility, custom branding, and print layout (1/2/4
per page)
- Client-side export to PDF, HTML, and PNG (replaces server-side flyer
generation)
- Preset themes (Light/Dark) with save/load custom presets via
localStorage

## Changes

- **New components:** `ReferralToolsDialog`, `QRCodeTab`, `FlyerTab`,
`FlyerPreview`, `FlyerControls`, `FlyerExport`, `flyer-presets`
- **Removed:** `QRCodeDialog` (replaced by `ReferralToolsDialog`)
- **Modified:** `ReferralDashboard.tsx`, `admin/referrals/page.tsx`
(import updates)
- **Dependencies:** Added `html2canvas`, `jspdf` for client-side export
- **i18n:** 30+ new translation keys across all 33 locales

## Testing

- [x] 32 referral-specific tests pass (presets, export, dialog
interaction)
- [x] 743/743 total frontend tests pass
- [x] TypeScript compilation clean (no new errors)
- [x] CodeRabbit CLI review completed locally, feedback addressed

## Review

- [x] Local CodeRabbit review completed (10 findings, 6 fixed, 4 skipped
as nitpicks)
- [x] Review feedback addressed in dedicated commit

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 19:02:12 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 43900921a5 fix: validate auth token on referral interstitial (#707)
## Summary
- Users with stale/expired tokens in localStorage were shown "Go to App"
instead of the magic link email form on referral interstitial pages
(`/r/<code>`)
- Now validates the token against `/api/users/me` before deciding which
UI to show
- Clears stale tokens so future visits work correctly

## Root cause
The interstitial checked `getAccessToken()` (localStorage only) which
returns non-null even for expired tokens. A user who had previously
visited the app would always see "Go to App" even if their session was
long expired.

## Test plan
- [x] Frontend build passes
- [x] All 722 tests pass
- [ ] Manual: visit `/r/<code>` with a stale token in localStorage →
should see email form
- [ ] Manual: visit `/r/<code>` while genuinely logged in → should see
"Go to App"

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 11:18:23 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 6068ef7a93 fix: only clear auth token on explicit 401, not network errors (#706)
## Summary

- `fetchUser()` was clearing the access token on ANY error (network
failures, timeouts, aborted requests during page redirects)
- This caused users to get logged out when returning from external flows
like Stripe Connect onboarding — the redirect chain triggers transient
fetch errors that wiped the token
- Now only clears the token when the server explicitly returns 401
(session expired/invalid)

This is the root cause of the "logged out after Stripe Connect" issue
reported alongside #702.

## Test plan

- [ ] Manual: complete Stripe Connect flow, verify user stays logged in
on return
- [x] Existing auth tests still pass (no behavior change for actual
401s)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 19:38:48 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 83fdc9e786 fix: hide Manage Payouts when Stripe onboarding incomplete (#705)
## Summary

- Hide "Manage Payouts" button when Connect account hasn't completed
onboarding (`details_submitted` is false)
- Stripe API rejects login link creation for incomplete accounts
(returns 400)
- "Update Bank Account" button remains available to complete setup

Follow-up to #702.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 19:15:54 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 77f64a52d7 feat: mobile-friendly two-row header (#704)
## Summary
- Adds a second row to the app header on mobile (< 640px) so action
buttons show text labels instead of cryptic icons
- Row 1: logo + title + auth/login status
- Row 2: refresh, referrals, help, language switcher, theme toggle — all
with visible text labels
- Desktop layout (≥ 640px) is completely unchanged
- Extracted HelpDropdown and ThemeToggle into small sub-components to
avoid JSX duplication

## Test plan
- [x] All 721 existing tests pass
- [ ] Visual check on mobile viewport (375px, 390px) — two rows visible
with text labels
- [ ] Visual check on desktop — single row, unchanged from before
- [ ] Check dashboard page (with Refresh/Admin children) and referrals
page (no children)
- [ ] Check logged-in vs logged-out states
- [ ] Verify language switcher dropdown positions correctly from row 2

@coderabbitai ignore

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

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 19:05:13 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 1c1c17f9ab fix: Stripe Connect redirect and referral payout management (#702)
## Summary

- **Fix broken Stripe Connect return URL** — was redirecting to
`/app?tab=referrals` (the dashboard, which ignores that param) instead
of `/app/referrals`. Users were ending up logged out at `/en/` after
completing Stripe onboarding.
- **Add locale redirect fallback** for `/app/referrals` route so Stripe
can redirect without locale prefix
- **Add Connect account status and management** — new backend endpoints
for account status, Express dashboard login, and re-onboarding. Frontend
shows payouts enabled/pending status, "Manage Payouts" and "Update Bank
Account" buttons.
- **Improve Connect button UX** — loading spinner + note that user will
be redirected to Stripe, error feedback for all actions

## Test plan

- [x] Backend: 48 referral tests + 7 Stripe tests pass
- [x] Frontend: 721 tests pass
- [x] CodeRabbit review: 3 issues found and fixed
- [ ] Manual: verify Connect flow with test account after deploy
- [ ] Manual: verify return redirect lands on referrals page with
success banner

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 18:29:29 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 9283d3c1ae feat: referral discount details UX + translation pipeline fix (#701)
@coderabbitai ignore

## Summary

- **Clickable "discount active" in dropdown**: Users who dismissed the
referral discount banner can click "discount active" in the user
dropdown to re-show it (clears localStorage dismissal, navigates to
dashboard)
- **Richer Buy Credits dialog**: Fetches and displays referrer's display
name and referral code alongside existing discount % and expiration info
- **Backend**: `no_track` query param on `GET /api/referrals/r/{code}`
to skip click tracking for display-only fetches
- **Translation pipeline fix**: `translate.py` dry-run no longer saves
snapshot (was causing subsequent runs to skip all translations), and
added missing-keys mode that compares against existing locale files
instead of re-translating everything when no snapshot exists

## Test plan

- [x] Backend unit test for `no_track=true` param
- [x] Frontend AuthStatus test updated with `next/navigation` mock
- [x] All 721 frontend tests passing
- [x] All backend tests passing
- [ ] Manual: dismiss discount banner → click "discount active" in
dropdown → verify banner re-appears on dashboard
- [ ] Manual: open Buy Credits dialog → verify referrer name and code
shown
- [ ] Manual: run `translate.py --dry-run` → verify snapshot not saved

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 18:19:03 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 3a1fd08c96 fix: apply discount dropdown, credit pricing, checkout state (#700)
## Summary
- **Apply Discount modal**: referral code dropdown was empty —
`loadReferralLinks()` was in `onOpenChange` which doesn't fire for
controlled Dialog open prop changes. Moved to button onClick. Also
replaced `Select` with searchable `Combobox` (Popover+Command) to scale
with many referral codes.
- **Buy Credits dialog**: discounted prices showed contradictory values
(e.g. "$9" and "$8.50/video") because `formatPrice` used `toFixed(0)`
rounding. Now shows cents when price isn't a whole dollar.
- **Buy Credits dialog**: "Redirecting to payment..." persisted after
closing/reopening because `checkoutLoading` wasn't reset on dialog open.

## Test plan
- [x] Build passes
- [x] 721 tests pass
- [x] CodeRabbit: no findings
- [ ] Manually verify Apply Discount modal loads and filters referral
codes
- [ ] Manually verify Buy Credits shows correct discounted prices (e.g.
$8.50 not $9)
- [ ] Manually verify closing/reopening Buy Credits resets checkout
button state

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 14:09:47 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 8ef587e7e3 feat(referral): fix discount checkout bug, show discounted prices, admin UX (#699)
## Summary
- **Fix**: Referral discount silently dropped at Stripe checkout due to
timezone-aware vs naive datetime comparison (same bug previously fixed
in `_build_user_public` but missed in `should_apply_discount`)
- **Admin UX**: Replace free-text referral code input in Apply Discount
dialog with dropdown of active codes (prevents typos/nonexistent codes)
- **Buy Credits modal**: Show discounted prices with strikethrough
originals when user has active referral discount
- **Dashboard banner**: Make referral discount banner dismissable (X
button, localStorage)
- **User menu**: Show "X% discount active" in the dropdown so discount
info persists after banner dismissal

## Test plan
- [ ] Verify referred user sees discounted prices in Buy Credits modal
- [ ] Verify Stripe checkout session includes the coupon (discount
actually applied)
- [ ] Verify discount banner can be dismissed and stays dismissed on
reload
- [ ] Verify user menu shows discount status
- [ ] Verify admin Apply Discount dialog shows dropdown of active
referral codes

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 16:53:06 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 3a9438f3e4 fix(referrals): use nomadkaraoke.com/r/ for QR codes and referral URLs (#698)
## Summary
QR codes and referral link displays were using
`gen.nomadkaraoke.com/r/{code}` which 404s. The `/r/` short URLs live on
`nomadkaraoke.com` (which redirects to gen). Fixes all referral URL
generation in both user dashboard and admin QR dialog.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 11:56:38 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 404caa624a feat(admin): full QR/flyer dialog on admin referrals page (#697)
## Summary
Replace the simple flyer download button on the admin referrals page
with the full QRCodeDialog modal — same one users see on their referrals
page. Supports customizable QR styles, colors, center logos, and
light/dark flyer themes.

- Add `onGenerateFlyer` and `flyerFilename` props to `QRCodeDialog` so
admin can use the admin flyer endpoint
- Wrap dialog in `NextIntlClientProvider` since admin pages don't have
the i18n provider

## Test plan
- [x] Build passes
- [ ] Click QR icon on any referral row → full dialog opens
- [ ] Customize QR, generate flyer → downloads PDF for that code

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 11:42:54 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 0dbd1d3ab0 fix(referrals): vanity URL request via backend API instead of mailto (#696)
## Summary
The `mailto:` approach for vanity URL requests silently fails when users
don't have a mail client configured — no email is ever sent.

- Adds `POST /api/referrals/me/vanity-request` endpoint that sends an
email to admin via SendGrid
- Validates the desired code isn't already taken (returns 409 with
friendly error)
- Frontend shows inline error messages and loading state
- Removes the broken `mailto:` approach

## Test plan
- [x] Build passes
- [x] All 721 tests pass
- [ ] Request a vanity URL → admin receives email
- [ ] Request a taken code → shows "already taken" error

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 11:12:56 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 9e96f7e089 fix: logo invisible — next/image SVG collapses to 0x0 (#695)
## Summary
The logo was rendering at 0x0 pixels. Root cause: `next/image` with
`w-auto h-auto` on an SVG has no intrinsic sizing, so it collapses.

Replaces `TenantLogo` with a plain `<img>` using explicit height classes
(`h-8 sm:h-10`) matching the header. Removes the `next/image` import
entirely since it causes more problems than it solves for logo SVGs.

## Test plan
- [x] Build passes
- [ ] Logo visible on dashboard (`/en/app/`)
- [ ] Logo visible on referrals page (`/en/app/referrals/`)
- [ ] Tenant logos still work (custom branding)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 01:54:19 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 31b02abd8c fix: replace broken external logo URL with local SVG (#694)
## Summary
The old WordPress PNG logo URL (`nomadkaraoke.com/wp-content/...`) is
returning 404. Both `logo.tsx` and `tenant-logo.tsx` still referenced it
as the default.

Switches to `/nomad-karaoke-logo.svg` which is already in `public/` and
used by `AppHeader`.

## Test plan
- [x] Build passes
- [ ] Logo loads on all pages (dashboard, referrals, tenant landing)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 01:42:13 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 04c7197445 feat(i18n): add translation cache, CI validation, and enforcement (#693)
## Summary
@coderabbitai ignore

- Add GCS translation cache (`translation_cache.py`) to `translate.py`
for instant repeated translations
- Add `--no-cache`, `--dry-run`, `--cache-bucket` CLI flags to
translation script
- Add `translation-check` CI job that validates all 33 locale files have
matching keys
- Add `.githooks/pre-commit` hook for auto-translation when `en.json`
changes
- Add i18n section to CLAUDE.md documenting 33-locale support and
enforcement rules

## Test plan
- [ ] `python frontend/scripts/translate.py --messages-dir
frontend/messages --target es --dry-run` shows cache stats
- [ ] `python frontend/scripts/validate-translations.py --messages-dir
frontend/messages` passes
- [ ] CI `translation-check` job runs on PR

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 01:22:39 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 19c85ca5b2 fix(referrals): DRY shared AppHeader matching dashboard style (#692)
## Summary
Follow-up to #691. Fixes issues found in production:

- Rewrites `AppHeader` to match the dashboard header style (local SVG
logo, fixed position, dark theme, consistent controls)
- Dashboard now uses the shared `AppHeader` with page-specific buttons
(refresh, admin toggle) passed as children
- Removes broken `Logo` component (external PNG URL) and dead `/jobs`
link that 404'd
- Adds proper top padding on referrals page for the fixed header

## Test plan
- [x] Build passes (`next build`)
- [x] All 721 tests pass (`make test`)
- [ ] Visual check: dashboard header unchanged after refactor
- [ ] Visual check: referrals page header now matches dashboard
- [ ] Logo loads correctly (local SVG)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 01:13:43 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 60c893391e feat(referrals): improve UX with header, explainer, vanity URL request, and i18n (#691)
## Summary
- Add AppHeader + "Back to Dashboard" nav to referrals page (matches the
rest of the app)
- Add friendly "How It Works" section explaining the 3-step referral
process with dynamic terms
- Add vanity URL request flow (opens pre-filled mailto to admin)
- Translate entire referrals section to all 32 non-English locales via
Gemini pipeline

## Test plan
- [x] Build passes (`next build`)
- [x] All 721 tests pass (`make test`)
- [x] Translation validation — no missing keys across 32 locales
- [ ] Visual check: referrals page has consistent header
- [ ] Visual check: "How It Works" section shows correct terms
- [ ] Visual check: vanity URL request form works (opens email)
- [ ] Visual check: non-English locale loads referrals translations

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 00:46:28 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 7c2d50b199 fix(referral): QR dialog — imageOptions error, emoji logo, button label (#690)
@coderabbitai ignore

## Summary
Fixes 3 issues with the QR code dialog shipped in #688:

1. **Bug fix**: `TypeError: can't access property "hideBackgroundDots",
e.imageOptions is undefined` — Always provide `imageOptions` to
`qr-code-styling` even when no logo selected
2. **Fix broken logos**: Replace Lucide icon center logos (Mic/Music)
with an emoji picker. The `iconNode` internal API doesn't work in
production builds. Users can now type any emoji as their QR center logo.
3. **Better button**: Change dashboard button from icon-only QR icon to
labeled "QR Code / Flyer"

Also includes CodeRabbit feedback: debounce cleanup on unmount,
FileReader error handler, user-facing error message for flyer failures.

## Test plan
- [x] 721/721 frontend tests passing
- [x] Updated center logo test assertions
- [ ] Manual: open QR dialog, verify no console error, try emoji logo,
download QR

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 23:30:27 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 e441b854c6 feat(referral): marketing flyer PDF generator (#688)
@coderabbitai ignore

## Summary
- **Marketing Flyer Generator**: Print-ready PDF flyers (light + dark
themes) with personalized referral code, discount, and styled QR code
- Server-side rendering via headless Chromium (added to Dockerfile)
- Available from QR Code dialog (user) and admin referrals table (admin)

## Changes

### Backend
- **New:** `flyer_service.py` — Template rendering + headless Chromium
PDF generation
- **New:** `POST /api/referrals/me/flyer` — User flyer endpoint
- **New:** `POST /api/referrals/admin/links/{code}/flyer` — Admin flyer
endpoint
- **New:** Light + dark HTML flyer templates (from kjbox printables)
- **Modified:** `Dockerfile.base` — Added `chromium` package

### Frontend
- **Modified:** `QRCodeDialog.tsx` — Theme picker + Generate Flyer
button, error handling
- **Modified:** Admin referrals page — Flyer button per row
- **New:** `generateFlyer()` API client function (user + admin)
- **i18n:** 5 new flyer-related strings

### Infrastructure
- **Dockerfile.base change** — Adds Chromium (~200MB). Base image
rebuild required.

## Test plan
- [x] 8 backend unit tests (template substitution, validation, Chromium
flags)
- [x] 11 frontend tests (QR dialog + flyer controls)
- [x] 721 total frontend tests passing
- [x] Local Chrome PDF verification (user confirmed)
- [x] Docker container PDF verification (Chromium 146, fonts + gradients
correct)
- [x] End-to-end test with real styled QR code (user confirmed
scannable)
- [ ] Manual: QR dialog → pick theme → Generate Flyer → verify PDF
- [ ] Manual: Admin referrals → flyer button → verify PDF

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 22:36:03 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 ab174f4d07 docs: add referral system lessons learned (#686)
5 gotchas from the referral system implementation added to
LESSONS-LEARNED.md.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 01:24:33 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 d471dbb47e fix: f-string syntax error blocking backend deploys (#685)
## Summary
- Fixes `SyntaxError: f-string expression part cannot include a
backslash` in `email_service.py:309`
- This has been blocking all backend Cloud Run deploys since PR #680
- Extracts inline HTML with escaped quotes to a variable before the
f-string

## Root Cause
PR #680 added a referral banner with `\"` escaped quotes inside an
f-string expression. Python 3.11 (Cloud Run runtime) doesn't allow
backslashes in f-string expressions — this is only allowed in Python
3.12+. Local tests pass because they don't exercise the import at module
level the same way uvicorn does.

## Testing
- [x] Verified `from backend.services.email_service import
get_email_service` succeeds
- [x] No logic changes — just moves HTML to a variable

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 20:03:02 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 7bf000eb81 feat(referral): add duration fields to admin and user referral UIs (#684)
## Summary

- Admin edit/create dialogs: now include discount duration and earning
duration fields
- Admin table: shows durations below rates (e.g. "10% / 20%" with "30d /
365d" below)
- User dashboard: new "Link Terms" section showing discount %, discount
window, kickback %, earning window

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 19:55:23 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 30bf8178aa feat(pricing): increase default price per track from $5 to $10 (#683)
## Summary
- Doubles base credit price from $5 to $10 per track
- Scales volume discount tiers proportionally (20%/30%/40% discounts
preserved)
- Updates all 33 i18n locale files, frontend savings calculation, and
E2E test fixtures

## Changes
- **Backend:** `CREDIT_PACKAGES` in `stripe_service.py` — 1cr: $10, 3cr:
$24, 5cr: $35, 10cr: $60
- **Frontend:** Savings calc base in `BuyCreditsDialog.tsx` (500 → 1000)
- **i18n:** `createYourselfPrice` "$5" → "$10" in all 33 locale files
- **Tests:** Updated price fixtures in `landing-page.spec.ts` and
`mobile.spec.ts`

## Testing
- [x] All 710 tests pass (`make test`)
- [x] No new logic — config value change only

## Review
- [x] CodeRabbit CLI review completed locally (no issues with pricing
changes)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 19:30:55 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 54c83e924c feat(referral): QR code generator with customizable styles (#682)
@coderabbitai ignore

## Summary
- Adds a QR code generator dialog to the referral dashboard
(`/app/referrals`)
- Referrers can customize dot style (6 options), corner frame (3),
corner dot (2), foreground/background colors, and center logo (NK logo,
microphone, music note)
- Live preview updates as options change
- Download as PNG or SVG
- Style preferences persist in localStorage

## Changes
- **New:** `frontend/components/referrals/QRCodeDialog.tsx` — QR
generator dialog using `qr-code-styling` library
- **Modified:** `frontend/components/referrals/ReferralDashboard.tsx` —
added QR Code button next to Copy Link
- **New:**
`frontend/components/referrals/__tests__/QRCodeDialog.test.tsx` — 10
unit tests
- **Modified:** `frontend/messages/en.json` — 22 new i18n strings
- **New dep:** `qr-code-styling` (client-side QR generation with style
customization)

## Test plan
- [x] 10 unit tests covering: rendering, style options, localStorage
persistence, download calls
- [x] 720/720 total tests passing
- [x] Next.js build compiles cleanly
- [x] ~70% coverage on new component (uncovered lines are
jsdom-incompatible DOM SVG APIs)
- [ ] Manual: open referral dashboard, click QR button, customize
styles, download PNG/SVG

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 19:17:43 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 817f2aa1bd feat(admin): add Apply Discount to user detail page (#681)
## Summary

Admins can apply a referral discount to any user from the user detail
page — useful for grandfathering existing users when raising prices.

## Changes

### Backend
- New endpoint: `POST /api/referrals/admin/apply-discount` — sets
discount %, duration, and referral code on any user
- `UserDetailResponse` now includes `referred_by_code`,
`referral_discount_expires_at`, `referral_code`

### Frontend
- "Apply Discount" button on user detail page (next to Add Credits)
- Dialog with discount %, duration (days), and referral code inputs
- Current discount status shown on user detail page if active

## Usage
- Go to Admin → Users → click a user → "Apply Discount"
- Set 50% off for 3650 days with code "loyalty" to grandfather a user

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 19:03:06 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 607c52bed3 feat(referral): embed referral code in magic link for cross-device attribution (#680)
## Summary

Referral attribution was failing because it relied solely on a browser
cookie. If the user opened the magic link email on a different device or
browser, the cookie wasn't there and attribution was lost.

## Fix: Triple-redundant referral code delivery

The referral code now travels through three independent paths:

1. **Cookie** (`x-referral-code` header) — same device, same browser
2. **Firestore** (magic link token doc) — stored server-side when magic
link is sent
3. **URL param** (`&ref=CODE` on the magic link) — travels with the
email itself

On verification, the backend checks all three and uses the first one
found.

## Changes

### Backend
- `SendMagicLinkRequest` + `MagicLinkToken` models: added
`referral_code` field
- `user_service.create_magic_link()`: accepts and stores referral_code
- `email_service.send_magic_link()`: appends `&ref=CODE` to URL, adds
discount banner to email
- `verify_magic_link`: reads referral code from header OR token doc OR
URL param

### Frontend
- `api.sendMagicLink()`: passes referral_code in request body
- Auth store `sendMagicLink`: reads referral cookie and passes it
- Verify page: reads `?ref=CODE` from magic link URL and stores cookie
before verification

## Testing
- 2952 backend tests pass
- Frontend build passes

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 17:22:53 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 3f00b08fb7 fix(referral): show display name on interstitial page (#679)
## Summary

The interstitial page wasn't showing the affiliate's display name
because of a field name mismatch — frontend type had `display_name` but
the API returns `referrer_display_name`.

## Changes

- `frontend/lib/types.ts` — `ReferralInterstitial.display_name` →
`referrer_display_name`, `code` → `referral_code`
- `frontend/app/[locale]/r/client.tsx` — Updated references to use
`data.referrer_display_name`

@coderabbitai ignore

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 16:44:45 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 af50b53cd8 feat(admin): add edit dialog for referral links (#678)
## Summary

Adds a pencil icon button on each row in the admin referrals table that
opens an edit dialog to modify display name, custom message, discount %,
and kickback %.

## Changes

- `frontend/app/admin/referrals/page.tsx` — Edit button + dialog with
form fields, uses existing `adminApi.updateReferralLink` endpoint

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 16:29:49 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 1cd747f170 fix(referral): compute and display referral discount status for users (#677)
## Summary

Three referral UX fixes:

1. **Discount visibility** — Backend now computes
`has_active_referral_discount` and returns discount details (percent,
expiry, referral code) in all UserPublic responses. Dashboard shows a
purple banner with discount info. Buy Credits dialog shows actual
percent + expiry.

2. **Existing user attribution** — Removed the `is_first_login` gate.
Any user who logs in with a referral code cookie and hasn't been
referred yet gets the referral attributed. This means existing users who
click a referral link will get the discount.

3. **Interstitial email signup** — Replaced the "Get Started" redirect
with an inline email input form. Users enter their email directly on the
interstitial page to receive a magic link. Shows "Check your email"
confirmation after sending. Already-logged-in users see a "Go to App"
CTA instead.

## Changes

### Backend
- `backend/api/routes/users.py` — New `_build_user_public()` helper
computes discount status. Attribution gate changed from `is_first_login`
to `not user.referred_by_code`.
- `backend/models/user.py` — Added `referral_discount_percent`,
`referral_discount_expires_at`, `referred_by_code` to UserPublic

### Frontend
- `frontend/app/[locale]/r/client.tsx` — Full rewrite: email signup form
with magic link, three states (form/sent/logged-in)
- `frontend/app/[locale]/app/page.tsx` — Referral discount banner on
dashboard
- `frontend/components/credits/BuyCreditsDialog.tsx` — Actual discount
percent + expiry date
- `frontend/lib/auth.ts` — Pass through referral fields
- `frontend/lib/types.ts` — New referral type fields

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 16:22:58 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 686402d643 fix(i18n): admin link 404 when accessed from locale-prefixed pages (#676)
## Summary
- `AuthStatus.tsx` imported `Link` from `@/i18n/routing` which
auto-prefixes hrefs with the current locale (e.g. `/en/admin`)
- Since `/admin` lives outside the `[locale]` route group, `/en/admin`
has no matching static page → 404
- Changed to `NextLink` from `next/link` which preserves the href as-is,
correctly navigating to `/admin`

## Test plan
- [x] `make test` passes (710 tests)
- [x] `next build` succeeds
- [ ] Verify clicking "Admin Dashboard" from `/en/app` navigates to
`/admin` (not `/en/admin`)

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 15:53:34 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 bb86722008 fix(referral): dedicated interstitial page instead of banner overlay (#675)
## Summary

Replace the banner overlay (which looked terrible floating over the
landing page) with a proper full-screen interstitial page.

## Flow

1. `nomadkaraoke.com/r/bevvy` → Worker redirects to
`gen.nomadkaraoke.com/en/r?code=bevvy`
2. Static `/en/r` page loads, reads `?code=` param, fetches referral
data from API
3. Full-screen interstitial: gift icon, referrer name, custom message,
discount details, "Get Started" CTA
4. User clicks "Get Started" → landing page (referral code already
stored in cookie)

## Changes

- New: `frontend/app/[locale]/r/page.tsx` + `client.tsx` — dedicated
interstitial page
- Reverted: `frontend/components/ReferralCapture.tsx` — back to silent
cookie-setter (no banner)
- Cleaned: `frontend/public/_redirects` — removed broken `:splat` rules

Also pushed: `public-website/worker.js` updated to redirect to
`/en/r?code=` instead of `/en/?ref=`

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 22:44:22 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 74eac6f5ee feat(referral): show interstitial banner on landing page for referral links (#674)
## Summary

When a user arrives via a referral link (`nomadkaraoke.com/r/CODE` →
`gen.nomadkaraoke.com/en/?ref=CODE`), the landing page now shows a
dismissible banner with the referrer's name, custom message, and
discount details.

## Changes

- `frontend/components/ReferralCapture.tsx` — Enhanced from silent
cookie-setter to interstitial banner. Fetches referral data from API,
shows referrer name/message/discount in a fixed top banner with slide-in
animation. Dismissible via X button.

## How it works

1. User clicks `nomadkaraoke.com/r/bevvy`
2. Cloudflare Worker redirects to `gen.nomadkaraoke.com/en/?ref=bevvy`
3. `ReferralCapture` component detects `?ref=bevvy`, stores cookie,
fetches interstitial data
4. Banner slides in showing "You've been referred! Referred by [name].
[message]. Enjoy 10% off..."
5. User dismisses or scrolls to sign up — referral code is already
stored for checkout

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 21:42:21 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 d142156138 fix: use correct :splat syntax for referral redirect (#673)
## Summary

The referral redirect `/r/:code → /en/?ref=:code` was passing the
literal string `:code` instead of the actual referral code. Cloudflare
Pages uses `*` + `:splat` syntax, not named parameters.

## Fix

`/r/:code /en/?ref=:code 302` → `/r/* /en/?ref=:splat 302`

@coderabbitai ignore

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 19:03:20 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 0353f5890d fix: use redirect for /r/CODE referral links instead of dynamic route (#672)
## Summary

The previous approach (catch-all `[[...code]]` route) doesn't work with
Next.js static export on Cloudflare Pages — dynamic paths 404 because no
HTML file exists for them.

## Fix

Replace the dynamic route with a simple Cloudflare Pages `_redirects`
rule:
- `/r/CODE` → `/en/?ref=CODE` (302 redirect)
- The `ReferralCapture` component on the landing page already captures
`?ref=CODE` and stores it in a cookie

This means referral links redirect to the landing page with the code as
a query param, which is simpler and fully compatible with static export.

## Tradeoff

The custom interstitial page (with referrer name/message) is removed for
now. The referral still works — the code gets stored and applied at
checkout. The interstitial can be added back later as a component on the
landing page that detects `?ref=` and shows the referral info.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 18:57:51 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 c97a340389 fix: add Cloudflare Pages rewrites for referral /r/CODE routes (#671)
## Summary

Referral interstitial pages at `/r/CODE` return 404 because Cloudflare
Pages doesn't know to serve the catch-all page for dynamic paths.

## Changes

Add `_redirects` rules:
- `/r/*` → `/en/r/:splat` (302) — bare paths get locale prefix
- `/{locale}/r/*` → `/{locale}/r/index.html` (200 rewrite) — all 33
locales get SPA-style fallback

## Testing
- Fixes `gen.nomadkaraoke.com/r/bevvy` (currently 404)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 18:42:24 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 1154adc150 feat(admin): add referral links management page (#670)
## Summary

- Add Referrals page to admin dashboard for managing referral links
- Stats overview: total links, clicks, signups, earnings
- Links table with enable/disable toggle and copy-to-clipboard
- Create Vanity Link dialog with custom discount/kickback rates

## Changes

- `frontend/app/admin/referrals/page.tsx` — New admin referrals page
- `frontend/components/admin/admin-sidebar.tsx` — Added Referrals nav
item
- `frontend/app/admin/layout.tsx` — Added breadcrumb support
- `frontend/lib/api.ts` — Added 3 admin referral API methods

## Testing
- [x] Frontend build passes
- [x] 710 frontend unit tests pass
- [x] No backend changes

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 18:26:32 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 80cb53f3a2 feat: referral link system with discounts and Stripe Connect payouts (#669)
## Summary

- Add a referral system where any user gets a shareable link (`/r/CODE`)
with a personalized interstitial page
- Referred users get a configurable discount (default 10%) on credit
purchases for 30 days
- Referrers earn a cash kickback (default 20% of revenue) paid out via
Stripe Connect at $20 threshold
- Admin can create vanity links with custom rates and manage all
referral links

## Changes

### Backend
- **New models** (`backend/models/referral.py`): ReferralLink,
ReferralEarning, ReferralPayout + API request/response models
- **New service** (`backend/services/referral_service.py`): Link CRUD,
attribution, discount detection, earnings recording, Stripe Connect
onboarding, auto-payout
- **New routes** (`backend/api/routes/referrals.py`): 7 endpoints —
public interstitial, user dashboard, link updates, Connect onboarding,
admin vanity/list/update
- **Stripe integration**: Coupon creation/lookup, Connect Express
accounts, transfers
- **Webhook hook**: Referral earnings recorded on credit purchases
- **Auth hook**: Referral attribution on first magic link verification
via `x-referral-code` header
- **User model**: Added referral fields (referral_code,
referred_by_code, referred_at, discount_expires_at,
stripe_connect_account_id)

### Frontend
- **Interstitial page** (`/r/CODE`): Shows referrer's name, custom
message, discount details
- **Referral dashboard** (`/app/referrals`): Link sharing, stats,
earnings, payout history, Stripe Connect CTA
- **Discount badge**: Shown in Buy Credits dialog during active referral
window
- **Referral capture**: Cookie + localStorage via `/r/CODE` route and
`?ref=CODE` query param
- **Auth integration**: Passes referral code on magic link verification,
clears after use
- **i18n**: 33 new translation keys in `referrals` namespace

### Documentation
- Design spec: `docs/archive/2026-04-04-referral-system-design.md`
- Implementation plan: `docs/archive/2026-04-04-referral-system-plan.md`
- Updated `docs/README.md` status table and `docs/API.md` with referral
endpoints

## Testing
- 68 referral-specific tests (models, service, routes) — all passing
- 2935 total backend tests — zero regressions
- 710 frontend tests — all passing
- Covers: link management, attribution, self-referral blocking, discount
detection, earnings calculation, payout threshold, edge cases (rounding,
zero amounts), all API endpoints

## Review
- [x] CodeRabbit CLI review completed locally (11 findings, 7 fixed)
- [x] Test review completed (P0/P1 gaps identified and filled)
- [x] Docs reviewed and updated

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 17:39:18 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 fb4bcc7737 fix(i18n): locale-prefix review links and protect auth from redirect aborts (#668)
## Summary
- Hash-based review/instrumental/audio-edit links in JobCard were
missing the locale prefix (`/en/`), causing a double-redirect through
`LocaleRedirect` that aborted the module-level `fetchUser()` call and
wiped the user's auth session
- Added `useLocale()` to JobCard so links include the locale prefix,
avoiding the redirect entirely
- Made `fetchUser()` resilient to `AbortError` so navigation-triggered
fetch aborts don't clear auth

## Test plan
- [x] Unit tests: 710 passing (3 new auth abort resilience tests)
- [x] JobCard test expectations updated for locale-prefixed URLs
- [x] CodeRabbit review: no findings
- [ ] Manual: verify clicking "Review Lyrics" on dashboard navigates
directly to review page without logout

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 14:30:27 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 48265d398f fix: edit with metadata change now properly regenerates screens (#667)
## Summary
- Fix invalid state transition when editing a completed track with
artist/title changes
- The edit flow now transitions to `LYRICS_COMPLETE` (instead of
`AWAITING_REVIEW`) when metadata changes, allowing the screens worker to
properly regenerate screens via the valid `LYRICS_COMPLETE →
GENERATING_SCREENS` path
- Clear stale `file_urls.screens` entries to prevent retry logic from
skipping screen generation

## Root cause
When a user edits a completed track and changes artist/title:
1. Edit flow correctly deleted screen files from GCS (they had old text
baked in)
2. Edit flow transitioned to `AWAITING_REVIEW` and triggered screens
worker
3. Screens worker tried `AWAITING_REVIEW → GENERATING_SCREENS` —
**invalid transition**
4. Screens never regenerated, but `file_urls.screens` had stale
references
5. Retry saw stale URLs, skipped screen generation → 404 on `title.png`

## Test plan
- [x] All 16 edit track tests pass (including 2 new regression tests)
- [x] Full test suite passes (707 frontend + backend tests)
- [x] Manually verified fix on job `4117228f` — screens regenerated and
job completed successfully

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 18:04:01 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 ab330a3ed6 feat(i18n): scale to 33 languages with RTL support (#666)
## Summary
- Scale i18n from 3 languages (en/es/de) to 33 languages
- Upgrade translation pipeline: async parallel execution (5 concurrent)
+ incremental delta detection
- Add RTL support (`dir="rtl"`) for Arabic and Hebrew
- Replace LanguageSwitcher `<select>` with grouped scrollable dropdown
(flags + native names)
- RTL CSS audit: convert directional properties to logical equivalents
- 30 new frontend translation files (1062 keys each) + 30 backend files
(274 keys each)

### New languages
Portuguese, French, Japanese, Korean, Chinese, Italian, Dutch, Polish,
Turkish, Russian, Thai, Indonesian, Vietnamese, Filipino, Hindi, Arabic,
Swedish, Norwegian, Danish, Finnish, Czech, Romanian, Hungarian, Greek,
Hebrew, Malay, Ukrainian, Croatian, Slovak, Catalan

## Test plan
- [x] `next build` — 285 static pages generated (11 pages x 33 locales -
some deduped)
- [x] All translation files have 100% key parity
- [ ] Post-deploy: verify Japanese, Arabic (RTL), Portuguese render
correctly
- [ ] Post-deploy: verify LanguageSwitcher shows all 33 options

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 05:08:47 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 84c879a352 fix(i18n): pass locale to cross-app links (#665)
## Summary
- Landing page footer link to nomadkaraoke.com now includes locale
prefix
- Order success "Back to Nomad Karaoke" link now includes locale prefix
- Ensures users stay in their chosen language when navigating between
apps

## Test plan
- [x] Build passes
- [ ] Post-deploy: Spanish user on order success page → "Back to Nomad
Karaoke" → nomadkaraoke.com/es/

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 03:17:20 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 4fd701ad21 fix(i18n): add LanguageSwitcher to landing page and dashboard (#664)
## Summary
- Add `LanguageSwitcher` dropdown to the landing page nav bar (before
theme toggle)
- Add `LanguageSwitcher` to the dashboard header (before AuthStatus)
- Previously it was only in `AppHeader` used on review pages — users on
the landing page and dashboard had no way to switch language

## Test plan
- [x] `next build` succeeds
- [ ] Post-deploy: verify language dropdown visible on landing page
- [ ] Post-deploy: verify language dropdown visible on dashboard when
logged in

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 02:53:14 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 9c1e951fd0 feat(i18n): localize email bodies + non-locale route redirects (#663)
## Summary
- **P1**: Replace 5 duplicate non-locale route pages (`/app`,
`/app/jobs`, `/auth/verify`, `/payment/success`, `/order/success`) with
thin `LocaleRedirect` component — detects locale from
localStorage/navigator and redirects to `/{locale}/...`
- **P2**: Localize all user-facing email bodies (7 inline types + 4
template defaults + shared footer). Adds ~80 translation keys to
en/es/de.json. Template service now tries locale-specific GCS paths
before falling back to localized defaults.
- Fix admin dropdown link using locale-aware Link (should use NextLink
since `/admin` is outside locale routing)

### Email types localized
Magic link, welcome, credits added, review reminder, review expired,
made-for-you order confirmation, credit denied, action reminder alert,
job completion/action needed/YouTube upload template defaults, shared
footer

### Not localized (intentionally)
Admin-only: feedback notification, credit review, admin order
notification

## Test plan
- [x] Backend: 2668 tests pass (139 skipped)
- [x] Frontend: `next build` succeeds with all locale directories
- [x] CodeRabbit: 1 finding fixed (admin dropdown link)
- [ ] Post-deploy: verify Spanish user receives localized email body
(magic link flow)
- [ ] Post-deploy: verify `/app` redirects to `/{locale}/app`

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 02:28:17 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 648a26d462 fix(i18n): locale-aware navigation for internal links (#662)
## Summary
- Replace `next/navigation` and `next/link` imports with
`@/i18n/routing` equivalents in 13 user-facing components and pages so
`router.push()` and `<Link>` automatically include the locale prefix
(`/es/`, `/de/`)
- Without this fix, users on Spanish/German routes were kicked back to
non-locale paths on every internal navigation click
- Admin navigation (`/admin`) correctly excluded from locale routing
(uses `next/link` / `window.location`)
- Fix Jest ESM transform for `next-intl` transitive deps and add global
`@/i18n/routing` mock

## Test plan
- [x] `next build` succeeds — all 3 locale directories generated
(`/en/`, `/es/`, `/de/`)
- [x] 39 Jest test suites / 707 tests pass
- [x] CodeRabbit review: clean, no findings
- [ ] Post-deploy: verify `/es/app` links navigate to `/es/` prefixed
routes
- [ ] Post-deploy: verify admin link from header goes to `/admin` (no
locale prefix)

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 01:34:57 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 b486fba790 fix: sanitize artist/title for CDG/TXT packaging (trailing period) (#661)
## Summary
- Fixes TXT packaging failure when song title ends with a period (e.g.
`Lofi Ver.`)
- Root cause: orchestrator's `sanitize_filename()` strips trailing
periods but CDG generator's internal sanitization does not, causing MP3
filename mismatch
- Now passes sanitized artist/title to CDG generator and reuses the
actual MP3 path for TXT packaging
- Adds 2 regression tests for the trailing-period filename scenario

## Details
Job `4117228f` (`Gió - JanK x Quanvrox「Lofi Ver.`) failed 5 times with
"TXT generation was enabled but failed" because:
1. Orchestrator sanitized title to `Lofi Ver` (no period)
2. CDG generator kept `Lofi Ver.` (with period) in ZIP filenames
3. TXT step looked for `...Lofi Ver (Karaoke).mp3` but file was `...Lofi
Ver. (Karaoke).mp3`

## Test plan
- [x] 67 orchestrator tests pass (including 2 new regression tests)
- [x] `test_cdg_packaging_uses_sanitized_artist_title` - verifies
sanitized values passed to CDG
- [x] `test_txt_uses_mp3_path_from_cdg_generation` - verifies TXT uses
actual CDG MP3 path
- [ ] Retry job 4117228f after deployment

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 01:27:44 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 04b5d16774 feat(i18n): add real Spanish and German translations (Gemini pipeline) (#660)
@coderabbitai ignore

## Summary
- Runs the two-pass Gemini 3.1 Pro translation pipeline on all English
strings
- **Frontend:** 1062/1062 keys translated for Spanish and German
- **Backend:** 186/186 keys translated for Spanish and German
- Uses karaoke-specific glossary (55 terms) for consistency
- 100% key coverage, valid JSON for all locales

## Sample translations
- "Create a Karaoke Video for Any Song" → "Crea un video de karaoke para
cualquier canción" (ES) / "Erstelle ein Karaoke-Video für jeden Song"
(DE)
- "Job not found" → "Trabajo no encontrado" (ES) / "Auftrag nicht
gefunden" (DE)

## Test plan
- [x] Build succeeds with real translations (45 pages generated)
- [ ] Post-deploy: visit /es/ and verify Spanish content
- [ ] Post-deploy: visit /de/ and verify German content
- [ ] Post-deploy: switch language via LanguageSwitcher

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 04:48:37 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 6ca0a58c14 feat(i18n): Phase 3 PR 4 — email localization, URL prefixes, user locale (#659)
@coderabbitai ignore

## Summary
- Final Phase 3 PR — localizes email subjects, adds locale prefix to all
frontend URLs in emails, persists user locale on login
- Adds `locale` parameter (default "en") to all 10 user-facing email
methods
- Job notification service looks up user locale from Firestore before
sending
- Stale review processor passes locale to reminder/expiry emails
- On magic link verification, user's locale is stored to Firestore for
async email use
- 11 new email subject translation keys in
`backend/translations/en.json`

## Test plan
- [x] 2897 backend tests pass (1 pre-existing flaky test)
- [x] 6 test files updated for locale-prefixed URL assertions
- [ ] Post-deploy: verify magic link email has /en/ prefix in verify URL
- [ ] Post-deploy: verify review reminder email has /en/ prefix in
review URL

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 04:08:29 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 9e9c4582a6 feat(i18n): Phase 3 backend — i18n utility, 209 strings, all routes localized (#658)
@coderabbitai ignore

## Summary
- Backend i18n for karaoke-gen (Phase 3, PR 3 of 4)
- Adds `backend/i18n.py` utility with `t()`,
`get_locale_from_request()`, `get_locale_prefix()`
- **209 strings** extracted into `backend/translations/en.json` across
13 namespaces
- All 12 user-facing route files converted to use `t(locale,
"namespace.key")`
- Push notification titles/bodies localized
- `InsufficientCreditsError` handler localized
- User model gains `locale` field for async process locale preference
- 22 new i18n unit tests + 3 existing tests updated

## Changes by file
- **New:** `backend/i18n.py`, `backend/translations/{en,es,de}.json`,
`backend/tests/test_i18n.py`
- **Modified:** 12 route files (auth, jobs, users, review, audio_search,
file_upload, catalog, themes, tenant, push, rate_limits, admin)
- **Modified:** `backend/main.py` (exception handler),
`backend/services/push_notification_service.py`,
`backend/models/user.py`

## Test plan
- [x] 22 new i18n unit tests pass
- [x] Full backend test suite passes (2895+ tests)
- [x] Frontend tests unaffected (707 pass)
- [ ] Post-deploy: verify API returns English strings (Accept-Language:
en)
- [ ] Post-deploy: verify Accept-Language: es returns Spanish when
translations are ready

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 23:15:52 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 cba0e00bcc fix(i18n): add DefaultIntlProvider for non-locale routes (#657)
@coderabbitai ignore

## Summary
- Hotfix for #656 — shared components using `useTranslations()` crashed
on non-locale routes (`/app`, `/admin`) because they had no
`NextIntlClientProvider`
- Adds `DefaultIntlProvider` (client component) to root layout that
provides English translations as fallback
- The `[locale]/layout.tsx` overrides this for locale-prefixed routes

## Test plan
- [x] All 707 frontend tests pass
- [x] Static build generates all 45 pages
- [ ] Verify `/app` dashboard loads without errors
- [ ] Verify `/admin` pages load without errors
- [ ] Verify `/en/app` still works with locale-specific provider

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 22:16:29 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 8c1dfe5460 feat(i18n): Phase 3 frontend — next-intl infrastructure + 1062 strings (en/es/de) (#656)
@coderabbitai ignore

## Summary
- Phase 3 of the i18n multilingual initiative — makes the karaoke-gen
frontend fully multilingual (English, Spanish, German)
- Installs `next-intl` with `[locale]` path-based routing,
LanguageSwitcher, and `Accept-Language` API header
- Extracts **1,062 strings** from ~70 components into `messages/en.json`
across 31 namespaces
- Wires `useTranslations()` into all user-facing components (landing,
dashboard, auth, job flow, lyrics review, instrumental review, audio
editor, etc.)
- Admin pages (`/admin/*`) stay outside locale routing — intentionally
excluded from i18n scope
- Static export generates `/en/`, `/es/`, `/de/` directories (45 total
pages) for Cloudflare Pages
- `es.json`/`de.json` are English placeholders — translation via Gemini
pipeline pending
- Translation pipeline (`scripts/translate.py`) and glossary (55
karaoke-specific terms) included

## Key architecture decisions
- Root layout keeps ThemeProvider/TenantProvider (needed by admin pages
outside `[locale]`)
- Only NextIntlClientProvider added to `[locale]/layout.tsx`
- `job-status.ts` labels converted to translation keys; consumers
translate via `useTranslations('jobStatus')`
- Jest mock loads actual `en.json` so existing tests validate i18n
wiring without assertion changes

## Test plan
- [x] All 707 frontend tests pass (39 suites)
- [x] Static build generates all 45 pages across 3 locales
- [x] Admin pages render at `/admin/` without locale prefix
- [x] CodeRabbit review: 4 issues fixed, 7 pre-existing noted
- [ ] Post-deploy: verify `/en/` landing page renders correctly
- [ ] Post-deploy: verify LanguageSwitcher redirects to `/es/` and
`/de/`
- [ ] Post-deploy: verify `/admin/` still works without locale context

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 21:50:53 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 105a5b28fd fix: default dashboard to all jobs, fix E2E completion detection (#655)
## Summary
- Default the dashboard status filter from "active" to "all" so
completed jobs remain visible (existing localStorage preferences
preserved)
- Add recovery logic to E2E happy path test: after 10 consecutive "card
unavailable" polls, automatically switch the filter dropdown to "All
statuses"
- Bump version to 0.157.4

**Root cause:** The daily E2E test (run #126) timed out at Step 9
because the "active" filter uses `hide_completed: true` at the API level
— when the job completed, the card vanished from the DOM and the test
retried for ~25 min until timeout. The generator itself was working
fine.

## Test plan
- [x] All 707 tests pass (`make test`)
- [x] CodeRabbit review clean (1 finding fixed)
- [ ] Next scheduled E2E run should pass with these changes

@coderabbitai ignore

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

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 11:41:48 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 a0e6448e7b fix: make E2E job card polling resilient to transient DOM changes (#654)
## Summary
- E2E happy path test failed because the job card DOM element briefly
disappeared during a status transition (step 9/10 "Packaging files"),
causing an unhandled `TimeoutError` on `jobCard.textContent()`
- Wrapped all `textContent()` calls in polling loops with try/catch and
a 15s explicit timeout so transient DOM disappearances retry instead of
crashing the test
- Applied fix to both `happy-path-real-user.spec.ts` and
`demo-recording.spec.ts`

Fixes:
https://github.com/nomadkaraoke/karaoke-gen/actions/runs/23887007717

## Test plan
- [x] Verified TypeScript has no new errors (all existing errors are
pre-existing Playwright type issues)
- [ ] Next scheduled E2E run will validate the fix against production

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 03:11:12 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 fbe3edceec fix: video worker downloads PNG instead of MOV for screens (#650)
## Summary

Follow-up to #647. The video worker was hardcoded to download
`title.mov`/`end.mov` from GCS, but those no longer exist after the
screens_worker change. 404 error on all job retries.

- `video_worker.py`: download PNG (or MOV for legacy), validate with PNG
fallback
- `video_worker_orchestrator.py`: `_screen_ext()` helper for dynamic
file extension

## Test plan

- [x] All video unit tests pass
- [ ] Retry job f0d51a0a after deploy

@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-31 23:39:57 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 ead074505b fix: skip files >3GB in divebar sync to prevent OOM kills (#653)
## Summary

- Skip files larger than 3GB in divebar file sync — the VM has 4GB RAM
and buffers files in memory, so a 4.3GB MKV was causing OOM kills every
run
- Sets `gcs_path = 'skipped:too_large'` so the file won't be retried
nightly (the `WHERE gcs_path IS NULL` query excludes it)
- Only 1 file currently affected: `IMBK-0068 - Zolas - Ancient Mars.mkv`
(4.3 GB)

@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-31 23:24:56 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 7e93d62457 fix: thread-safe Drive service in divebar file sync (#651)
## Summary

- Use `threading.local()` for Drive API service — `googleapiclient` is
not thread-safe and sharing across `ThreadPoolExecutor` workers caused
SSL errors, bad file descriptors, and heap corruption (`free():
corrupted unsorted chunks`)
- This is why ~200 files were permanently stuck with `gcs_path=NULL` —
different files failed each run depending on thread timing

**Evidence from VM logs:**
```
ERROR Failed files/NOMAD-1346.zip: 'email'
ERROR Failed files/Shark Attack.zip: [Errno 9] Bad file descriptor
ERROR Failed files/KGAL-0004.zip: [SSL: DECRYPTION_FAILED_OR_BAD_RECORD_MAC]
ERROR Failed files/LSWK-0024.zip: [SSL: WRONG_VERSION_NUMBER]
free(): corrupted unsorted chunks
```

## Test plan

- [x] Existing unit tests pass
- [ ] Next nightly file sync run should have 0 failures (was ~200/run)
- [ ] Monitor `gcs_path IS NULL` count — should drop to only genuinely
new files

@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-31 23:04:54 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 1c846ebae7 fix: preserve gcs_path in divebar catalog sync (#649)
## Summary

- **index_builder.py**: replaced `WRITE_TRUNCATE` with staging table +
`MERGE` SQL to preserve `gcs_path` values during daily catalog index
updates
- **divebar_file_sync.py**: added `blob.exists()` check before
downloading from Drive — if a file is already in GCS, just updates
`gcs_path` in BigQuery without re-downloading
- Added unit tests verifying the MERGE approach preserves `gcs_path`
correctly

**Root cause**: The daily 2 AM index sync was atomically replacing the
entire `divebar_catalog` BigQuery table, wiping all `gcs_path` values.
The 3 AM file sync then saw all ~48K files as unsynced and re-downloaded
the entire ~779 GB catalog from Google Drive every night.

## Test plan

- [x] Unit tests for staging+MERGE behavior (5 tests pass)
- [ ] Verify staging table auto-creates on first run (BigQuery creates
on WRITE_TRUNCATE with schema)
- [ ] Monitor next nightly sync — file_sync should report "recovered
from GCS" instead of downloading
- [ ] Confirm gcs_path values persist across consecutive index runs

@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-31 22:31:42 +00:00
Andrew Beveridge ☄️andClaude Sonnet 4.6 c02fdc8d9f Fix GCE cache invalidation and empty corrections handling (#648)
## Summary
- **GCE style asset disk cache** now validates file size against GCS on
cache hit, re-downloading when content has changed at the same URI.
Transient GCS errors gracefully fall back to cached version.
- **Review complete endpoint** no longer writes
`corrections_updated.json` when no corrections data is present (root
cause fix for KeyError in render workers).
- **Both GCE and Cloud Run render workers** validate
`corrections_updated.json` has a `corrections` key before processing,
falling back to base result gracefully (defensive fix).

## Test plan
- [x] Added `test_cache_hit_redownloads_on_size_mismatch` — verifies
stale cache replaced
- [x] Updated `test_cache_hit_skips_download` for size validation flow
- [x] Added `test_gce_worker_skips_empty_corrections` — verifies empty
dict doesn't crash
- [x] Added `TestCompleteReviewSkipsEmptyCorrections` — 4 tests covering
guard conditions
- [x] All 2875 tests pass (8 pre-existing emulator failures unrelated)

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-31 18:03:26 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 3bc1fcb250 fix: move screen video generation to GCE encoding worker (#647)
## Summary

- Screen MOV generation (4K H.264) was silently failing on Cloud Run
after right-sizing to 2Gi (PR #640), producing 36-byte empty shells that
broke all downstream encoding
- `screens_worker` now only generates PNG/JPG images (Pillow, no FFmpeg)
- GCE encoding worker generates MOV from PNG before encoding, with
proper `subprocess.run()` error handling
- Fixed `os.system()` in `video_generator.py` to use `subprocess.run()`
so failures are no longer silent

## Root Cause

PR #640 reduced Cloud Run from 8CPU/16Gi to 2CPU/2Gi. The
`VideoGenerator._create_video_from_image()` used `os.system(ffmpeg ...)`
which OOMs silently for 4K H.264 encoding, producing 36-byte empty MOV
shells. All jobs since March 31 are affected.

## Test plan

- [x] 2875 tests pass (8 pre-existing emulator failures unrelated)
- [x] CodeRabbit: no findings
- [ ] Re-run failed job f0d51a0a after deploy to verify fix
- [ ] Verify admin "Regen screens" button works (tested flow: deletes
old screens → worker generates PNG/JPG only → GCE generates MOV from
PNG)

@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-31 21:44:53 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 adae022fbf Fix encoding progress callback causing invalid state transition (#646)
## Summary
- Fix `encoding -> encoding` invalid state transition that caused job
7bbd0d9d to fail
- The GCE encoding `progress_callback` was using `transition_to_state()`
to update progress while already in ENCODING state, which the state
machine correctly rejects as a self-transition
- Changed to `update_job()` which updates progress/message without
validating state transitions

## Test plan
- [x] All 2875 backend tests pass (8 pre-existing emulator failures
unrelated to change)
- [x] State machine integration tests pass
- [x] Encoding interface contract 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-31 21:19:47 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 9ccad7c6d3 feat: service health status modal with blue-green deploy details (#645)
## Summary
- Clickable footer opens a modal showing all service health, versions,
deploy times, and PR links
- Progressive disclosure: basic info for everyone, blue-green encoder
details for admins
- New aggregated `/api/health/system-status` endpoint (single fetch
instead of 4 separate calls)
- CI captures git SHA and PR info, passes to frontend and backend builds

## Changes
- **Backend**: New `/api/health/system-status` endpoint with optional
admin auth for blue-green Firestore config
- **Backend**: Build metadata env vars (COMMIT_SHA, PR_NUMBER, PR_TITLE,
STARTUP_TIME) in version module
- **Frontend**: New `SystemStatusModal` component with service cards and
expandable blue-green section
- **Frontend**: Footer version line is now clickable to open the modal
- **Frontend**: Build metadata env vars passed through next.config.mjs
- **CI**: Both frontend and backend deploy jobs capture and pass git SHA
+ PR info

## Testing
- [x] 3 unit tests for system-status endpoint (public, offline, admin
blue-green)
- [x] TypeScript compilation clean (no new errors)
- [x] CodeRabbit CLI reviewed

@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-31 15:42:58 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 8e2a949a29 fix: complete blue-green deploy test payload and status check (#644)
## Summary
- Fix the deploy health check test payload and status value mismatches
that prevented blue-green swaps from ever completing
- Follow-up to #642 which fixed the error handling / rollback conditions

## Changes
- **Missing required fields**: `encode-preview` requires
`audio_gcs_path` and `output_gcs_path` but the health check only sent
`job_id`, `ass_gcs_path`, and `duration_seconds` (caused HTTP 422).
Added a 3-second test audio file and proper output path.
- **Status polling mismatch**: Polling checked for `"completed"` but the
GCE worker returns `"complete"` — would always time out even on success.
- **Submit response mismatch**: Validated against `"completed"` which is
never returned — endpoint returns `"accepted"`, `"cached"`, or
`"in_progress"`.

## Root Cause
The test payload was written based on the plan doc which had an
incomplete request schema. The `audio_gcs_path` and `output_gcs_path`
fields have been required since the endpoint was first created (PR #200,
Jan 2026). The status string mismatch (`"completed"` vs `"complete"`)
was likely a typo that was never caught because the request always
failed before reaching the polling stage.

## Testing
- Previous deploy (#642) confirmed the 422 error and verified rollback
now triggers correctly
- This fix addresses the payload so the encode test can actually succeed
and the swap can complete
- Real validation: next deploy after merge

@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-31 14:07:38 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 0464d3edb3 Fix render_video GCE endpoint import paths (#643)
@coderabbitai ignore

## Summary

- Fix broken import paths in GCE worker's `/render-video` endpoint that
caused `ImportError: No module named 'backend.output_generator'` in
production
- Fix incorrect API signatures for OutputGenerator, CountdownProcessor,
CorrectionResult, load_styles_from_gcs
- Update tests to mock correct module paths

## Root cause

The subagent that implemented Task 2 (PR #641) used invented module
paths (`backend.output_generator`,
`backend.services.countdown_processor`, etc.) instead of the actual
karaoke-gen wheel paths
(`karaoke_gen.lyrics_transcriber.output.generator`, etc.). The tests
also mocked the wrong paths, so they passed locally but the code failed
in production.

## Changes

- `backend/services/gce_encoding/main.py` — Rewrote `run_render_video()`
to use correct imports and API calls matching `render_video_worker.py`
- `tests/unit/test_gce_render_video_endpoint.py` — Rewrote
TestRunRenderVideo to mock correct module paths

## Test plan

- [ ] 18 unit tests pass (verified locally with
`GOOGLE_CLOUD_PROJECT=""` to simulate CI)
- [ ] E2E happy path test after merge validates full pipeline

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 14:01:36 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 5dfaa3f73f fix: blue-green deploy health check and rollback conditions (#642)
## Summary
- Fix blue-green deploy workflow that has been silently failing since
v0.151.0 (March 25)
- Every deploy has fallen through to `ensure_latest_wheel()` hot-update
instead of tested blue-green swap

## Changes
- **Health check curl**: Replace `curl -sf` (which exits immediately on
HTTP errors before setting output) with `curl -s -o file -w
'%{http_code}'` to capture HTTP status without early exit
- **Status polling curl**: Remove `-f` flag and add fallback for failed
status checks
- **Rollback condition**: Change `passed == 'false'` to `passed !=
'true'` to catch unset/skipped cases (defense in depth)

## Root Cause
`curl -sf` with `-f` (fail silently) exits non-zero on HTTP errors.
Combined with GitHub Actions' `set -e`, the script exits before writing
`passed=false` to `$GITHUB_OUTPUT`. Both the rollback (`== 'false'`) and
swap (`== 'true'`) conditions evaluate false against the unset output,
creating a silent no-op.

## Testing
- [x] CI workflow syntax validated
- [x] CodeRabbit CLI review completed locally (no issues in changed
file)
- Real validation: next deploy will exercise the fixed workflow

@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-31 13:46:30 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 1cf6b62398 Route render_video to GCE encoding worker (#641)
@coderabbitai ignore

## Summary

- Route `render_video_worker` (OutputGenerator/ffmpeg lyrics rendering)
to the GCE encoding worker instead of running on Cloud Run
- Fixes OOM crashes after Cloud Run memory was right-sized to 2Gi
- Adds style asset disk cache on GCE worker to avoid repeated downloads
of the same default theme
- Preserves local fallback when GCE is disabled

## Changes

### GCE Worker (`backend/services/gce_encoding/main.py`)
- New `/render-video` endpoint with `RenderVideoRequest` model
- `run_render_video()` — downloads corrections/audio/styles from GCS,
runs OutputGenerator, uploads outputs
- `download_with_cache()` — SHA-256 keyed disk cache for style assets
(fonts, backgrounds)
- `metadata` field added to `JobStatus` model for countdown padding info

### EncodingService (`backend/services/encoding_service.py`)
- `submit_render_video_job()` — POST to `/render-video` with retry logic
- `render_video_on_gce()` — submit + wait convenience method

### render_video_worker (`backend/workers/render_video_worker.py`)
- Conditional GCE routing when `encoding_service.is_enabled`
- Cloud Run does zero downloads in GCE path — constructs GCS paths from
Firestore metadata
- Existing local path preserved unchanged as fallback

## Test plan

- [ ] 18 new unit tests covering cache, endpoint, service methods, and
routing logic (all pass)
- [ ] Full test suite: 1164 passed, 0 failures
- [ ] CodeRabbit review: 1 bug caught and fixed (missing metadata in
cached response)
- [ ] E2E happy path CI validates full pipeline after merge

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 16:58:00 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 82e9becc7c chore: right-size Cloud Run + fix divebar-sync auto-shutdown (#640)
## Summary
- Right-size karaoke-backend Cloud Run: concurrency 1→80, minScale 4→1,
CPU 8→2, memory 16Gi→2Gi, enable cpu-throttling, maxScale 50→20
- Fix divebar-sync VM: add missing `shutdown -h now` after file sync
completes (VM was staying on 24/7)

## Cost Impact
- Backend right-sizing: ~$1,800/mo savings
- Divebar-sync fix: ~$32/mo savings
- Part of broader GCP cost reduction
(docs/2026-03-31-cost-reduction-design.md)

## Context
The backend is an I/O-bound API orchestrator (Firestore queries + Cloud
Run job dispatch). Heavy processing was moved to Cloud Run Jobs and a
dedicated GCE encoding worker months ago, but the Cloud Run config was
never updated. Concurrency=1 forced one-request-per-instance, and
minScale=4 kept 4 instances of 8CPU/16Gi running 24/7.

Changes have already been applied live via `gcloud run services update`
and verified with health checks.

## Test plan
- [x] All 6 Cloud Run settings updated incrementally with health checks
between each
- [x] `curl https://api.nomadkaraoke.com/api/health` returns 200 after
all changes
- [x] Divebar-sync VM stopped and metadata updated with new startup
script
- [ ] Monitor billing data over next 24-48h to confirm cost reduction

@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-31 10:00:16 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 ca0d5507b2 Business continuity: DR backups, read-only SA, deny policies (#639)
## Summary

- Two-tier disaster recovery: GCP-native protections (PITR, versioning,
deny policies) + cross-cloud AWS S3 backups
- Nightly Cloud Function exports Firestore, BigQuery, and GCS job files
to AWS S3
- Read-only Claude SA (`claude-readonly`) and break-glass SA for
emergency access
- IAM deny policy blocking `buckets.delete` and `datasets.delete` for
all principals
- External backup freshness monitor (AWS Lambda alerts if backups go
stale >48h)

## Changes

**Infrastructure (Pulumi):**
- `modules/iam/claude_readonly_sa.py` — new read-only + break-glass SAs
- `modules/backup.py` — backup SA, staging bucket, Cloud Function, Cloud
Scheduler
- `modules/database.py` — enable Firestore PITR
- `modules/storage.py` — enable GCS versioning + soft delete lifecycle
- `modules/secrets.py` — add `discord-alert-webhook` secret
- `__main__.py` — wire new modules

**Backup Cloud Function:**
- `functions/backup_to_aws/` — Firestore export, BigQuery export
(weekly/monthly), GCS delta sync, S3 streaming upload, Discord alerts

**Documentation:**
- `docs/DISASTER-RECOVERY.md` — restore runbook for accidental deletion
+ catastrophic GCP loss
- `docs/archive/2026-03-27-business-continuity-design.md` — full design
spec
- `docs/archive/2026-03-29-business-continuity-plan.md` — implementation
plan
- `docs/archive/2026-03-29-external-services-config.md` —
OAuth/DNS/external service reference

## Already deployed

All infrastructure has been applied via `pulumi up`. First backup run
completed successfully (Firestore + job files in S3). Nightly backups
running at 1 AM ET.

## Test plan

- [x] Pulumi preview — 30 creates, 2 updates, 0 deletes
- [x] Pulumi up — all resources deployed
- [x] Manual backup function trigger — Firestore export (1.4 GB) landed
in S3
- [x] GCS job files sync — 161 files (2.9 GB) in S3
- [x] AWS Lambda freshness check — returned `ok` (3h age)
- [x] IAM deny policy verified active via `gcloud iam policies get`

@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-31 03:32:01 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 789bf80646 Skip welcome credit AI evaluation for test emails (#638)
## Summary
- E2E test accounts (`@inbox.testmail.app`) were triggering the
Gemini-based credit evaluation on every daily test run, wasting LLM
credits and sending unnecessary denial emails
- Skip both the pre-compute (at magic link send) and inline evaluation
(at verification) for test emails — they get auto-granted directly

## Changes
- `backend/api/routes/users.py`: Skip background pre-compute thread for
test emails
- `backend/services/user_service.py`: Skip AI evaluation in
`grant_welcome_credits_if_eligible()` for test emails, go straight to
granting
- `backend/tests/test_anti_abuse.py`: Add test verifying AI eval is
skipped for testmail addresses

## Testing
- [x] All 2872 unit tests pass (8 pre-existing emulator failures
unrelated)
- [x] New test `test_skips_evaluation_for_test_emails` verifies behavior

## Review
- [x] Local CodeRabbit review completed — no findings

@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-30 14:37:14 -04:00
Andrew Beveridge ☄️ c98da49da9 feat: add jobs search, status filter, and fix loading states (#637)
## Summary
- Add server-side text search to jobs list API (case-insensitive
substring match across artist, title, job_id)
- Replace eye icon toggle with status filter dropdown (All statuses,
Active, Failed, Completed, Cancelled, Awaiting review, Processing)
- Add debounced search input to Recent Jobs header
- Expand limit dropdown options (5, 10, 20, 50, 100, 1000)
- Fix loading state showing "No jobs yet" during cold starts (now shows
spinner)
- Fix API always fetching limit=100 regardless of dropdown selection

## Test plan
- [x] 8 unit tests for `_search_filter_jobs` (artist, title, job_id,
audio search fields, case insensitivity, None handling, empty string,
limit interaction)
- [x] Full backend test suite passes (2870 passed)
- [x] Frontend builds cleanly
- [ ] Manual: verify search filters jobs in real-time on dashboard
- [ ] Manual: verify status dropdown filters correctly
- [ ] Manual: verify loading spinner shows during cold starts instead of
"No jobs yet"

<!-- @coderabbitai ignore -->

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-03-30 05:03:05 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 022b4e343a fix: backing vocals recommendation showing 0% with contradictory message (#636)
## Summary

- Fixed API defaulting `recommended_selection` to `with_backing` when no
analysis exists, creating contradictory "Significant backing vocals
(0%)" message — now defaults to `clean`
- Fixed analyzer returning `review_needed` (unknown to frontend) instead
of `with_backing` when backing vocals detected
- Fixed race condition where backing vocals analysis ran in
screens_worker before audio separation completed — moved to audio_worker

## Test plan

- [x] All 25 analyzer unit tests pass (3 updated to match new
`WITH_BACKING` return value)
- [x] All 21 frontend instrumental review component tests pass
- [x] Full test suite: 2863 passed (8 pre-existing emulator failures)
- [x] CodeRabbit: no findings
- [ ] Verify fix in production: create new job and check instrumental
review shows correct recommendation

@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-30 00:39:59 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 16fcb77d0f fix: relevance filtering in correction_disabled path + guidance message (#635)
## Summary

Two fixes found during post-deploy testing of #632:

1. **Relevance filter bypassed when SKIP_CORRECTION=true** — The
controller's `create_uncorrected_result()` path builds CorrectionResult
directly without going through LyricsCorrector, so wrong-song references
were never filtered. Now applies `filter_irrelevant_sources()` in this
path too.

2. **Misleading "All lyrics matched" message** — When no reference
sources exist (all filtered or none found), the guidance panel showed
"All lyrics matched the reference — no corrections needed." Now shows
"No reference lyrics were found" with guidance to use the search panel.

## Testing

- 9/9 relevance tests passing
- 22/22 GuidancePanel tests passing (updated + new test for empty state)

@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-30 04:21:58 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 14a6b767ce fix: improve cancelled job UX and fix /dashboard redirects (#633)
## Summary
- Allow downloading files from cancelled jobs (backend no longer
requires job to be complete if the file exists in GCS)
- Hide cancelled jobs from default recent jobs view alongside completed
jobs; visible via "Show all jobs" toggle
- Fix stale `/dashboard` routes → `/app` (including impersonation
redirect that 404'd)
- Show accurate total job count and helpful empty state when jobs are
filtered out

## Test plan
- [x] Backend unit tests pass (2837 passed)
- [x] Frontend unit tests pass (717 passed, 39 suites)
- [ ] Verify cancelled job download works in prod after deploy
- [ ] Verify impersonation redirects to /app correctly
- [ ] Verify "Show all jobs" toggle shows/hides cancelled and completed
jobs
- [ ] Verify empty state message shows correct total and eye icon hint

@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-29 20:49:28 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 591c050545 feat: Reference lyrics search with relevance filtering (#632)
## Summary

- Add relevance filtering to the correction pipeline — automatically
rejects wrong-song reference lyrics (below 30% word match threshold,
validated against 168 prod source pairs)
- New `POST /api/review/{job_id}/search-lyrics` endpoint lets users
search with alternate artist/title from the review UI, with force-add
override for edge cases
- Redesigned Add Reference Lyrics modal with Search (default) and Paste
tabs, plus inline empty state when no valid sources exist

## Changes

### Backend
- **Relevance filtering** (`correction/relevance.py`): Per-source
scoring based on anchor sequence word coverage. Integrated into
`LyricsCorrector.run()` after anchor finding — sources below threshold
removed before corrections computed
- **Search endpoint** (`routes/review.py`): Queries all providers
(Genius, Spotify, Musixmatch, LRCLIB) with user-supplied artist/title,
auto-filters results, returns added/rejected/not-found breakdown
- **Provider factory** (`operations.py`): `create_lyrics_providers()`
reads env vars, `search_lyrics_sources()` orchestrates
fetch+filter+correct
- **Force override**: `add-lyrics` and `search-lyrics` support `force`
flag to bypass threshold

### Frontend
- **Tabbed modal**: `AddLyricsModal` rewritten with Search (default) and
Paste tabs
- **SearchLyricsTab**: Artist/title inputs, provider search, rejected
source cards with force-add checkboxes
- **ReferenceEmptyState**: Inline search/paste UI when no valid
reference sources exist
- **API client**: New `searchLyrics()` method with
`SearchLyricsResponse` types

### Analysis
- Empirical threshold analysis script
(`scripts/analyze_reference_relevance.py`) + visual review tool
- 168 source pairs from 81 prod jobs: wrong-song max 3.5%, correct-song
min 26.8% → 30% threshold

## Testing
- 35 new backend tests (relevance scoring, filtering, corrector
integration, search operation, API endpoint)
- 717 existing frontend tests passing (no regressions)
- Edge case: all sources filtered out handled gracefully

## Review
- [x] Local CodeRabbit review completed (3 issues fixed: response
contract, force param coercion, null checks)

@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-30 00:25:47 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 5a5ee4a780 fix: validate Google OIDC tokens from Cloud Scheduler (#631)
## Summary
- All 4 Cloud Scheduler → backend jobs (stale review processor, stuck
job recovery, YouTube queue, disposable domain sync) were returning 401
because the auth system didn't validate Google OIDC JWT tokens
- Added OIDC token validation to `AuthService.validate_token_full()`
using `google.oauth2.id_token.verify_oauth2_token()`
- Only accepts tokens signed by Google from the configured backend
service account

## Changes
- `backend/services/auth_service.py` — New `_validate_oidc_token()`
method + integration into `validate_token_full()`
- `backend/config.py` — New `SCHEDULER_SERVICE_ACCOUNT` setting
(defaults to `karaoke-backend@nomadkaraoke.iam.gserviceaccount.com`)
- `backend/tests/test_auth_oidc.py` — 10 unit tests covering all code
paths
- `docs/LESSONS-LEARNED.md` — New lesson about Cloud Scheduler OIDC vs
admin token auth
- `pyproject.toml` — Version bump 0.153.6 → 0.153.7

## Testing
- [x] 10 new unit tests (valid token, wrong SA, expired, invalid
signature, network error, passthrough)
- [x] Full backend suite: 2837 passed
- [x] Full frontend suite: 717 passed

## Review
- [x] Local CodeRabbit review completed (no findings)
- [x] Docs reviewed and updated

@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-29 20:00:36 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 f6102e11ab fix: correct admin credits API path in e2e test (#630)
## Summary
- Follow-up to #629 — the admin credits endpoint is at
`/api/users/admin/credits` (users router prefix `/users`), not
`/api/admin/credits`
- One-line fix to the URL in the e2e test

<!-- @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-29 12:59:18 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 dba4ea1912 fix: grant credits via admin API when e2e test user gets 0 credits (#629)
## Summary
- Follow-up to #625 and #628 — after fixing the disposable email
allowlist and credit interstitial handling, the e2e test hits a third
issue: the credit evaluation system denies credits to testmail.app
users, leaving the guided flow inputs disabled
- Now detects 0 credits after signup and uses `E2E_ADMIN_TOKEN` to grant
1 credit via the admin API, then reloads the page

## Changes
- `frontend/e2e/production/happy-path-real-user.spec.ts`: After signup,
check credit balance and grant via admin API if 0

## Test plan
- [ ] E2E happy path test passes after merge (triggered manually)

<!-- @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-29 12:48:19 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 dbadcc5c17 fix: handle credit interstitial in e2e happy path test (#628)
## Summary
- Follow-up to #625 — after fixing the disposable email allowlist, the
e2e test hit a second failure: the magic link verification page now
shows credit evaluation interstitials for new users instead of
"Successfully signed in!" (which is only for returning users)
- The test now handles all verification outcomes (credits_granted,
credits_denied, credits_pending, success) and clicks through credit
interstitials to reach /app

## Changes
- `frontend/e2e/production/happy-path-real-user.spec.ts`: Use
`Promise.race` to detect which verification state appears, handle credit
interstitials by clicking through

## Test plan
- [ ] E2E happy path test passes after deployment (triggered manually)

<!-- @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-29 12:38:30 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 257315d632 ci: use poetry.lock for GPU base image hash to avoid needless rebuilds (#627)
## Summary

- Use `poetry.lock` instead of `pyproject.toml` when computing the GPU
base image content hash
- Prevents expensive 15-20 min GPU base image rebuilds on version-only
bumps

## Problem

The GPU base image hash was computed from `cat Dockerfile.gpu-base
pyproject.toml | sha256sum`. Any change to `pyproject.toml` — including
version bumps that don't change dependencies — triggered a full GPU base
image rebuild. This adds ~15-20 min to every deploy that follows a
version bump.

## Fix

`poetry.lock` is the authoritative record of resolved dependencies. It
only changes when actual dependencies are added/removed/updated, not on
version bumps. The GPU base image installs deps via `pip install -e .`
which reads `pyproject.toml` at build time, but the Docker layer cache
handles that separately — the CI hash check just needs to know if deps
changed.

@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-29 11:30:50 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 92d1c9729d ci: auto-update lyrics-transcription-job on deploy (#626)
## Summary

- Add `lyrics-transcription-job` to the CI deploy step that updates
Cloud Run Jobs
- Previously only `video-encoding-job` and `audio-separation-job` were
updated, requiring manual `gcloud run jobs update` for lyrics

## Context

Discovered during the anchor IndexError fix (#623) — the fix was
deployed to the Cloud Run Service automatically but the Cloud Run Job
(where lyrics transcription actually runs) had to be updated manually.

## Changes

- `.github/workflows/ci.yml`: Add `gcloud run jobs update
lyrics-transcription-job` alongside the existing job updates

@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-29 10:52:02 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 cd3076fc58 fix: allowlisted domains bypassed by external disposable email APIs (#625)
## Summary
- The disposable email detection had a bug where the Firestore
`allowlisted_domains` only protected against the Tier 1 static blocklist
check. External API checks (DeBounce, verifymail.io) at Tiers 3-4 ran
regardless and could override admin allowlist decisions.
- This broke the E2E happy path test starting March 21 when
`inbox.testmail.app` got flagged by DeBounce as disposable — the signup
step failed because "Check Your Email" never appeared.
- Adds a "Tier 1.5" check so allowlisted domains skip external API calls
entirely, plus a CI setup step to ensure the domain stays allowlisted.

## Changes
- `backend/services/email_validation_service.py`: Add allowlist check
before external API calls; include `allowlisted_domains` in cached
config
- `backend/tests/test_email_validation_service.py`: Regression test for
allowlisted domain bypass
- `.github/workflows/e2e-happy-path.yml`: CI setup step to ensure
`inbox.testmail.app` is allowlisted before test runs

## Test plan
- [x] All 53 email validation tests pass (52 existing + 1 new regression
test)
- [x] `inbox.testmail.app` added to production Firestore allowlist
- [ ] E2E happy path test passes after deployment

<!-- @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-29 10:48:24 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 78e4cc7010 fix: bounds check ref_words in anchor gap extension (IndexError b7e8c96d) (#623)
## Summary

- Fix IndexError in `_extend_anchors_into_single_word_gaps` when
`ref_texts_clean` and `ref_words` have different word counts due to
`clean_text()` normalization
- Adds production fixture regression test from crashing job `b7e8c96d`
(Bằng Kiều - Dẫu có lỗi lầm)

## Root Cause

`ref_texts_clean` is built by joining words → `clean_text()` →
`split()`, which can produce a **different word count** than the raw
`ref_words` Word objects list. For Spotify in the crashing job:
`ref_texts_clean` had 599 words, `ref_words` had 528. Anchor
`reference_positions` computed against the 599-word list were used to
index the 528-word list.

## Changes

- `anchor_sequence.py`: Add `< len(ref_words[source])` bounds check in
both `_apply_forward_extension` and `_apply_backward_extension`
- `test_anchor_gap_extension_bounds.py`: 4 regression tests (production
fixture + synthetic bounds tests)
- `anchor_crash_b7e8c96d.json`: Sanitized production fixture (49
anchors, 526 words)
- `LESSONS-LEARNED.md`: Document text normalization word count mismatch
gotcha
- Version bump: 0.153.4 → 0.153.5

## Testing

- [x] 33 anchor gap extension tests pass (29 existing + 4 new)
- [x] Full unit suite: 1146 tests pass
- [ ] After deploy: retry job `b7e8c96d`

## Review

- [x] CodeRabbit CLI review completed locally (1 finding fixed:
sanitized copyrighted lyrics)

@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-28 14:23:13 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 dd25a6110f docs: troubleshooting runbooks for job repair and Cloud Run Jobs (#622)
## Summary

- Surgical audio re-separation that preserves lyrics/review data (direct
Firestore + Cloud Run Jobs API)
- How to trigger Cloud Run Jobs directly, bypassing internal API
idempotency checks
- CI gap: `lyrics-transcription-job` image not updated on deploy (manual
workaround + permanent fix pointer)

Docs-only — no code changes, no version bump.

<!-- @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-27 20:36:51 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 e3c55672e5 fix: bounds check in anchor sequence gap extension (#621)
## Summary

- Fix IndexError in `_extend_anchors_into_single_word_gaps` when
`gap_position >= len(all_words)`
- This crashes lyrics transcription for songs where the last anchor ends
at the transcription boundary
- Affected job: `b7e8c96d` (Bằng Kiều - Dẫu có lỗi lầm)

## Fix

Add `if gap_position >= len(all_words): continue` before accessing
`all_words[gap_position]`.

## Test plan

- [x] 2 new boundary regression tests in test_anchor_gap_extension.py
- [x] Full unit suite: 1142 passed (29 anchor gap tests)
- [ ] After deploy: retry job b7e8c96d

<!-- @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-27 19:51:42 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 bcbbb7865f fix: prevent false 'No audio sources found' on search failure (#620)
## Summary

- Fix misleading "No audio sources found" message that appeared when
audio search failed (timeout, network error, 5xx) instead of showing an
error
- Replace scattered boolean/string state with explicit `SearchStatus`
state machine so the no-results message can only appear after a
confirmed successful search
- Add automatic retry (up to 3 attempts with backoff) for transient
failures

## Changes

- **State machine:** Replace `isSearching`, `error`, `isCreditError`
with single `SearchStatus` discriminated union (`searching | succeeded |
failed`)
- **Retry logic:** Auto-retry network errors, timeouts, and 5xx up to 3
times with 2s/4s backoff delays. 4xx errors (auth, credits) fail
immediately
- **Spinner feedback:** Show "Retry 1 of 2" / "Retry 2 of 2" during
retries
- **Fuzzy accept:** Route through `doSearch` via useEffect instead of
inline API call, so corrected searches also get retry protection
- **Tests:** 5 new tests covering the core bug fix, retry behavior, and
error classification
- **Docs:** Added lesson learned about state conflation pattern

## Testing

- [x] 20/20 unit tests pass (15 existing + 5 new)
- [x] 712/712 full suite tests pass
- [x] TypeScript compiles cleanly
- [x] Production flacfetch verified healthy (v0.19.5, all providers up)

## Review

- [x] Local CodeRabbit review completed (no findings)
- [x] Two-stage review (spec compliance + code quality) during
implementation

@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-27 14:44:27 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 8c7627b7ec fix: prevent video worker race condition and add encoding worker warmup (#619)
## Summary
- Fix race condition where Cloud Run Job `max_retries` + manual retry
launched concurrent video workers that corrupted each other's state
transitions (job 13b8adcf)
- Add encoding worker VM warmup to all paths that trigger video
encoding, not just the frontend happy path
- Defense in depth: frontend warmup → worker dispatch warmup → encoding
retry warmup

## Changes
- **job_health_service.py**: Remove `GENERATING_VIDEO`/`RENDERING_VIDEO`
from valid video_worker startup states — if a job is already in those
states, another worker is processing it
- **video_worker.py**: Make `_validate_prerequisites` a hard failure on
wrong status (was warn-and-continue)
- **worker_service.py**: Add `_warmup_encoding_worker()` called from
both `trigger_video_worker` and `trigger_render_video_worker`
- **encoding_service.py**: Add `_warmup_encoding_worker_fallback()`
called on first connection failure in retry loop
- **docs/LESSONS-LEARNED.md**: Document both findings

## Testing
- [x] 7 new unit tests covering race condition fix, warmup dispatch, and
fallback behavior
- [x] Full backend suite passes (2817 passed)
- [x] Full frontend suite passes (712 passed)

## Review
- [x] Local CodeRabbit review completed (0 code issues)
- [x] Review feedback addressed

@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-27 14:27:29 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 0c996d1c8e fix: rename Stage 1 vocals before Stage 2 to avoid stem tag regex collision (#618)
## Summary

Follow-up to #617 — the stem tag parsing fix alone wasn't enough. The
audio-separator library's ensemble code uses
`re.search(r'_\(([^)]+)\)')` to classify intermediate stems, matching
the **first** `_(Tag)_` pattern. When Stage 2 receives Stage 1 output
like `Song_(Vocals)_preset_instrumental_clean.flac`, the regex matches
the Stage 1 tag instead of the Stage 2 tag, classifying ALL stems as
"Vocals" and producing only 1 output file instead of 2.

## Fix

Copy Stage 1 vocals to a clean filename (`Artist - Song (Vocals).flac`)
before passing to Stage 2, avoiding the regex collision.

## Test plan

- [x] Unit tests updated to verify clean filename is used for Stage 2
input
- [x] Full test suite: 1140 passed, 0 failed
- [ ] After deploy: trigger test job and verify backing vocals +
combined instrumental stems appear

<!-- @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-27 14:18:07 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 f58c74e67e fix: ensemble preset stem tag parsing — restore backing vocals separation (#617)
## Summary

- Fix stem filename parsing bug where preset name `instrumental_clean`
caused the Vocals file to be misclassified as instrumental, preventing
Stage 2 (backing vocals separation) from running
- All new GPU-processed jobs were only producing `instrumental_clean` —
no backing vocals, lead vocals, or combined instrumentals
- The instrumental review page showed "No backing vocals detected" for
all jobs

## Root Cause

Ensemble preset output filenames follow
`{base}_(StemTag)_preset_{name}.flac`. The old code did `"instrumental"
in basename` which matched the **preset name** `instrumental_clean` in
the Vocals file, so `result["vocals"]` was never set, and Stage 2 never
ran.

## Fix

Extract the stem tag from between `_(` and `)_` delimiters and match
only that, not the full filename.

## Test plan

- [x] 5 new regression tests for stem tag parsing (both stages)
- [x] 2 pre-existing tests fixed to use realistic ensemble filenames
- [x] Full unit suite: 1140 passed, 0 failed
- [x] CodeRabbit: no findings
- [ ] After deploy: trigger a test job and verify all stems appear on
instrumental review page

<!-- @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-27 12:14:32 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 ccc1b7c714 Fix lyrics upload race condition when artist/title changes mid-processing (#616)
## Summary

- Fix race condition in `upload_lyrics_results` where admin edits to job
artist/title during lyrics worker execution caused filename mismatch and
"No corrections JSON found" errors
- Scan lyrics directory by file suffix pattern instead of reconstructing
filenames from mutable Firestore metadata
- Remove unnecessary `get_job()` call and `sanitize_filename` import
from upload path

## Root Cause

Job `fbec37d6` failed because:
1. Lyrics worker started processing with artist = `zmcmillan08`
2. Admin updated artist to `Quay Money` mid-processing
3. `upload_lyrics_results` read the updated artist from Firestore and
looked for `Quay Money - ... (Lyrics Corrections).json`
4. File on disk was `zmcmillan08 - ... (Lyrics Corrections).json` → not
found → job failed

## Test plan

- [x] Updated 3 existing tests to validate directory-scanning behavior
- [x] Added new test: error path when no corrections file exists at all
- [x] All 68 worker tests pass
- [x] CodeRabbit review: no findings

@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-27 11:14:55 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 056ce3ce2d docs: GPU audio separation learnings and cleanup (#615)
## Summary
- Remove deprecated `AUDIO_SEPARATOR_API_URL` from DEVELOPMENT.md env
vars (no longer used — separation runs directly in Cloud Run Job)
- Add GPU-specific lessons to LESSONS-LEARNED.md:
  - Pin CUDA-specific PyTorch versions in Docker images
  - Ensemble presets require explicit `load_model()` before `separate()`
  - Validate with actual Docker builds, not just package combos

Docs-only, no version bump needed.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 01:32:35 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 dfcd79e5c7 fix: GPU app image — preserve pinned torch cu126 with --no-deps (#614)
## Summary
- Use `--no-deps` in app Dockerfile when building on GPU base image
(detected via `MODEL_DIR` env var)
- Without this, `pip install -e .` upgrades torch from pinned cu126 back
to cu130 (pyproject.toml has `torch>=2.7`) and reinstalls
audio-separator[cpu], breaking both CUDA and GPU ONNX Runtime

This is a follow-up to #613 — the GPU base image had the right packages,
but the app layer's `pip install -e .` undid the pinning.

## Test plan
- [ ] CI passes
- [ ] Deploy, trigger audio separation job
- [ ] Verify Job logs show CUDA available + successful separation

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 23:59:47 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 c4ea0e8fb4 fix: GPU audio separation — pin PyTorch cu126 + missing load_model() (#613)
## Summary
- Pin PyTorch to `cu126` in GPU Dockerfile — Cloud Run L4 GPUs have
driver 570 (CUDA 12.8 max), but `audio-separator[gpu]` pulls PyTorch
`cu130` which fails with "driver too old"
- Add missing `separator.load_model()` before `separator.separate()` for
ensemble presets in `audio_processor.py` — the Separator API requires
this even for presets
- Remove `AUDIO_SEPARATOR_API_URL` from Service env vars (cleanup — Job
has its own `MODEL_DIR`)

## Validation
Tested on GCE L4 GPU VM:
- `torch==2.6.0+cu126` + `audio-separator[gpu]` 0.44.1 → CUDA detected,
GPU acceleration enabled
- Full ensemble separation (`instrumental_clean` preset) completed in
**26.6s** on real audio
- Docker image build validation in progress on separate L4 VM

## Test plan
- [ ] CI passes (GPU image rebuilds due to Dockerfile change)
- [ ] Trigger audio separation job after deploy
- [ ] Verify Cloud Run Job logs show "CUDA is available" and "local GPU"
mode
- [ ] Verify stems are correct

@coderabbitai ignore

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 23:18:32 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 7424398fcf fix: use us-east4 region for audio separation job trigger (#612)
## Summary

The audio-separation-job moved to us-east4 (GPU), but the worker trigger
was still using the default us-central1 region. Added `location`
parameter to `_trigger_worker_cloud_run_job()` and passed `us-east4` for
the audio worker.

Also includes the FFmpeg apt fix from #611.

@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-26 17:36:07 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 41f296f70b fix: use apt FFmpeg in GPU Dockerfile (CI timeout fix) (#611)
## Summary

The johnvansickle.com static FFmpeg download times out in CI (curl exit
code 28). The audio worker only uses FFmpeg for format conversion and
padding, not encoding, so the Ubuntu apt package is sufficient.

Fixes the GPU base image build failure in the deploy-backend workflow.

@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-26 20:56:36 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 177e70efc5 fix: GPU Cloud Run Job infra fixes (zonal redundancy, deletion protection) (#610)
## Summary

Fixes for the GPU audio worker Cloud Run Job that were discovered during
Pulumi apply:

- `deletion_protection=False` — needed so Pulumi can replace the job
when changing regions
- `gpu_zonal_redundancy_disabled=True` — required for Cloud Run Jobs
with GPU (GCP capacity limitation)

Follow-up to #609 (GPU image CI) where the Pulumi apply failed.

@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-26 16:28:17 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 55dd7a30d0 ci: add GPU image build and audio worker deploy to workflow (#609)
## Summary

- Adds GPU base image build to the deploy-backend CI job (same
hash-check pattern as regular base image)
- Builds GPU app image (regular Dockerfile with GPU base as
`BASE_IMAGE`)
- Updates `audio-separation-job` in us-east4 with the GPU image on every
deploy
- Configures Docker auth for the us-east4 Artifact Registry

## Changes

- `.github/workflows/ci.yml` — GPU base image hash check + build, GPU
app image build, audio-separation-job update
- `backend/Dockerfile.gpu-base` — Added `BASE_CONTENT_HASH` label for
hash-based rebuild detection

## How it works

On merge to main, the deploy-backend job now:
1. Builds regular base + app images (unchanged)
2. Hashes `Dockerfile.gpu-base` + `pyproject.toml` → checks if GPU base
needs rebuild
3. If rebuild needed: builds GPU base image (CUDA + PyTorch + models,
~45 min timeout)
4. Builds GPU app image (regular Dockerfile with GPU base)
5. Updates `audio-separation-job` in us-east4 with the new GPU image

The first run will take longer (GPU base image bootstrap). Subsequent
runs skip the GPU base build unless `Dockerfile.gpu-base` or
`pyproject.toml` changes.

## Testing
- [x] YAML syntax verified
- [ ] First CI run will bootstrap the GPU base image (expect ~30-45 min)

@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-26 15:47:07 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 92ae3fb28f feat: run audio separation directly on GPU in audio worker (#608)
## Summary

- **Eliminates HTTP hop** between the audio worker Cloud Run Job and the
audio-separator Cloud Run Service by running the `Separator` class
directly with an L4 GPU attached
- **Adds GPU Docker image** (`karaoke-backend-gpu`) with CUDA 12.6,
PyTorch, and pre-baked ensemble preset models
- **Moves audio worker to us-east4** with L4 GPU, 4 CPU, 16Gi memory —
old separator service kept for rollback

## Changes

### Code
- `audio_processor.py` — Ensemble presets wired into local Separator
path (2-stage: `instrumental_clean` + `karaoke`)
- `audio_worker.py` — Dual-mode support: `MODEL_DIR` env var → local
GPU, `AUDIO_SEPARATOR_API_URL` → remote API
- `create_audio_processor()` — New `model_file_dir` parameter to enable
local GPU mode

### Infrastructure (Pulumi)
- `gpu_artifact_registry.py` — New Artifact Registry in us-east4 for GPU
images
- `cloud_run.py` — Audio worker job: GPU (nvidia-l4), us-east4, 16Gi,
`MODEL_DIR=/models`
- `__main__.py` — Wire in GPU registry + Cloud Build IAM

### Docker
- `Dockerfile.gpu-base` — CUDA 12.6 + Python 3.11 + audio-separator[gpu]
+ baked models
- `cloudbuild-gpu-base.yaml` — Cloud Build config (E2_HIGHCPU_32, 100GB
disk, 1h timeout)
- `download_models.py` — Bakes `instrumental_clean` + `karaoke` preset
models at build time

### Tests
- 8 new unit tests covering factory config, mode selection, and preset
wiring
- Updated existing test patch targets for module-level Separator import

## Testing
- [x] 22/22 unit tests pass (8 new + 14 existing)
- [x] Code review completed (subagent-driven + final review)
- [x] CodeRabbit CLI review completed locally
- [ ] GPU image build (requires `gcloud builds submit`)
- [ ] Production verification with `under_pressure_harmonies.flac`

## Rollback Plan
Set `AUDIO_SEPARATOR_API_URL` back on the audio worker job → falls
through to remote API path. Old separator service is still running
(scale-to-zero).

## Design & Plan
- Design spec:
`docs/archive/2026-03-26-direct-gpu-audio-separation-design.md`
- Implementation plan:
`docs/archive/2026-03-26-direct-gpu-audio-separation-plan.md`

@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-26 15:13:51 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 2cc1061a9d Audio separator infra + docs (concurrency, Firestore, GCS) (#607)
## Summary

- Infrastructure for async audio separator: GCS output bucket, Firestore
index, IAM, env vars
- Set concurrency=1 (each GPU job gets own instance for proper
autoscaling)
- Updated all docs: Modal→Cloud Run GPU references, architecture design
spec, lessons learned
- Phase 2 noted: migrate separator to Cloud Run Jobs

@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-26 17:37:59 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 be19e6c7a0 Infra for async audio separator (concurrency, GCS, Firestore) (#606)
## Summary

- Update audio separator Cloud Run service:
`max_instance_request_concurrency` 1→50, `max_instances` 5→10
- Add `OUTPUT_BUCKET` and `GCP_PROJECT` env vars for the separator
service
- Create `nomadkaraoke-audio-separator-outputs` GCS bucket with 1-day
lifecycle policy
- Grant separator service account `roles/datastore.user` for Firestore
and `roles/storage.objectAdmin` for the output bucket
- Add Firestore composite index on `audio_separation_jobs` (status +
updated_at) for cleanup queries

Companion to nomadkaraoke/python-audio-separator#280. Deploy order: this
PR's infra first (`pulumi up`), then the separator service.

## Test plan

- [ ] `pulumi preview` shows expected resource changes
- [ ] `pulumi up` applies cleanly
- [ ] Verify GCS bucket created with lifecycle policy
- [ ] Verify Firestore index created
- [ ] Verify separator service updated with new concurrency/scaling
settings

@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-26 00:41:45 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 8f8fc269e6 fix: retry returns to lyrics review when not completed (#605)
## Summary
- Fixed retry checkpoint detection skipping lyrics review when user
never completed it
- Previously, retry used `corrections.json` + `title.mov` as proxy for
"review done," but both are auto-generated artifacts that exist BEFORE
user review
- Now requires `instrumental_selection` in state_data (only set via
review submit endpoint) to confirm review was actually completed
- Jobs that failed before review completion now correctly return to
`awaiting_review` on retry

## Root Cause
Job `45f9bbc0` hit this: audio separation kept failing, but corrections
+ title screen existed from the lyrics/screens pipeline. Retry jumped to
`REVIEW_COMPLETE`, skipping review entirely. Admin had to manually
reset.

## Test plan
- [x] Updated existing render checkpoint test to require
`instrumental_selection`
- [x] Added regression test for the skip-review scenario
- [x] All 8 retry endpoint tests pass
- [x] Full backend suite passes (2583 passed)

@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-25 21:58:58 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 ce4bde6a6d fix: update audio-separator to 0.44.1 (multipart fix) (#603)
## Summary
Update audio-separator from 0.44.0 to 0.44.1 to fix 400 Bad Request when
using `gcs_uri`.

v0.44.0 sent `x-www-form-urlencoded` when no file was uploaded (gcs_uri
mode), but FastAPI requires `multipart/form-data`. v0.44.1 fixes this.

@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-25 19:01:25 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 22a500d153 Pre-compute credit evaluation at magic link send time (#602)
## Summary
- Run AI credit evaluation in background thread when sending magic link
(new users only)
- Store result on magic link Firestore doc
- At verify time, use pre-computed result if available, fall back to
inline evaluation if not
- Most users will see instant verification instead of 20s wait

## Test plan
- [x] 53 anti-abuse + credit evaluation tests pass (3 new)
- [x] New test: pre-computed eval skips AI call
- [x] New test: verify passes pre-computed eval from magic link doc
- [x] New test: verify falls back to None when no pre-computed eval
- [ ] Manual test: sign up, verify welcome screen appears quickly

@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-25 22:36:31 +00:00
408 changed files with 131253 additions and 4873 deletions

No files matched your search

+37
View File
@@ -0,0 +1,37 @@
#!/bin/bash
# Auto-translate when English translation files change.
# Uses GCS cache so this is near-instant for small changes.
# Skip with: git commit --no-verify
set -e
STAGED_EN=$(git diff --cached --name-only --diff-filter=ACM | grep -E '(messages|translations)/en\.json$' || true)
if [ -z "$STAGED_EN" ]; then
exit 0
fi
echo "i18n: English translations changed — running translation pipeline..."
for en_file in $STAGED_EN; do
dir=$(dirname "$en_file")
if [[ "$dir" == frontend/messages ]]; then
script="frontend/scripts/translate.py"
elif [[ "$dir" == backend/translations ]]; then
script="frontend/scripts/translate.py"
else
echo " Warning: Unknown messages dir $dir, skipping"
continue
fi
echo " Translating $dir..."
if python "$script" --messages-dir "$dir" --target all --skip-review 2>&1 | tail -5; then
git add "$dir"/*.json
echo " Done: $dir"
else
echo " Warning: Translation failed for $dir (GCP auth may be missing). CI will catch this."
fi
done
echo "i18n: Translation complete."
+210 -24
View File
@@ -90,6 +90,26 @@ jobs:
working-directory: frontend
run: npm run lint
translation-check:
name: "Translation Validation"
runs-on: ubuntu-latest
needs: changes
if: github.ref != 'refs/heads/main' && needs.changes.outputs.frontend == 'true'
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Validate frontend translations (key parity)
run: |
python frontend/scripts/validate-translations.py --messages-dir frontend/messages --keys-only || echo "::warning::Frontend translation validation failed — run translate.py to fix"
- name: Validate backend translations (key parity)
run: python frontend/scripts/validate-translations.py --messages-dir backend/translations --keys-only
frontend-unit-tests:
name: "Frontend - Unit Tests"
runs-on: ubuntu-latest
@@ -694,7 +714,7 @@ jobs:
# frontend-lint IS required - catches React hooks violations that cause runtime crashes
# frontend-e2e-happy-path is required ONLY when 'e2e-happy-path' label is present
# frontend-e2e-full is optional (requires 'e2e' label) so not enforced here
needs: [frontend-lint, frontend-unit-tests, frontend-e2e-smoke, frontend-build, package-unit-tests, package-integration-tests, backend-unit-tests, backend-emulator-tests, backend-lint, frontend-e2e-happy-path]
needs: [frontend-lint, frontend-unit-tests, frontend-e2e-smoke, frontend-build, package-unit-tests, package-integration-tests, backend-unit-tests, backend-emulator-tests, backend-lint, frontend-e2e-happy-path, translation-check]
if: github.ref != 'refs/heads/main' && always()
steps:
- name: Check results
@@ -718,6 +738,14 @@ jobs:
fi
done
# Translation check: warn but don't block (pre-existing placeholder issues)
translation_result="${{ needs.translation-check.result }}"
if [[ "$translation_result" == "failure" ]]; then
echo "⚠️ Translation validation failed — run translate.py to fix"
elif [[ "$translation_result" == "success" ]]; then
echo "✅ Translation validation passed"
fi
# E2E Happy Path: enforced when 'e2e-happy-path' label is on the PR
e2e_result="${{ needs.frontend-e2e-happy-path.result }}"
has_label="${{ contains(github.event.pull_request.labels.*.name, 'e2e-happy-path') }}"
@@ -902,6 +930,22 @@ jobs:
# - / (main app)
# - /app/jobs/{id}/lyrics (lyrics review)
# - /app/jobs/{id}/instrumental (instrumental review)
- name: Capture build metadata
id: frontend-meta
run: |
echo "sha=${GITHUB_SHA::8}" >> $GITHUB_OUTPUT
PR_NUM=$(git log -1 --format=%s | grep -oP '\(#\K[0-9]+' | head -1 || echo "")
if [ -n "$PR_NUM" ]; then
PR_TITLE=$(gh pr view "$PR_NUM" --json title -q .title 2>/dev/null || echo "")
else
PR_NUM=""
PR_TITLE=""
fi
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Install frontend dependencies
working-directory: frontend
run: npm ci --legacy-peer-deps
@@ -911,6 +955,10 @@ jobs:
working-directory: frontend
env:
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
NEXT_PUBLIC_COMMIT_SHA: ${{ steps.frontend-meta.outputs.sha }}
NEXT_PUBLIC_PR_NUMBER: ${{ steps.frontend-meta.outputs.pr_number }}
NEXT_PUBLIC_PR_TITLE: ${{ steps.frontend-meta.outputs.pr_title }}
NEXT_PUBLIC_BUILD_TIME: ${{ github.event.head_commit.timestamp }}
run: npm run build
- name: Deploy consumer to Cloudflare Pages
@@ -929,6 +977,10 @@ jobs:
env:
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
NEXT_PUBLIC_TENANT_PORTAL: "true"
NEXT_PUBLIC_COMMIT_SHA: ${{ steps.frontend-meta.outputs.sha }}
NEXT_PUBLIC_PR_NUMBER: ${{ steps.frontend-meta.outputs.pr_number }}
NEXT_PUBLIC_PR_TITLE: ${{ steps.frontend-meta.outputs.pr_title }}
NEXT_PUBLIC_BUILD_TIME: ${{ github.event.head_commit.timestamp }}
run: npm run build
- name: Deploy tenant portal to Cloudflare Pages
@@ -959,6 +1011,11 @@ jobs:
REPOSITORY: karaoke-repo
BASE_IMAGE_NAME: karaoke-backend-base
APP_IMAGE_NAME: karaoke-backend
# GPU image for audio worker (L4 in us-east4)
GPU_REGISTRY: us-east4-docker.pkg.dev
GPU_REPOSITORY: karaoke-backend-gpu
GPU_BASE_IMAGE_NAME: karaoke-backend-gpu-base
GPU_APP_IMAGE_NAME: karaoke-backend
steps:
- name: Check disk space (aggressive for Docker builds)
run: |
@@ -1003,6 +1060,23 @@ jobs:
echo "📋 Current version: $VERSION"
echo "🚀 Deploying on every push to main"
- name: Capture build metadata
id: build-meta
run: |
echo "sha=${GITHUB_SHA::8}" >> $GITHUB_OUTPUT
# For squash-merge commits, PR number is in the commit message as (#NNN)
PR_NUM=$(git log -1 --format=%s | grep -oP '\(#\K[0-9]+' | head -1 || echo "")
if [ -n "$PR_NUM" ]; then
PR_TITLE=$(gh pr view "$PR_NUM" --json title -q .title 2>/dev/null || echo "")
else
PR_NUM=""
PR_TITLE=""
fi
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Authenticate to Google Cloud (Workload Identity)
id: auth
uses: google-github-actions/auth@v2
@@ -1181,24 +1255,37 @@ jobs:
API_KEY=$(gcloud secrets versions access latest \
--secret=encoding-worker-api-key --project=nomadkaraoke)
DEPLOY_TEST_PATH="gs://karaoke-gen-storage-nomadkaraoke/deploy-test"
echo "Uploading test assets to GCS..."
gsutil cp infrastructure/encoding-worker/test-assets/test-preview.ass \
gs://karaoke-gen-storage-nomadkaraoke/deploy-test/test-preview.ass
"${DEPLOY_TEST_PATH}/test-preview.ass"
gsutil cp infrastructure/encoding-worker/test-assets/test-audio.flac \
"${DEPLOY_TEST_PATH}/test-audio.flac"
echo "Submitting test encode to $SECONDARY_IP..."
RESPONSE=$(curl -sf -X POST "http://${SECONDARY_IP}:8080/encode-preview" \
HTTP_CODE=$(curl -s -o /tmp/encode-response.json -w '%{http_code}' \
-X POST "http://${SECONDARY_IP}:8080/encode-preview" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"job_id": "deploy-health-check",
"ass_gcs_path": "gs://karaoke-gen-storage-nomadkaraoke/deploy-test/test-preview.ass",
"duration_seconds": 10
}')
-d "{
\"job_id\": \"deploy-health-check\",
\"ass_gcs_path\": \"${DEPLOY_TEST_PATH}/test-preview.ass\",
\"audio_gcs_path\": \"${DEPLOY_TEST_PATH}/test-audio.flac\",
\"output_gcs_path\": \"${DEPLOY_TEST_PATH}/output-preview.mp4\"
}") || HTTP_CODE="000"
RESPONSE=$(cat /tmp/encode-response.json 2>/dev/null || echo "{}")
echo "Encode response (HTTP $HTTP_CODE): $RESPONSE"
if [ "$HTTP_CODE" != "200" ] && [ "$HTTP_CODE" != "202" ]; then
echo "::error::Encode request failed with HTTP $HTTP_CODE"
echo "passed=false" >> $GITHUB_OUTPUT
exit 1
fi
echo "Encode response: $RESPONSE"
STATUS=$(echo "$RESPONSE" | jq -r '.status // "unknown"')
if [ "$STATUS" != "accepted" ] && [ "$STATUS" != "completed" ]; then
if [ "$STATUS" != "accepted" ] && [ "$STATUS" != "cached" ] && [ "$STATUS" != "in_progress" ]; then
echo "::error::Encode test failed with status: $STATUS"
echo "passed=false" >> $GITHUB_OUTPUT
exit 1
@@ -1206,11 +1293,11 @@ jobs:
for i in $(seq 1 12); do
sleep 5
JOB_STATUS=$(curl -sf \
JOB_STATUS=$(curl -s \
"http://${SECONDARY_IP}:8080/status/deploy-health-check" \
-H "X-API-Key: $API_KEY" | jq -r '.status // "unknown"')
-H "X-API-Key: $API_KEY" 2>/dev/null | jq -r '.status // "unknown"' 2>/dev/null) || JOB_STATUS="unknown"
echo "Encode status: $JOB_STATUS (attempt $i/12)"
if [ "$JOB_STATUS" = "completed" ]; then
if [ "$JOB_STATUS" = "complete" ]; then
echo "Encode test passed!"
echo "passed=true" >> $GITHUB_OUTPUT
gsutil rm -f gs://karaoke-gen-storage-nomadkaraoke/deploy-test/** || true
@@ -1227,7 +1314,7 @@ jobs:
exit 1
- name: Rollback on failure
if: steps.health.outputs.healthy != 'true' || steps.encode-test.outputs.passed == 'false'
if: steps.health.outputs.healthy != 'true' || steps.encode-test.outputs.passed != 'true'
run: |
SECONDARY_VM="${{ steps.config.outputs.secondary_vm }}"
if [ -n "$SECONDARY_VM" ]; then
@@ -1319,7 +1406,9 @@ jobs:
--zone=us-central1-c --project=nomadkaraoke || true
- name: Configure Docker for Artifact Registry
run: gcloud auth configure-docker ${{ env.REGISTRY }} --quiet
run: |
gcloud auth configure-docker ${{ env.REGISTRY }} --quiet
gcloud auth configure-docker ${{ env.GPU_REGISTRY }} --quiet
# ============================================
# Docker Build with BuildKit + Registry Cache
@@ -1438,6 +1527,88 @@ jobs:
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:cache,mode=max,ignore-error=true
provenance: false
# ============================================
# GPU Image Build (for audio worker with L4 GPU)
# Same pattern as base image: hash check → rebuild if needed
# GPU image lives in us-east4 (co-located with GPU instances)
# ============================================
- name: Calculate GPU base image hash
id: gpu-base-hash
run: |
# Hash Dockerfile.gpu-base + poetry.lock (resolved deps that affect GPU image)
# Using poetry.lock instead of pyproject.toml so that version-only bumps
# (which don't change dependencies) don't trigger expensive GPU base rebuilds
CURRENT_HASH=$(cat backend/Dockerfile.gpu-base poetry.lock | sha256sum | cut -d' ' -f1)
echo "hash=$CURRENT_HASH" >> $GITHUB_OUTPUT
echo "📋 GPU base content hash: $CURRENT_HASH"
- name: Check if GPU base image exists and is current
id: check-gpu-base
run: |
GPU_BASE_IMAGE="${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest"
EXISTING_HASH=""
MANIFEST=$(docker manifest inspect $GPU_BASE_IMAGE 2>/dev/null || echo "")
CONFIG_DIGEST=$(echo "$MANIFEST" | jq -r '.config.digest // ""' 2>/dev/null || echo "")
if [ -n "$CONFIG_DIGEST" ] && [ "$CONFIG_DIGEST" != "null" ] && [ "$CONFIG_DIGEST" != "" ]; then
echo "📋 Found GPU manifest, config digest: $CONFIG_DIGEST"
TOKEN=$(gcloud auth print-access-token)
CONFIG_JSON=$(curl -sL -H "Authorization: Bearer $TOKEN" \
"https://${{ env.GPU_REGISTRY }}/v2/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}/blobs/$CONFIG_DIGEST" 2>/dev/null)
EXISTING_HASH=$(echo "$CONFIG_JSON" | jq -r '.config.Labels["base.content.hash"] // ""' 2>/dev/null || echo "")
echo "📋 Registry GPU base image hash: $EXISTING_HASH"
else
echo "⚠️ No existing GPU base image found in registry - will build"
fi
if [ "${{ steps.gpu-base-hash.outputs.hash }}" != "$EXISTING_HASH" ]; then
echo "🔄 GPU base image needs rebuild (Dockerfile.gpu-base or pyproject.toml changed)"
echo " Current: ${{ steps.gpu-base-hash.outputs.hash }}"
echo " Registry: $EXISTING_HASH"
echo "needs_rebuild=true" >> $GITHUB_OUTPUT
else
echo "✅ GPU base image is up to date"
echo "needs_rebuild=false" >> $GITHUB_OUTPUT
fi
- name: Build and push GPU base image (if needed)
if: steps.check-gpu-base.outputs.needs_rebuild == 'true'
timeout-minutes: 45
uses: docker/build-push-action@v6
with:
context: .
file: backend/Dockerfile.gpu-base
push: true
tags: |
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:${{ github.sha }}
cache-from: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,ignore-error=true
cache-to: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,mode=max,ignore-error=true
build-args: |
BUILD_DATE=${{ github.run_id }}
BUILD_ID=${{ github.sha }}
BASE_CONTENT_HASH=${{ steps.gpu-base-hash.outputs.hash }}
provenance: false
- name: Build and push GPU app image
timeout-minutes: 10
uses: docker/build-push-action@v6
with:
context: .
file: backend/Dockerfile
push: true
tags: |
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:latest
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:${{ github.sha }}
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:v${{ steps.version_check.outputs.version }}
build-args: |
BASE_IMAGE=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
cache-from: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:cache,ignore-error=true
cache-to: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:cache,mode=max,ignore-error=true
provenance: false
# ============================================
# Deploy to Cloud Run
# ============================================
@@ -1456,33 +1627,48 @@ jobs:
--region us-central1 \
--platform managed \
--allow-unauthenticated \
--memory 16Gi \
--cpu 8 \
--memory 2Gi \
--cpu 2 \
--cpu-boost \
--no-cpu-throttling \
--cpu-throttling \
--execution-environment gen2 \
--timeout 1800 \
--concurrency 1 \
--max-instances 50 \
--min-instances 4 \
--concurrency 80 \
--max-instances 20 \
--min-instances 1 \
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
--vpc-egress private-ranges-only \
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,AUDIO_SEPARATOR_API_URL=https://audio-separator-718638054799.us-east4.run.app,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true" \
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,SENDGRID_API_KEY=sendgrid-api-key:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest"
- name: Update Cloud Run Jobs with new image
run: |
IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:${{ github.sha }}"
GPU_IMAGE="${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:${{ github.sha }}"
echo "📦 Updating Cloud Run Jobs to image: $IMAGE"
echo "📦 Updating Cloud Run Jobs..."
# Video encoding job - runs video worker to completion, immune to service deployments
# Video encoding job (CPU, us-central1)
gcloud run jobs update video-encoding-job \
--image "$IMAGE" \
--region us-central1 \
--project ${{ env.PROJECT_ID }} \
--quiet
# Lyrics transcription job (CPU, us-central1)
gcloud run jobs update lyrics-transcription-job \
--image "$IMAGE" \
--region us-central1 \
--project ${{ env.PROJECT_ID }} \
--quiet
# Audio separation job (GPU, us-east4) — uses GPU image
gcloud run jobs update audio-separation-job \
--image "$GPU_IMAGE" \
--region us-east4 \
--project ${{ env.PROJECT_ID }} \
--quiet
echo "✅ Cloud Run Jobs updated"
- name: Verify deployment and version
+337
View File
@@ -0,0 +1,337 @@
name: E2E Daily Test (Payment + Happy Path)
# Full production E2E: buy credits via real Stripe, then use them for karaoke generation.
# Replaces the previous e2e-happy-path.yml with an additional payment stage.
on:
schedule:
- cron: '0 6 * * *'
workflow_dispatch:
inputs:
debug_mode:
description: 'Enable debug mode (slower, more screenshots)'
required: false
default: 'false'
type: boolean
browser:
description: 'Browser to test with'
required: false
default: 'chromium'
type: choice
options:
- chromium
- firefox
- webkit
skip_payment:
description: 'Skip Stage 1 (payment) — use admin-granted credits for happy path only'
required: false
default: 'false'
type: boolean
use_test_token:
description: 'Skip signup entirely — use E2E_TEST_TOKEN (for quick iterations)'
required: false
default: 'false'
type: boolean
permissions:
contents: read
jobs:
# =========================================================================
# Stage 1: Purchase credits via real Stripe Checkout
# =========================================================================
e2e-credit-purchase:
name: "Stage 1: Credit Purchase"
runs-on: ubuntu-latest
timeout-minutes: 15
if: ${{ github.event.inputs.skip_payment != 'true' && github.event.inputs.use_test_token != 'true' }}
outputs:
session_token: ${{ steps.extract_token.outputs.token }}
result: ${{ steps.test_result.outputs.result }}
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: frontend/package-lock.json
- name: Install dependencies
working-directory: frontend
run: npm ci --legacy-peer-deps
- name: Install Playwright browsers
working-directory: frontend
run: npx playwright install --with-deps ${{ inputs.browser || 'chromium' }}
- name: Create test-results directory
working-directory: frontend
run: mkdir -p test-results
- name: Ensure testmail.app domain is allowlisted
run: |
curl -sf -X POST \
"https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
-H "Content-Type: application/json" \
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: allowlist may already exist"
- name: Run Credit Purchase Test
working-directory: frontend
env:
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
E2E_STRIPE_CARD_NUMBER: ${{ secrets.E2E_STRIPE_CARD_NUMBER }}
E2E_STRIPE_CARD_EXPIRY: ${{ secrets.E2E_STRIPE_CARD_EXPIRY }}
E2E_STRIPE_CARD_CVC: ${{ secrets.E2E_STRIPE_CARD_CVC }}
E2E_STRIPE_CARDHOLDER_NAME: ${{ secrets.E2E_STRIPE_CARDHOLDER_NAME }}
DEBUG_MODE: ${{ inputs.debug_mode || 'false' }}
run: |
echo "=== Stage 1: Credit Purchase via Real Stripe ==="
echo "Time: $(date)"
npx playwright test credit-purchase-real.spec.ts \
--config=playwright.production.config.ts \
--project=${{ inputs.browser || 'chromium' }} \
--reporter=list \
--timeout=600000 \
2>&1 | tee test-output-payment.log
continue-on-error: true
- name: Check test result
id: test_result
working-directory: frontend
run: |
if grep -q "CREDIT PURCHASE TEST PASSED" test-output-payment.log; then
echo "result=success" >> $GITHUB_OUTPUT
else
echo "result=failure" >> $GITHUB_OUTPUT
fi
- name: Extract session token
id: extract_token
if: steps.test_result.outputs.result == 'success'
working-directory: frontend
run: |
if [ -f test-results/e2e-session-token.txt ]; then
TOKEN=$(cat test-results/e2e-session-token.txt)
echo "::add-mask::$TOKEN"
echo "token=$TOKEN" >> $GITHUB_OUTPUT
echo "Session token extracted for Stage 2"
else
echo "No session token file found"
echo "token=" >> $GITHUB_OUTPUT
fi
- name: Upload artifacts
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-payment-results-${{ github.run_number }}
path: |
frontend/test-results/
frontend/test-output-payment.log
retention-days: 30
- name: Discord notification (failure)
if: steps.test_result.outputs.result == 'failure'
run: |
curl -s -H "Content-Type: application/json" \
-d "{\"embeds\": [{\"title\": \"🚨 E2E Daily Test FAILED — Stage 1: Credit Purchase\", \"description\": \"Payment flow is broken. Customers may not be receiving credits.\n\n**Run:** #${{ github.run_number }}\n**Details:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\", \"color\": 15158332}]}" \
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}"
- name: Fail if test failed
if: steps.test_result.outputs.result == 'failure'
run: exit 1
# =========================================================================
# Stage 2: Happy Path (uses credit from Stage 1)
# =========================================================================
e2e-happy-path:
name: "Stage 2: Happy Path"
runs-on: ubuntu-latest
timeout-minutes: 90
needs: e2e-credit-purchase
if: |
always() && (
needs.e2e-credit-purchase.result == 'success' ||
github.event.inputs.skip_payment == 'true' ||
github.event.inputs.use_test_token == 'true'
)
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: frontend/package-lock.json
- name: Install dependencies
working-directory: frontend
run: npm ci --legacy-peer-deps
- name: Install Playwright browsers
working-directory: frontend
run: npx playwright install --with-deps ${{ inputs.browser || 'chromium' }}
- name: Create test-results directory
working-directory: frontend
run: mkdir -p test-results
- name: Ensure testmail.app domain is allowlisted
run: |
curl -sf -X POST \
"https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
-H "Content-Type: application/json" \
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: allowlist may already exist"
- name: Refresh E2E session token (when use_test_token enabled)
id: refresh_token
if: github.event.inputs.use_test_token == 'true'
run: |
RESPONSE=$(curl -sf -X POST \
"https://api.nomadkaraoke.com/api/admin/users/e2e-test-runner@nomadkaraoke.com/impersonate" \
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
-H "Content-Type: application/json")
TOKEN=$(echo "$RESPONSE" | python3 -c 'import json,sys; print(json.load(sys.stdin)["session_token"])')
echo "::add-mask::$TOKEN"
echo "token=$TOKEN" >> $GITHUB_OUTPUT
- name: Run Happy Path Test
working-directory: frontend
env:
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token || needs.e2e-credit-purchase.outputs.session_token || '' }}
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
DEBUG_MODE: ${{ inputs.debug_mode || 'false' }}
run: |
echo "=== Stage 2: Happy Path ==="
echo "Time: $(date)"
TOKEN_SOURCE="none"
if [ -n "${{ steps.refresh_token.outputs.token }}" ]; then
TOKEN_SOURCE="use_test_token (impersonation)"
elif [ -n "${{ needs.e2e-credit-purchase.outputs.session_token }}" ]; then
TOKEN_SOURCE="Stage 1 (credit purchase)"
fi
echo "Token source: $TOKEN_SOURCE"
npx playwright test happy-path-real-user.spec.ts \
--config=playwright.production.config.ts \
--project=${{ inputs.browser || 'chromium' }} \
--reporter=list \
--timeout=3600000 \
2>&1 | tee test-output-happy-path.log
continue-on-error: true
- name: Check test result
id: test_result
working-directory: frontend
run: |
if grep -q "passed" test-output-happy-path.log && ! grep -q "failed" test-output-happy-path.log; then
echo "result=success" >> $GITHUB_OUTPUT
else
echo "result=failure" >> $GITHUB_OUTPUT
fi
- name: Upload test artifacts
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-happy-path-results-${{ github.run_number }}
path: |
frontend/test-results/
frontend/playwright-report/
frontend/test-output-happy-path.log
retention-days: 30
- name: Upload video recordings
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-happy-path-videos-${{ github.run_number }}
path: frontend/test-results/**/*.webm
retention-days: 30
if-no-files-found: ignore
- name: Create summary
if: always()
run: |
STAGE1="${{ needs.e2e-credit-purchase.result || 'skipped' }}"
STAGE2="${{ steps.test_result.outputs.result || 'unknown' }}"
echo "## E2E Daily Test Results" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "| Stage | Result |" >> $GITHUB_STEP_SUMMARY
echo "|-------|--------|" >> $GITHUB_STEP_SUMMARY
echo "| Stage 1: Credit Purchase | ${STAGE1} |" >> $GITHUB_STEP_SUMMARY
echo "| Stage 2: Happy Path | ${STAGE2} |" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "| Property | Value |" >> $GITHUB_STEP_SUMMARY
echo "|----------|-------|" >> $GITHUB_STEP_SUMMARY
echo "| Run | #${{ github.run_number }} |" >> $GITHUB_STEP_SUMMARY
echo "| Trigger | ${{ github.event_name }} |" >> $GITHUB_STEP_SUMMARY
echo "| Browser | ${{ inputs.browser || 'chromium' }} |" >> $GITHUB_STEP_SUMMARY
- name: Discord notification (failure)
if: steps.test_result.outputs.result == 'failure'
run: |
curl -s -H "Content-Type: application/json" \
-d "{\"embeds\": [{\"title\": \"🚨 E2E Daily Test FAILED — Stage 2: Happy Path\", \"description\": \"Karaoke generation flow is broken.\n\n**Run:** #${{ github.run_number }}\n**Details:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\", \"color\": 15158332}]}" \
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}"
- name: Fail if test failed
if: steps.test_result.outputs.result == 'failure'
run: exit 1
# =========================================================================
# Final: Send notifications
# =========================================================================
notify:
name: "Notify"
runs-on: ubuntu-latest
needs: [e2e-credit-purchase, e2e-happy-path]
if: always()
steps:
- name: Discord notification (success)
if: needs.e2e-happy-path.result == 'success'
run: |
STAGE1="${{ needs.e2e-credit-purchase.result || 'skipped' }}"
curl -s -H "Content-Type: application/json" \
-d "{\"embeds\": [{\"title\": \"✅ E2E Daily Test PASSED\", \"description\": \"Payment: ${STAGE1} | Happy Path: success\n\n**Run:** #${{ github.run_number }}\", \"color\": 3066993}]}" \
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}"
- name: Send email notification
if: github.event_name == 'schedule'
uses: dawidd6/action-send-mail@v3
with:
server_address: smtp.sendgrid.net
server_port: 587
username: apikey
password: ${{ secrets.SENDGRID_API_KEY }}
subject: "E2E Daily Test ${{ needs.e2e-happy-path.result == 'success' && 'PASSED' || 'FAILED' }} - Run #${{ github.run_number }}"
to: andrew@nomadkaraoke.com
from: "Karaoke Gen CI <noreply@nomadkaraoke.com>"
body: |
E2E Daily Test Results
======================
Stage 1 (Credit Purchase): ${{ needs.e2e-credit-purchase.result || 'skipped' }}
Stage 2 (Happy Path): ${{ needs.e2e-happy-path.result || 'skipped' }}
Run: #${{ github.run_number }}
Trigger: ${{ github.event_name }}
View details: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
-186
View File
@@ -1,186 +0,0 @@
name: E2E Happy Path Test
# Comprehensive end-to-end test that validates the full karaoke generation journey
# using ONLY browser interactions (no API shortcuts)
#
# See docs/E2E-HAPPY-PATH-TEST-SPEC.md for full requirements
on:
# Daily run at 6 AM UTC
schedule:
- cron: '0 6 * * *'
# Manual trigger with optional parameters
workflow_dispatch:
inputs:
debug_mode:
description: 'Enable debug mode (slower, more screenshots)'
required: false
default: 'false'
type: boolean
browser:
description: 'Browser to test with'
required: false
default: 'chromium'
type: choice
options:
- chromium
- firefox
- webkit
use_test_token:
description: 'Skip signup and use E2E_TEST_TOKEN (for iterations)'
required: false
default: 'false'
type: boolean
permissions:
contents: read
jobs:
e2e-happy-path:
name: "Full Happy Path (Real User)"
runs-on: ubuntu-latest
timeout-minutes: 90 # 1.5 hours max (test itself is 60 min)
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: frontend/package-lock.json
- name: Install dependencies
working-directory: frontend
run: npm ci --legacy-peer-deps
- name: Install Playwright browsers
working-directory: frontend
run: |
BROWSER=${{ inputs.browser || 'chromium' }}
npx playwright install --with-deps $BROWSER
- name: Create test-results directory
working-directory: frontend
run: mkdir -p test-results
- name: Refresh E2E session token (when use_test_token enabled)
id: refresh_token
if: inputs.use_test_token == true
run: |
RESPONSE=$(curl -sf -X POST \
"https://api.nomadkaraoke.com/api/admin/users/e2e-test-runner@nomadkaraoke.com/impersonate" \
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
-H "Content-Type: application/json")
TOKEN=$(echo "$RESPONSE" | python3 -c 'import json,sys; print(json.load(sys.stdin)["session_token"])')
echo "::add-mask::$TOKEN"
echo "token=$TOKEN" >> $GITHUB_OUTPUT
- name: Run E2E Happy Path Test
working-directory: frontend
env:
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token || '' }}
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
DEBUG_MODE: ${{ inputs.debug_mode || 'false' }}
run: |
echo "Starting E2E Happy Path Test"
echo "Browser: ${{ inputs.browser || 'chromium' }}"
echo "Debug mode: ${{ inputs.debug_mode || 'false' }}"
echo "Use test token: ${{ inputs.use_test_token || 'false' }}"
echo "Time: $(date)"
echo ""
# Run the real user happy path test
npx playwright test happy-path-real-user.spec.ts \
--config=playwright.production.config.ts \
--project=${{ inputs.browser || 'chromium' }} \
--reporter=list \
--timeout=3600000 \
2>&1 | tee test-output.log
continue-on-error: true
- name: Check test result
id: test_result
working-directory: frontend
run: |
if grep -q "passed" test-output.log && ! grep -q "failed" test-output.log; then
echo "result=success" >> $GITHUB_OUTPUT
echo "Test PASSED"
else
echo "result=failure" >> $GITHUB_OUTPUT
echo "Test FAILED - see artifacts for details"
fi
- name: Upload test artifacts
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-happy-path-results-${{ github.run_number }}
path: |
frontend/test-results/
frontend/playwright-report/
frontend/test-output.log
retention-days: 30
- name: Upload video recordings
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-happy-path-videos-${{ github.run_number }}
path: frontend/test-results/**/*.webm
retention-days: 30
if-no-files-found: ignore
- name: Create summary
if: always()
run: |
echo "## E2E Happy Path Test Results" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "| Property | Value |" >> $GITHUB_STEP_SUMMARY
echo "|----------|-------|" >> $GITHUB_STEP_SUMMARY
echo "| Run | #${{ github.run_number }} |" >> $GITHUB_STEP_SUMMARY
echo "| Trigger | ${{ github.event_name }} |" >> $GITHUB_STEP_SUMMARY
echo "| Browser | ${{ inputs.browser || 'chromium' }} |" >> $GITHUB_STEP_SUMMARY
echo "| Result | ${{ steps.test_result.outputs.result || 'unknown' }} |" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
if [ -f frontend/test-output.log ]; then
echo "### Test Output (last 100 lines)" >> $GITHUB_STEP_SUMMARY
echo "\`\`\`" >> $GITHUB_STEP_SUMMARY
tail -100 frontend/test-output.log >> $GITHUB_STEP_SUMMARY
echo "\`\`\`" >> $GITHUB_STEP_SUMMARY
fi
- name: Send email notification
if: always() && github.event_name == 'schedule'
uses: dawidd6/action-send-mail@v3
with:
server_address: smtp.sendgrid.net
server_port: 587
username: apikey
password: ${{ secrets.SENDGRID_API_KEY }}
subject: "E2E Happy Path Test ${{ steps.test_result.outputs.result == 'success' && 'PASSED' || 'FAILED' }} - Run #${{ github.run_number }}"
to: andrew@nomadkaraoke.com
from: "Karaoke Gen CI <noreply@nomadkaraoke.com>"
body: |
E2E Happy Path Test Results
===========================
Status: ${{ steps.test_result.outputs.result == 'success' && 'PASSED ✅' || 'FAILED ❌' }}
Run: #${{ github.run_number }}
Trigger: ${{ github.event_name }}
Time: ${{ github.event.repository.updated_at }}
View details: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
This is an automated notification from the daily E2E happy path test.
- name: Fail if test failed
if: steps.test_result.outputs.result == 'failure'
run: exit 1
+1
View File
@@ -232,3 +232,4 @@ flacfetch
# Test output directories
Rick Astley*/
.superpowers/
+1
View File
@@ -0,0 +1 @@
[{"name":"generate-buildid","duration":272,"timestamp":244518298649,"id":4,"parentId":1,"tags":{},"startTime":1775262331361,"traceId":"b3ef0d179e8acedf"},{"name":"load-custom-routes","duration":314,"timestamp":244518299029,"id":5,"parentId":1,"tags":{},"startTime":1775262331361,"traceId":"b3ef0d179e8acedf"},{"name":"create-dist-dir","duration":333,"timestamp":244518299363,"id":6,"parentId":1,"tags":{},"startTime":1775262331362,"traceId":"b3ef0d179e8acedf"},{"name":"clean","duration":358,"timestamp":244518300558,"id":7,"parentId":1,"tags":{},"startTime":1775262331363,"traceId":"b3ef0d179e8acedf"},{"name":"next-build","duration":1670851,"timestamp":244516630180,"id":1,"tags":{"buildMode":"default","version":"16.2.2","bundler":"turbopack","failed":true},"startTime":1775262329693,"traceId":"b3ef0d179e8acedf"}]
+1
View File
@@ -0,0 +1 @@
[{"name":"next-build","duration":1670851,"timestamp":244516630180,"id":1,"tags":{"buildMode":"default","version":"16.2.2","bundler":"turbopack","failed":true},"startTime":1775262329693,"traceId":"b3ef0d179e8acedf"}]
+14
View File
@@ -97,6 +97,20 @@ See `docs/TESTING.md` § "Ad-Hoc Production Debugging" for full details.
- `gcloud` CLI for reading/debugging only (e.g., checking logs, SSH to VMs)
- Stop and notify user on auth issues
### Internationalization (i18n)
- All user-facing strings live in `frontend/messages/{locale}.json` (33 locales), NOT in components
- Backend strings live in `backend/translations/{locale}.json` (currently 3 locales: en, es, de)
- Components use `useTranslations('namespace')` from next-intl
- Pages are under `frontend/src/app/[locale]/` — locale-aware routing
- Admin pages (under `/admin/`, `/app/`) use DefaultIntlProvider (English-only, excluded from i18n)
- Internal links use `Link` from `@/i18n/routing` (locale-aware)
- After adding/changing English strings: `python frontend/scripts/translate.py --messages-dir frontend/messages --target all`
- Translation uses Gemini 3.1 Pro via Vertex AI with GCS cache for efficiency
- CI validates all locale files have matching keys — **PR will fail if translations are missing**
- Pre-commit hook auto-translates when en.json changes (enable: `git config core.hooksPath .githooks`)
- Don't hardcode user-facing strings — add to `messages/en.json` and use `t('key')`
## API Authentication (for Agents)
When you need to call backend APIs programmatically:
+2
View File
@@ -29,6 +29,8 @@ tmp/
# Google Cloud
.gcloud/
*.json
# Allow i18n translation files
!translations/*.json
# Testing
.pytest_cache/
+9 -1
View File
@@ -26,7 +26,15 @@ COPY backend /app/backend
# Note: lyrics_transcriber is now a subpackage of karaoke_gen
COPY karaoke_gen /app/karaoke_gen
COPY pyproject.toml README.md LICENSE /app/
RUN pip install --no-cache-dir -e .
# GPU images (MODEL_DIR set in base): use --no-deps to preserve pinned torch cu126
# and audio-separator[gpu]. Without this, pip upgrades torch to cu130 (breaks CUDA
# on Cloud Run L4 drivers) and reinstalls audio-separator[cpu] (breaks GPU ONNX).
# CPU images: normal install resolves all deps from pyproject.toml.
RUN if [ -n "$MODEL_DIR" ]; then \
pip install --no-cache-dir --no-deps -e .; \
else \
pip install --no-cache-dir -e .; \
fi
# Set environment variables
ENV PYTHONUNBUFFERED=1
+1
View File
@@ -23,6 +23,7 @@ RUN apt-get update && apt-get install -y \
build-essential \
curl \
xz-utils \
chromium \
&& rm -rf /var/lib/apt/lists/*
# Install comprehensive font support for international lyrics and symbols
+136
View File
@@ -0,0 +1,136 @@
# GPU base image with CUDA, PyTorch, audio-separator, and pre-downloaded models
# This image is rebuilt only when deps or models change (infrequently).
#
# Build with: gcloud builds submit --config=backend/cloudbuild-gpu-base.yaml --project=nomadkaraoke --timeout=3600s
# Or manually: docker build -f backend/Dockerfile.gpu-base -t karaoke-backend-gpu-base .
#
# Layer caching strategy:
# 1. System deps + fonts + ffmpeg (rarely change, always cached)
# 2. CUDA library path configuration
# 3. pyproject.toml + package stubs (changes with dep updates)
# 4. pip install karaoke-gen deps + audio-separator[gpu] (slow, cached unless pyproject.toml changes)
# 5. Source code copy (changes every rebuild, but AFTER deps are installed)
# 6. spaCy model download (cached unless pip install layer changes)
# 7. Pre-downloaded ensemble preset models (~1-1.5 GB, cached unless pip layer changes)
FROM nvidia/cuda:12.6.3-runtime-ubuntu22.04
# Prevent interactive prompts during package installation
ENV DEBIAN_FRONTEND=noninteractive
# Install Python 3.11 from deadsnakes PPA and system dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
software-properties-common \
&& add-apt-repository -y ppa:deadsnakes/ppa \
&& apt-get update && apt-get install -y --no-install-recommends \
# Python 3.11
python3.11 \
python3.11-dev \
python3.11-venv \
# Audio libraries
libsndfile1 \
libsox-dev \
sox \
# Build tools
build-essential \
# Utilities
curl \
xz-utils \
&& rm -rf /var/lib/apt/lists/* \
&& python3.11 --version
# Install comprehensive font support for international lyrics and symbols
# Noto fonts provide full Unicode coverage including:
# - Latin, Greek, Cyrillic (core)
# - CJK: Chinese, Japanese, Korean (~150MB)
# - Arabic, Hebrew, Thai, Hindi, and other scripts (extra)
# - Color emoji (limited support in libass, but available)
# - Musical symbols (♪ ♫ etc.)
# Note: This adds ~200-300MB to the image but ensures all languages render correctly
RUN apt-get update && apt-get install -y --no-install-recommends \
fonts-noto-core \
fonts-noto-cjk \
fonts-noto-extra \
fonts-noto-color-emoji \
fontconfig \
&& fc-cache -f \
&& rm -rf /var/lib/apt/lists/*
# Install FFmpeg from Ubuntu package
# The audio worker only uses FFmpeg for format conversion and padding, not
# encoding-intensive tasks, so the Debian package is sufficient. The static
# build from johnvansickle.com is used for the encoding worker instead.
RUN apt-get update && apt-get install -y ffmpeg && rm -rf /var/lib/apt/lists/*
# Set Python 3.11 as default and install pip
RUN update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.11 1 \
&& update-alternatives --install /usr/bin/python python /usr/bin/python3.11 1 \
&& curl -sS https://bootstrap.pypa.io/get-pip.py | python3.11 \
&& python3 -m pip install --no-cache-dir --upgrade pip setuptools wheel
# Set up CUDA library paths so GPU-accelerated packages can find CUDA libs at runtime
RUN echo '/usr/local/cuda/lib64' >> /etc/ld.so.conf.d/cuda.conf && ldconfig
# Environment configuration for CUDA and Python
ENV LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH \
PATH=/usr/local/cuda/bin:$PATH \
PYTHONUNBUFFERED=1 \
MODEL_DIR=/models
# Set working directory
WORKDIR /app
# Copy ONLY dependency specification files first (changes less often than source code)
COPY pyproject.toml README.md LICENSE /app/
# Create minimal package stubs so pip can resolve the editable install
# pip install -e . needs package directories to exist but doesn't validate content
RUN mkdir -p /app/karaoke_gen /app/lyrics_transcriber_temp /app/backend && \
touch /app/karaoke_gen/__init__.py /app/lyrics_transcriber_temp/__init__.py /app/backend/__init__.py
# Install all karaoke-gen Python dependencies (the slow part)
# BuildKit cache mount preserves downloaded wheels across builds
RUN --mount=type=cache,target=/root/.cache/pip \
pip install --upgrade pip && \
pip install -e .
# Install audio-separator with GPU support (PyTorch + CUDA + onnxruntime-gpu)
# This is separate from pip install -e . to keep layer caching granular
#
# IMPORTANT: Install PyTorch cu126 FIRST, then audio-separator[gpu].
# The default audio-separator[gpu] pulls PyTorch cu130, but Cloud Run L4 GPUs
# have NVIDIA driver 570 which only supports up to CUDA 12.8. PyTorch cu130
# fails with "NVIDIA driver is too old". PyTorch cu126 works with 12.8 drivers.
# Installing torch first means audio-separator[gpu] sees it as already satisfied.
RUN --mount=type=cache,target=/root/.cache/pip \
pip install torch==2.6.0+cu126 torchvision==0.21.0+cu126 --index-url https://download.pytorch.org/whl/cu126 && \
pip install "audio-separator[gpu]"
# Now copy actual source code (AFTER deps installed, so code changes don't
# invalidate the expensive pip install layer in registry cache)
COPY karaoke_gen /app/karaoke_gen
COPY lyrics_transcriber_temp /app/lyrics_transcriber_temp
COPY backend /app/backend
# Download spaCy language model for lyrics transcription
# Must be done at build time, not runtime (Cloud Run network restrictions)
RUN python -m spacy download en_core_web_sm
# Create models directory and pre-download ensemble preset models
# Baking models into the image eliminates cold-start model download latency.
# Total model size: ~1-1.5 GB for instrumental_clean + karaoke presets.
RUN mkdir -p /models
COPY backend/scripts/download_models.py /tmp/download_models.py
RUN python /tmp/download_models.py /models && \
rm /tmp/download_models.py && \
ls -lh /models/
# Label with build info
ARG BUILD_DATE
ARG BUILD_ID
ARG BASE_CONTENT_HASH
LABEL org.opencontainers.image.created="${BUILD_DATE}"
LABEL org.opencontainers.image.revision="${BUILD_ID}"
LABEL org.opencontainers.image.title="karaoke-backend-gpu-base"
LABEL org.opencontainers.image.description="GPU base image with CUDA, PyTorch, audio-separator, and pre-downloaded models for karaoke-backend audio worker"
LABEL base.content.hash="${BASE_CONTENT_HASH}"
+2 -1
View File
@@ -11,10 +11,11 @@ import logging
from datetime import datetime, timedelta, timezone
from typing import Tuple, List, Optional, Any, Dict
from fastapi import APIRouter, Depends, HTTPException
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel
from backend.api.dependencies import require_admin
from backend.i18n import t, get_locale_from_request
from backend.services.auth_service import UserType, AuthResult
from backend.services.user_service import get_user_service, UserService, USERS_COLLECTION
from backend.services.job_manager import JobManager
+15 -10
View File
@@ -53,6 +53,7 @@ from backend.exceptions import InsufficientCreditsError
from backend.services.tracing import add_span_attribute
from backend.services.firestore_service import FirestoreService
from pathlib import Path
from backend.i18n import t, get_locale_from_request
logger = logging.getLogger(__name__)
@@ -309,17 +310,17 @@ def _validate_and_prepare_selection(
"""
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
raise HTTPException(status_code=404, detail=t("en", "audioSearch.jobNotFound", job_id=job_id))
# Get search results from state_data
search_results = job.state_data.get('audio_search_results', [])
if not search_results:
raise HTTPException(status_code=400, detail="No search results available")
raise HTTPException(status_code=400, detail=t("en", "audioSearch.noSearchResults"))
if selection_index < 0 or selection_index >= len(search_results):
raise HTTPException(
status_code=400,
detail=f"Invalid selection index {selection_index}. Valid range: 0-{len(search_results)-1}"
detail=t("en", "audioSearch.invalidSelectionIndex", selection_index=selection_index, max=len(search_results)-1)
)
selected = search_results[selection_index]
@@ -594,12 +595,14 @@ async def search_audio(
- Interactive mode (default): Returns results, user calls /select endpoint
- Auto mode (auto_download=True): Automatically selects and downloads best
"""
locale = get_locale_from_request(request)
# Check tenant feature flag
tenant_config = get_tenant_config_from_request(request)
if tenant_config and not tenant_config.features.audio_search:
raise HTTPException(
status_code=403,
detail="Audio search is not available for this portal"
detail=t(locale, "audioSearch.notEnabled")
)
try:
@@ -966,12 +969,14 @@ async def search_audio_standalone(
Credits are checked here (early feedback) but NOT deducted — deduction
happens when the job is created via create-from-search.
"""
locale = get_locale_from_request(request)
# Check tenant feature flag
tenant_config = get_tenant_config_from_request(request)
if tenant_config and not tenant_config.features.audio_search:
raise HTTPException(
status_code=403,
detail="Audio search is not available for this portal"
detail=t(locale, "audioSearch.notEnabled")
)
try:
@@ -1098,14 +1103,14 @@ async def get_audio_search_results(
"""
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
raise HTTPException(status_code=404, detail=t("en", "audioSearch.jobNotFound", job_id=job_id))
search_results = job.state_data.get('audio_search_results', [])
if not search_results:
raise HTTPException(
status_code=400,
detail="No search results available for this job"
detail=t("en", "audioSearch.noSearchResults")
)
return {
@@ -1136,7 +1141,7 @@ async def select_audio_source(
"""
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
raise HTTPException(status_code=404, detail=t("en", "audioSearch.jobNotFound", job_id=job_id))
# Verify job is awaiting selection
if job.status != JobStatus.AWAITING_AUDIO_SELECTION:
+41 -35
View File
@@ -9,7 +9,7 @@ Provides endpoints for:
import logging
from typing import Optional
from datetime import datetime
from fastapi import APIRouter, HTTPException, BackgroundTasks
from fastapi import APIRouter, HTTPException, BackgroundTasks, Request
from pydantic import BaseModel
from backend.services.credential_manager import (
@@ -18,6 +18,7 @@ from backend.services.credential_manager import (
CredentialCheckResult,
)
from backend.config import get_settings
from backend.i18n import t, get_locale_from_request
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/auth", tags=["auth"])
@@ -125,15 +126,16 @@ async def get_credentials_status():
@router.get("/status/{service}", response_model=CredentialStatusResponse)
async def get_service_credential_status(service: str):
async def get_service_credential_status(service: str, request: Request):
"""
Get the status of a specific service's OAuth credentials.
Args:
service: One of "youtube", "gdrive", "dropbox"
"""
locale = get_locale_from_request(request)
manager = get_credential_manager()
if service == "youtube":
result = manager.check_youtube_credentials()
elif service == "gdrive":
@@ -141,7 +143,7 @@ async def get_service_credential_status(service: str):
elif service == "dropbox":
result = manager.check_dropbox_credentials()
else:
raise HTTPException(status_code=400, detail=f"Unknown service: {service}")
raise HTTPException(status_code=400, detail=t(locale, "auth.unknownService", service=service))
return CredentialStatusResponse(
service=result.service,
@@ -153,42 +155,43 @@ async def get_service_credential_status(service: str):
@router.post("/validate", response_model=CredentialValidationResponse)
async def validate_credentials(request: CredentialValidationRequest):
async def validate_credentials(request: CredentialValidationRequest, http_request: Request):
"""
Validate that credentials are available for requested services.
Use this before submitting a job to ensure all required
credentials are valid.
"""
locale = get_locale_from_request(http_request)
manager = get_credential_manager()
invalid_services = []
if request.youtube:
result = manager.check_youtube_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append("youtube")
if request.gdrive:
result = manager.check_gdrive_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append("gdrive")
if request.dropbox:
result = manager.check_dropbox_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append("dropbox")
if invalid_services:
return CredentialValidationResponse(
valid=False,
invalid_services=invalid_services,
message=f"The following services need re-authorization: {', '.join(invalid_services)}"
message=t(locale, "auth.invalidCredentials", services=", ".join(invalid_services))
)
return CredentialValidationResponse(
valid=True,
invalid_services=[],
message="All requested credentials are valid"
message=t(locale, "auth.validCredentials")
)
@@ -197,40 +200,41 @@ async def validate_credentials(request: CredentialValidationRequest):
# ===========================================================================
@router.post("/youtube/device", response_model=DeviceAuthStartResponse)
async def start_youtube_device_auth(request: Optional[DeviceAuthStartRequest] = None):
async def start_youtube_device_auth(request: Optional[DeviceAuthStartRequest] = None, http_request: Request = None):
"""
Start YouTube device authorization flow.
This initiates a device auth flow that allows authorization
from any device. The user must visit the verification URL
and enter the user code.
Client credentials are loaded from Secret Manager ('youtube-client-credentials')
unless explicitly provided in the request body.
After starting, poll /auth/youtube/device/{device_code} to
check for completion.
"""
locale = get_locale_from_request(http_request) if http_request else "en"
manager = get_credential_manager()
try:
device_info = manager.start_youtube_device_auth(
client_id=request.client_id if request else None,
client_secret=request.client_secret if request else None
)
return DeviceAuthStartResponse(
device_code=device_info.device_code,
user_code=device_info.user_code,
verification_url=device_info.verification_url,
expires_in=device_info.expires_in,
interval=device_info.interval,
instructions=f"Visit {device_info.verification_url} and enter code: {device_info.user_code}"
instructions=t(locale, "auth.youtubeAuthInstructions", verification_url=device_info.verification_url, user_code=device_info.user_code)
)
except Exception as e:
logger.error(f"Failed to start YouTube device auth: {e}")
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail=t(locale, "auth.youtubeAuthStartFailed", error=str(e)))
@router.get("/youtube/device/{device_code}", response_model=DeviceAuthPollResponse)
@@ -259,35 +263,36 @@ async def poll_youtube_device_auth(device_code: str):
@router.post("/gdrive/device", response_model=DeviceAuthStartResponse)
async def start_gdrive_device_auth(request: Optional[DeviceAuthStartRequest] = None):
async def start_gdrive_device_auth(request: Optional[DeviceAuthStartRequest] = None, http_request: Request = None):
"""
Start Google Drive device authorization flow.
Client credentials are loaded from Secret Manager ('gdrive-client-credentials')
unless explicitly provided in the request body.
After starting, poll /auth/gdrive/device/{device_code} to check for completion.
"""
locale = get_locale_from_request(http_request) if http_request else "en"
manager = get_credential_manager()
try:
device_info = manager.start_gdrive_device_auth(
client_id=request.client_id if request else None,
client_secret=request.client_secret if request else None
)
return DeviceAuthStartResponse(
device_code=device_info.device_code,
user_code=device_info.user_code,
verification_url=device_info.verification_url,
expires_in=device_info.expires_in,
interval=device_info.interval,
instructions=f"Visit {device_info.verification_url} and enter code: {device_info.user_code}"
instructions=t(locale, "auth.gdriveLinkInstructions", verification_url=device_info.verification_url, user_code=device_info.user_code)
)
except Exception as e:
logger.error(f"Failed to start Google Drive device auth: {e}")
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail=t(locale, "auth.gdriveAuthStartFailed", error=str(e)))
@router.get("/gdrive/device/{device_code}", response_model=DeviceAuthPollResponse)
@@ -311,19 +316,20 @@ async def poll_gdrive_device_auth(device_code: str):
# ===========================================================================
@router.post("/test-alert")
async def test_credential_alert(background_tasks: BackgroundTasks):
async def test_credential_alert(background_tasks: BackgroundTasks, request: Request):
"""
Test the credential alert mechanism.
Sends a test alert to Discord if configured.
"""
locale = get_locale_from_request(request)
settings = get_settings()
discord_url = settings.get_secret("discord-alert-webhook")
if not discord_url:
raise HTTPException(
status_code=400,
detail="Discord alert webhook not configured"
detail=t(locale, "auth.discordAlertNotConfigured")
)
manager = get_credential_manager()
+13 -6
View File
@@ -14,6 +14,7 @@ from pydantic import BaseModel, Field
from backend.api.dependencies import require_auth
from backend.services.auth_service import AuthResult
from backend.i18n import t, get_locale_from_request
logger = logging.getLogger(__name__)
@@ -26,7 +27,7 @@ RATE_LIMIT_MAX_REQUESTS = 20
RATE_LIMIT_WINDOW_SECONDS = 60
def _check_rate_limit(user_email: str) -> None:
def _check_rate_limit(user_email: str, locale: str = "en") -> None:
"""Check per-user rate limit. Raises 429 if exceeded."""
now = time.monotonic()
window_start = now - RATE_LIMIT_WINDOW_SECONDS
@@ -37,12 +38,12 @@ def _check_rate_limit(user_email: str) -> None:
# Remove expired entries
timestamps = _rate_limit_windows[user_email]
_rate_limit_windows[user_email] = [t for t in timestamps if t > window_start]
_rate_limit_windows[user_email] = [ts for ts in timestamps if ts > window_start]
if len(_rate_limit_windows[user_email]) >= RATE_LIMIT_MAX_REQUESTS:
raise HTTPException(
status_code=429,
detail=f"Rate limit exceeded. Maximum {RATE_LIMIT_MAX_REQUESTS} catalog requests per minute.",
detail=t(locale, "catalog.rateLimitExceeded", max_requests=RATE_LIMIT_MAX_REQUESTS),
)
_rate_limit_windows[user_email].append(now)
@@ -107,6 +108,7 @@ class CommunityCheckResponse(BaseModel):
@router.get("/artists", response_model=list[ArtistResult])
async def search_artists(
request: Request,
q: str = Query(..., min_length=2, description="Artist name search query"),
limit: int = Query(10, ge=1, le=50, description="Maximum results"),
auth_result: AuthResult = Depends(require_auth),
@@ -115,7 +117,8 @@ async def search_artists(
Search for artists by name. Returns canonical MusicBrainz/Spotify artist data
for autocomplete in job creation forms.
"""
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown")
locale = get_locale_from_request(request)
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale)
from backend.services.catalog_proxy_service import search_artists
results = await search_artists(q, limit)
@@ -124,6 +127,7 @@ async def search_artists(
@router.get("/tracks", response_model=list[TrackResult])
async def search_tracks(
request: Request,
q: str = Query(..., min_length=2, description="Track name search query"),
artist: Optional[str] = Query(None, description="Filter by artist name"),
limit: int = Query(10, ge=1, le=50, description="Maximum results"),
@@ -133,7 +137,8 @@ async def search_tracks(
Search for tracks by name, optionally filtered by artist.
Returns canonical Spotify track data for autocomplete in job creation forms.
"""
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown")
locale = get_locale_from_request(request)
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale)
from backend.services.catalog_proxy_service import search_tracks
results = await search_tracks(q, artist, limit)
@@ -142,6 +147,7 @@ async def search_tracks(
@router.post("/community-check", response_model=CommunityCheckResponse)
async def check_community_versions(
request: Request,
body: CommunityCheckRequest,
auth_result: AuthResult = Depends(require_auth),
):
@@ -149,7 +155,8 @@ async def check_community_versions(
Check if a song already has community-approved karaoke versions on YouTube
via karaokenerds.com. Non-blocking — just informs the user.
"""
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown")
locale = get_locale_from_request(request)
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale)
from backend.services.karaokenerds_service import check_community_versions
result = await check_community_versions(body.artist, body.title)
+35 -22
View File
@@ -45,6 +45,7 @@ from backend.services.youtube_download_service import (
get_youtube_download_service,
YouTubeDownloadError,
)
from backend.i18n import t, get_locale_from_request
logger = logging.getLogger(__name__)
@@ -350,7 +351,8 @@ async def _trigger_audio_worker_only(job_id: str) -> None:
def _prepare_theme_for_job(
job_id: str,
theme_id: str,
color_overrides: Optional[Dict[str, str]] = None
color_overrides: Optional[Dict[str, str]] = None,
locale: str = "en"
) -> Tuple[str, Dict[str, str], Optional[str]]:
"""
Prepare theme style files for a job.
@@ -359,6 +361,7 @@ def _prepare_theme_for_job(
job_id: The job ID
theme_id: Theme identifier
color_overrides: Optional color override dict
locale: Locale for error messages
Returns:
Tuple of (style_params_gcs_path, style_assets, youtube_description)
@@ -372,7 +375,7 @@ def _prepare_theme_for_job(
if not theme_service.theme_exists(theme_id):
raise HTTPException(
status_code=400,
detail=f"Theme not found: {theme_id}. Use GET /api/themes to list available themes."
detail=t(locale, "fileUpload.invalidTheme", theme_id=theme_id)
)
# Convert dict to ColorOverrides model if provided
@@ -465,6 +468,8 @@ async def upload_and_create_job(
The style_params JSON can reference the uploaded images/fonts by their original
filenames, and the backend will update the paths to GCS locations.
"""
locale = get_locale_from_request(request)
# Check tenant feature flag
tenant_config = get_tenant_config_from_request(request)
if tenant_config and not tenant_config.features.file_upload:
@@ -699,7 +704,7 @@ async def upload_and_create_job(
if effective_theme_id and not has_custom_style_files:
try:
theme_style_params_path, theme_style_assets, theme_youtube_desc = _prepare_theme_for_job(
job_id, effective_theme_id, parsed_color_overrides or None
job_id, effective_theme_id, parsed_color_overrides or None, locale=locale
)
logger.info(f"Applied theme '{effective_theme_id}' to job {job_id}")
except HTTPException:
@@ -896,7 +901,7 @@ async def upload_and_create_job(
return {
"status": "success",
"job_id": job_id,
"message": "Files uploaded successfully. Processing started.",
"message": t(locale, "fileUpload.uploadSuccess"),
"filename": file.filename,
"style_assets_uploaded": list(style_assets.keys()) if style_assets else [],
"server_version": VERSION,
@@ -909,7 +914,7 @@ async def upload_and_create_job(
raise
except Exception as e:
logger.error(f"Error uploading files: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e)) from e
raise HTTPException(status_code=500, detail=t(locale, "fileUpload.uploadError", error=str(e))) from e
# ============================================================================
@@ -1110,6 +1115,8 @@ async def create_job_with_upload_urls(
- Works with any HTTP client (no HTTP/2 required)
- Resumable uploads possible with GCS
"""
locale = get_locale_from_request(request)
# Check tenant feature flag
tenant_config = get_tenant_config_from_request(request)
if tenant_config and not tenant_config.features.file_upload:
@@ -1121,14 +1128,14 @@ async def create_job_with_upload_urls(
try:
# Validate files list
if not body.files:
raise HTTPException(status_code=400, detail="At least one file is required")
raise HTTPException(status_code=400, detail=t(locale, "fileUpload.noAudioFileProvided"))
# Check that audio file is included
audio_files = [f for f in body.files if f.file_type == 'audio']
if not audio_files:
raise HTTPException(status_code=400, detail="An audio file is required")
raise HTTPException(status_code=400, detail=t(locale, "fileUpload.noAudioFileProvided"))
if len(audio_files) > 1:
raise HTTPException(status_code=400, detail="Only one audio file is allowed")
raise HTTPException(status_code=400, detail=t(locale, "fileUpload.multipleAudioFilesNotAllowed"))
# Validate file types and extensions
for file_info in body.files:
@@ -1271,7 +1278,7 @@ async def create_job_with_upload_urls(
# If theme is set and no style_params uploaded, prepare theme style now
if effective_theme_id and not has_style_params_upload:
style_params_path, style_assets, youtube_desc = _prepare_theme_for_job(
job_id, effective_theme_id, body.color_overrides
job_id, effective_theme_id, body.color_overrides, locale=locale
)
# Update job with theme style data
update_data = {
@@ -1307,7 +1314,7 @@ async def create_job_with_upload_urls(
return CreateJobWithUploadUrlsResponse(
status="success",
job_id=job_id,
message="Job created. Upload files to the provided URLs, then call /api/jobs/{job_id}/uploads-complete",
message=t(locale, "fileUpload.urlCreationSuccess"),
upload_urls=upload_urls,
server_version=VERSION
)
@@ -1318,12 +1325,13 @@ async def create_job_with_upload_urls(
raise
except Exception as e:
logger.error(f"Error creating job with upload URLs: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e)) from e
raise HTTPException(status_code=500, detail=t(locale, "fileUpload.urlCreationError", error=str(e))) from e
@router.post("/jobs/{job_id}/uploads-complete")
async def mark_uploads_complete(
job_id: str,
request: Request,
background_tasks: BackgroundTasks,
body: UploadsCompleteRequest,
auth_result: AuthResult = Depends(require_auth)
@@ -1342,22 +1350,23 @@ async def mark_uploads_complete(
- Update job with GCS paths
- Trigger audio and lyrics workers
"""
locale = get_locale_from_request(request)
try:
# Get job and verify it exists
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Verify job is in pending state
if job.status != JobStatus.PENDING:
raise HTTPException(
status_code=400,
detail=f"Job {job_id} is not in pending state (current: {job.status}). Cannot complete uploads."
detail=t(locale, "jobs.notCompleted", status=job.status)
)
# Validate required files
if 'audio' not in body.uploaded_files:
raise HTTPException(status_code=400, detail="Audio file upload is required")
raise HTTPException(status_code=400, detail=t(locale, "fileUpload.noAudioFileProvided"))
# Build GCS paths for uploaded files and validate they exist
update_data = {}
@@ -1495,7 +1504,7 @@ async def mark_uploads_complete(
return {
"status": "success",
"job_id": job_id,
"message": "Uploads validated. Processing started.",
"message": t(locale, "fileUpload.uploadsCompleteSuccess"),
"files_validated": body.uploaded_files,
"style_assets": list(style_assets.keys()) if style_assets else [],
"server_version": VERSION,
@@ -1506,7 +1515,7 @@ async def mark_uploads_complete(
raise
except Exception as e:
logger.error(f"Error completing uploads for job {job_id}: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e)) from e
raise HTTPException(status_code=500, detail=t(locale, "fileUpload.uploadsCompleteError", error=str(e))) from e
# ============================================================================
@@ -1589,6 +1598,8 @@ async def create_job_from_url(
Note: YouTube rate limiting may cause occasional download failures.
The backend will retry automatically.
"""
locale = get_locale_from_request(request)
# Check tenant feature flag
tenant_config = get_tenant_config_from_request(request)
if tenant_config and not tenant_config.features.youtube_url:
@@ -1744,7 +1755,7 @@ async def create_job_from_url(
# If theme is set, prepare theme style now
if effective_theme_id:
style_params_path, style_assets, youtube_desc = _prepare_theme_for_job(
job_id, effective_theme_id, body.color_overrides
job_id, effective_theme_id, body.color_overrides, locale=locale
)
# Update job with theme style data
update_data = {
@@ -1803,7 +1814,7 @@ async def create_job_from_url(
job_manager.fail_job(job_id, f"YouTube download failed: {e}")
raise HTTPException(
status_code=500,
detail=f"YouTube download failed: {e}"
detail=t(locale, "audioSearch.youtubeDownloadError", error=str(e))
)
else:
# For non-YouTube URLs, transition to DOWNLOADING and trigger audio worker
@@ -1897,6 +1908,8 @@ async def create_finalise_only_job(
The endpoint returns signed URLs for uploading all the prep files.
"""
locale = get_locale_from_request(request)
# Check tenant feature flag - finalise-only requires file upload capability
tenant_config = get_tenant_config_from_request(request)
if tenant_config and not tenant_config.features.file_upload:
@@ -2057,7 +2070,7 @@ async def create_finalise_only_job(
# If theme is set and no style_params uploaded, prepare theme style now
if effective_theme_id and not has_style_params_upload:
style_params_path, style_assets, youtube_desc = _prepare_theme_for_job(
job_id, effective_theme_id, body.color_overrides
job_id, effective_theme_id, body.color_overrides, locale=locale
)
# Update job with theme style data
update_data = {
+141 -3
View File
@@ -5,10 +5,12 @@ import os
import logging
import subprocess
import platform
from fastapi import APIRouter
from typing import Dict, Any, Optional
from fastapi import APIRouter, Depends
from typing import Dict, Any, Optional, Tuple
from backend.version import VERSION
from backend.version import VERSION, COMMIT_SHA, PR_NUMBER, PR_TITLE, STARTUP_TIME
from backend.api.dependencies import optional_auth
from backend.services.auth_service import UserType
from backend.services.flacfetch_client import get_flacfetch_client
from backend.services.email_service import get_email_service
from backend.services.stripe_service import get_stripe_service
@@ -308,6 +310,30 @@ async def flacfetch_health() -> Dict[str, Any]:
}
def check_audio_separator_status() -> Dict[str, Any]:
"""Check audio separator availability without calling the remote GPU service."""
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/audio-separator")
async def audio_separator_health() -> Dict[str, Any]:
"""
@@ -341,6 +367,118 @@ async def audio_separator_health() -> Dict[str, Any]:
}
def _get_encoding_worker_manager():
"""Get the EncodingWorkerManager instance. Separated for testability."""
try:
encoding_service = get_encoding_service()
if hasattr(encoding_service, '_worker_manager') and encoding_service._worker_manager:
return encoding_service._worker_manager
except Exception:
pass
return None
@router.get("/health/system-status")
async def system_status(
auth: Optional[Tuple] = Depends(optional_auth),
) -> Dict[str, Any]:
"""
Aggregated system status for all services.
Returns basic info for everyone. Admin users get additional
blue-green deployment details for the encoder.
"""
is_admin = auth is not None and len(auth) >= 2 and auth[1] == UserType.ADMIN
# Fetch all health statuses concurrently
import asyncio
encoding_task = check_encoding_worker_status()
flacfetch_task = check_flacfetch_service_status()
encoding_status, flacfetch_status = await asyncio.gather(
encoding_task, flacfetch_task
)
separator_status = check_audio_separator_status()
# Build frontend service info (from env vars baked at build time — returned as-is)
frontend_svc = {
"status": "ok",
"version": VERSION, # Frontend and backend share the same version from pyproject.toml
}
# Build backend service info
backend_svc = {
"status": "ok",
"version": VERSION,
"deployed_at": STARTUP_TIME,
}
if COMMIT_SHA:
backend_svc["commit_sha"] = COMMIT_SHA
if PR_NUMBER:
backend_svc["pr_number"] = PR_NUMBER
if PR_TITLE:
backend_svc["pr_title"] = PR_TITLE
# Build encoder service info
encoder_svc = {
"status": "ok" if encoding_status.get("available") else "offline",
"version": encoding_status.get("wheel_version"),
"active_jobs": encoding_status.get("active_jobs", 0),
}
# Build flacfetch service info
flacfetch_svc = {
"status": "ok" if flacfetch_status.get("available") else "offline",
"version": flacfetch_status.get("version"),
}
# Build separator service info
separator_svc = {
"status": "ok" if separator_status.get("available") else "offline",
"version": separator_status.get("version"),
}
# Admin-only: blue-green encoder details from Firestore
if is_admin:
manager = _get_encoding_worker_manager()
if manager:
try:
config = manager.get_config()
encoder_svc["admin_details"] = {
"primary_vm": config.primary_vm,
"primary_ip": config.primary_ip,
"primary_version": config.primary_version,
"primary_deployed_at": config.primary_deployed_at,
"secondary_vm": config.secondary_vm,
"secondary_ip": config.secondary_ip,
"secondary_version": config.secondary_version,
"secondary_deployed_at": config.secondary_deployed_at,
"last_swap_at": config.last_swap_at,
"deploy_in_progress": config.deploy_in_progress,
"active_jobs": encoding_status.get("active_jobs", 0),
"queue_length": encoding_status.get("queue_length", 0),
}
except Exception as e:
logger.warning(f"Failed to get blue-green config: {e}")
# Add error details for offline services
if not flacfetch_status.get("available"):
flacfetch_svc["admin_details"] = {"error": flacfetch_status.get("error")}
if not separator_status.get("available"):
separator_svc["admin_details"] = {"error": separator_status.get("error")}
if not encoding_status.get("available") and "admin_details" not in encoder_svc:
encoder_svc["admin_details"] = {"error": encoding_status.get("error")}
return {
"services": {
"frontend": frontend_svc,
"backend": backend_svc,
"encoder": encoder_svc,
"flacfetch": flacfetch_svc,
"separator": separator_svc,
}
}
@router.get("/health/detailed")
async def detailed_health_check() -> Dict[str, Any]:
"""
+217 -119
View File
@@ -38,6 +38,7 @@ from backend.services.tracing import add_span_attribute
from backend.api.dependencies import require_admin, require_auth
from backend.services.auth_service import AuthResult
from backend.services.metrics import metrics
from backend.i18n import t, get_locale_from_request
from backend.middleware.tenant import get_tenant_from_request
from backend.utils.test_data import is_test_email
from backend.exceptions import InsufficientCreditsError
@@ -84,6 +85,7 @@ async def create_job(
3. Both workers update job state as they progress
4. When both complete, job transitions to AWAITING_REVIEW
"""
locale = get_locale_from_request(http_request)
try:
# Determine job owner email:
# All authentication methods must provide a user_email for job ownership
@@ -95,7 +97,7 @@ async def create_job(
logger.error("Authentication succeeded but no user_email provided")
raise HTTPException(
status_code=500,
detail="Authentication error: no user identity available"
detail=t(locale, "jobs.authError")
)
# Admins can optionally create jobs on behalf of other users
@@ -114,7 +116,7 @@ async def create_job(
if not effective_theme_id:
raise HTTPException(
status_code=422,
detail="No default theme configured. Please contact support or specify a theme_id."
detail=t(locale, "jobs.noDefaultTheme")
)
logger.info(f"Applying default theme: {effective_theme_id}")
@@ -156,7 +158,7 @@ async def create_job(
return JobResponse(
status="success",
job_id=job.job_id,
message="Job created successfully. Processing started."
message=t(locale, "jobs.created")
)
except InsufficientCreditsError:
raise
@@ -172,16 +174,18 @@ async def create_job(
@router.get("/{job_id}", response_model=Job)
async def get_job(
job_id: str,
request: Request,
auth_result: AuthResult = Depends(require_auth)
) -> Job:
"""Get job status and details."""
locale = get_locale_from_request(request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership - users can only see their own jobs, admins can see all
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to access this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
# If job is complete, include download URLs
if job.status == JobStatus.COMPLETE:
@@ -236,6 +240,7 @@ class EditTrackResponse(BaseModel):
async def edit_completed_track(
job_id: str,
request: EditTrackRequest,
http_request: Request,
background_tasks: BackgroundTasks,
auth_result: AuthResult = Depends(require_auth),
):
@@ -249,30 +254,31 @@ async def edit_completed_track(
No additional credits are consumed — the original credit covers re-edits.
"""
locale = get_locale_from_request(http_request)
import re
from datetime import timezone
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to edit this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionEdit"))
# Only completed jobs can be edited
if job.status != JobStatus.COMPLETE.value and job.status != "complete":
raise HTTPException(
status_code=400,
detail=f"Only completed jobs can be edited. Current status: {job.status}"
detail=t(locale, "jobs.notCompleted", status=job.status)
)
# Prevent editing if outputs already deleted (edit already in progress)
if job.outputs_deleted_at:
raise HTTPException(
status_code=400,
detail="This job is already being edited (outputs were already deleted)"
detail=t(locale, "jobs.alreadyBeingEdited")
)
user_email = auth_result.user_email or "unknown"
@@ -397,8 +403,7 @@ async def edit_completed_track(
if critical_failures:
raise HTTPException(
status_code=500,
detail=f"Cleanup failed for {', '.join(critical_failures)}. "
f"Job not modified. Please try again or contact support."
detail=t(locale, "jobs.cleanupFailed", services=", ".join(critical_failures))
)
# --- Phase 2: Update job record ---
@@ -450,6 +455,11 @@ async def edit_completed_track(
if "screens_progress" in state_data:
update_payload[f"state_data.screens_progress"] = DELETE_FIELD
# Clear stale file_urls.screens so retry logic doesn't skip screen generation
file_urls = job.file_urls or {}
for key in list(file_urls.get('screens', {}).keys()):
update_payload[f"file_urls.screens.{key}"] = DELETE_FIELD
# Add timeline event with structured metadata
edit_number = (job.edit_count if hasattr(job, 'edit_count') else 0) + 1
timeline_event = {
@@ -469,23 +479,32 @@ async def edit_completed_track(
# Apply Firestore update
job_ref.update(update_payload)
# --- Phase 4: Transition state to AWAITING_REVIEW ---
# This auto-generates a review token via transition_to_state
job_manager.transition_to_state(
job_id,
JobStatus.AWAITING_REVIEW,
progress=60,
message="Track reopened for editing",
)
# If metadata changed, trigger screens worker in background
# --- Phase 4: Transition state ---
if metadata_updated:
# Metadata changed → screens need regeneration.
# Transition to LYRICS_COMPLETE so screens worker can run
# (LYRICS_COMPLETE → GENERATING_SCREENS is a valid transition;
# AWAITING_REVIEW → GENERATING_SCREENS is not).
job_manager.transition_to_state(
job_id,
JobStatus.LYRICS_COMPLETE,
progress=55,
message="Regenerating screens with updated metadata",
)
background_tasks.add_task(worker_service.trigger_screens_worker, job_id)
else:
# No metadata change → screens still valid, go straight to review
job_manager.transition_to_state(
job_id,
JobStatus.AWAITING_REVIEW,
progress=60,
message="Track reopened for editing",
)
# Fetch updated job to get the review token
updated_job = job_manager.get_job(job_id)
if not updated_job:
logger.error(f"Job {job_id} not found after state transition to AWAITING_REVIEW")
logger.error(f"Job {job_id} not found after state transition")
raise HTTPException(status_code=500, detail="Job state update failed unexpectedly")
review_token = updated_job.review_token or ""
@@ -504,7 +523,7 @@ async def edit_completed_track(
return EditTrackResponse(
status="success",
job_id=job_id,
message="Track reopened for editing. Previous outputs have been removed.",
message=t(locale, "jobs.reopened"),
review_url=f"/app/jobs#/{job_id}/review",
review_token=review_token,
metadata_updated=metadata_updated,
@@ -519,7 +538,7 @@ _SUMMARY_STATE_DATA_KEYS = {
'backing_vocals_analysis', 'visibility_change_in_progress',
}
_SUMMARY_FILE_URLS_KEYS = {'finals', 'videos', 'packages'}
_HIDE_COMPLETED_STATUSES = ['complete', 'prep_complete']
_HIDE_COMPLETED_STATUSES = ['complete', 'prep_complete', 'cancelled']
def _prune_state_data(data: Dict[str, Any]) -> Dict[str, Any]:
@@ -538,6 +557,21 @@ def _prune_file_urls(data: Dict[str, Any]) -> Dict[str, Any]:
return data
def _search_filter_jobs(jobs: List[Dict[str, Any]], search: str) -> List[Dict[str, Any]]:
"""Filter job dicts by case-insensitive substring match across key fields."""
if not search:
return jobs
term = search.lower()
results = []
for job in jobs:
searchable = " ".join(
str(job.get(f) or "") for f in ("job_id", "artist", "title", "audio_search_artist", "audio_search_title")
)
if term in searchable.lower():
results.append(job)
return results
@router.get("", response_model=None)
async def list_jobs(
request: Request,
@@ -550,6 +584,7 @@ async def list_jobs(
limit: int = 100,
fields: Optional[str] = None,
hide_completed: bool = False,
search: Optional[str] = None,
auth_result: AuthResult = Depends(require_auth)
):
"""
@@ -568,6 +603,7 @@ async def list_jobs(
limit: Maximum number of jobs to return (default 100)
fields: Set to "summary" for reduced payload with only dashboard-required fields
hide_completed: If True, exclude successful completions (complete, prep_complete). Failed jobs remain visible.
search: Text search filter - matches against artist, title, audio_search_artist, audio_search_title, and job_id (case-insensitive substring). Only works with fields=summary.
Returns:
List of jobs matching filters, ordered by created_at descending.
@@ -581,17 +617,19 @@ async def list_jobs(
created_after_dt = None
created_before_dt = None
locale = get_locale_from_request(request)
if created_after:
try:
created_after_dt = datetime.fromisoformat(created_after.replace('Z', '+00:00'))
except ValueError as e:
raise HTTPException(status_code=400, detail=f"Invalid created_after format: {created_after}") from e
raise HTTPException(status_code=400, detail=t(locale, "jobs.invalidDatetimeFormat", field="created_after", value=created_after)) from e
if created_before:
try:
created_before_dt = datetime.fromisoformat(created_before.replace('Z', '+00:00'))
except ValueError as e:
raise HTTPException(status_code=400, detail=f"Invalid created_before format: {created_before}") from e
raise HTTPException(status_code=400, detail=t(locale, "jobs.invalidDatetimeFormat", field="created_before", value=created_before)) from e
# Determine user_email filter based on admin status
# Admins see all jobs, regular users only see their own
@@ -615,6 +653,8 @@ async def list_jobs(
# --- Summary mode: field-projected query returning dicts ---
if fields == "summary":
exclude_statuses = _HIDE_COMPLETED_STATUSES if hide_completed else None
# When searching, fetch more results and filter in Python
fetch_limit = 1000 if search else limit
jobs_dicts = job_manager.list_jobs_summary(
status=status,
exclude_statuses=exclude_statuses,
@@ -624,13 +664,18 @@ async def list_jobs(
created_before=created_before_dt,
user_email=user_email_filter,
tenant_id=effective_tenant_id,
limit=limit,
limit=fetch_limit,
)
# Exclude test user jobs (Python-side, same as full mode)
if exclude_test and auth_result.is_admin:
jobs_dicts = [j for j in jobs_dicts if not is_test_email(j.get('user_email') or "")]
# Apply search filter if provided
if search:
jobs_dicts = _search_filter_jobs(jobs_dicts, search)
jobs_dicts = jobs_dicts[:limit] # Apply original limit after filtering
# Safety-net pruning (in case Firestore returned extra nested keys)
jobs_dicts = [_prune_file_urls(_prune_state_data(j)) for j in jobs_dicts]
@@ -659,24 +704,26 @@ async def list_jobs(
raise
except Exception as e:
logger.error(f"Error listing jobs: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail=t(locale, "jobs.listError", error=str(e)))
@router.delete("/{job_id}")
async def delete_job(
job_id: str,
request: Request,
delete_files: bool = True,
auth_result: AuthResult = Depends(require_auth)
) -> dict:
"""Delete a job and optionally its output files."""
locale = get_locale_from_request(request)
try:
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership - users can only delete their own jobs
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to delete this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionDelete"))
# Recycle any unreturned brand code before deleting the job record
state_data = job.state_data or {}
@@ -703,11 +750,12 @@ async def delete_job(
raise
except Exception as e:
logger.error(f"Error deleting job {job_id}: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail=t(locale, "jobs.deleteError", job_id=job_id, error=str(e)))
@router.delete("")
async def bulk_delete_jobs(
request: Request,
environment: Optional[str] = None,
client_id: Optional[str] = None,
status: Optional[JobStatus] = None,
@@ -739,13 +787,15 @@ async def bulk_delete_jobs(
"""
from datetime import datetime
locale = get_locale_from_request(request)
# Require at least one filter to prevent accidental deletion of all jobs
if not any([environment, client_id, status, created_before]):
raise HTTPException(
status_code=400,
detail="At least one filter (environment, client_id, status, created_before) is required"
detail=t(locale, "jobs.deletionRequiresFilters")
)
# Require explicit confirmation
if not confirm:
# Return preview of what would be deleted
@@ -766,7 +816,7 @@ async def bulk_delete_jobs(
return {
"status": "preview",
"message": "Add &confirm=true to execute deletion",
"message": t(locale, "jobs.deletionPreview"),
"jobs_to_delete": len(jobs),
"sample_jobs": [
{
@@ -808,7 +858,7 @@ async def bulk_delete_jobs(
except Exception as e:
logger.error(f"Error bulk deleting jobs: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail=t(locale, "jobs.bulkDeleteError", error=str(e)))
# ============================================================================
@@ -818,6 +868,7 @@ async def bulk_delete_jobs(
@router.get("/{job_id}/review-data")
async def get_review_data(
job_id: str,
request: Request,
auth_result: AuthResult = Depends(require_auth)
) -> Dict[str, Any]:
"""
@@ -826,18 +877,19 @@ async def get_review_data(
Returns corrections JSON URL and audio URL.
Frontend loads these to render the review UI.
"""
locale = get_locale_from_request(request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to access this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=f"Job not ready for review (current status: {job.status})"
detail=t(locale, "jobs.reviewNotReady", status=job.status)
)
# Get URLs from file_urls
@@ -856,13 +908,13 @@ async def get_review_data(
if not corrections_url:
raise HTTPException(
status_code=500,
detail="Corrections data not available"
detail=t(locale, "jobs.correctionsUnavailable")
)
if not audio_url:
raise HTTPException(
status_code=500,
detail="Audio not available for review"
detail=t(locale, "jobs.audioUnavailable")
)
# Generate signed URLs for direct access
@@ -882,6 +934,7 @@ async def get_review_data(
async def start_review(
job_id: str,
request: StartReviewRequest,
http_request: Request,
auth_result: AuthResult = Depends(require_auth)
) -> dict:
"""
@@ -889,22 +942,23 @@ async def start_review(
This helps track that the user is actively working on the review.
"""
locale = get_locale_from_request(http_request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to access this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
success = job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.IN_REVIEW,
message="User started reviewing lyrics"
)
if not success:
raise HTTPException(status_code=400, detail="Cannot start review")
raise HTTPException(status_code=400, detail=t(locale, "jobs.reviewCannotStart"))
return {"status": "success", "job_status": "in_review"}
@@ -913,6 +967,7 @@ async def start_review(
async def submit_corrections(
job_id: str,
submission: CorrectionsSubmission,
http_request: Request,
background_tasks: BackgroundTasks,
auth_result: AuthResult = Depends(require_auth)
) -> dict:
@@ -924,18 +979,19 @@ async def submit_corrections(
Can be called multiple times to save progress.
"""
locale = get_locale_from_request(http_request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to modify this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=f"Job not in review state (current status: {job.status})"
detail=t(locale, "jobs.jobNotInReviewState", status=job.status)
)
try:
@@ -971,7 +1027,7 @@ async def submit_corrections(
return {
"status": "success",
"job_status": "in_review",
"message": "Corrections saved. Call /complete-review when done."
"message": t(locale, "jobs.correctionsProcessing")
}
except Exception as e:
@@ -983,6 +1039,7 @@ async def submit_corrections(
async def submit_edit_log(
job_id: str,
edit_log: Dict[str, Any],
request: Request,
auth_result: AuthResult = Depends(require_auth)
) -> dict:
"""
@@ -993,12 +1050,13 @@ async def submit_edit_log(
Stored to GCS as jobs/{job_id}/lyrics/edit_log_{session_id}.json.
"""
locale = get_locale_from_request(request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to modify this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
session_id = edit_log.get("session_id", "unknown")
entries = edit_log.get("entries", [])
@@ -1025,13 +1083,14 @@ async def submit_edit_log(
except Exception as e:
logger.error(f"Error saving edit log for job {job_id}: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail=t(locale, "jobs.editLogSaveFailed", job_id=job_id, error=str(e)))
@router.post("/{job_id}/create-custom-instrumental")
async def create_custom_instrumental(
job_id: str,
request: CreateCustomInstrumentalRequest,
http_request: Request,
auth_result: AuthResult = Depends(require_auth)
) -> dict:
"""
@@ -1040,17 +1099,18 @@ async def create_custom_instrumental(
Downloads the clean instrumental and backing vocals stems, applies mute
regions, combines them, uploads to GCS, and returns a signed URL for playback.
"""
locale = get_locale_from_request(http_request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to modify this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=f"Job not in review state (current status: {job.status})"
detail=t(locale, "jobs.jobNotInReviewState", status=job.status)
)
# Get stem paths from job
@@ -1061,7 +1121,7 @@ async def create_custom_instrumental(
if not clean_path or not backing_path:
raise HTTPException(
status_code=400,
detail="Job missing required stems (instrumental_clean and/or backing_vocals)"
detail=t(locale, "jobs.stemsMissing")
)
try:
@@ -1109,12 +1169,13 @@ async def create_custom_instrumental(
except Exception as e:
logger.error(f"Error creating custom instrumental for job {job_id}: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail=t(locale, "jobs.customInstrumentalFailed", job_id=job_id, error=str(e)))
@router.post("/{job_id}/upload-instrumental")
async def upload_custom_instrumental(
job_id: str,
request: Request,
file: UploadFile = File(...),
auth_result: AuthResult = Depends(require_auth)
) -> dict:
@@ -1125,17 +1186,18 @@ async def upload_custom_instrumental(
The file is stored to GCS and its path recorded in the job's stems metadata.
The user can then select 'custom' as their instrumental_selection when completing review.
"""
locale = get_locale_from_request(request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to modify this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=f"Job not in review state (current status: {job.status})"
detail=t(locale, "jobs.reviewNotInState", status=job.status)
)
# Determine extension from filename or content type
@@ -1178,11 +1240,9 @@ async def upload_custom_instrumental(
if diff > 0.5:
raise HTTPException(
status_code=400,
detail=(
f"Duration mismatch: uploaded file is {upload_duration:.1f}s "
f"but original audio is {original_duration:.1f}s. "
f"The instrumental must be exactly {original_duration:.1f}s (±0.5s)."
),
detail=t(locale, "jobs.durationMismatch",
upload_duration=f"{upload_duration:.1f}",
original_duration=f"{original_duration:.1f}"),
)
# Convert to FLAC for consistency with the rest of the pipeline
@@ -1201,7 +1261,7 @@ async def upload_custom_instrumental(
raise
except Exception as e:
logger.error(f"Job {job_id}: Error processing uploaded instrumental: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Failed to process audio file: {str(e)}")
raise HTTPException(status_code=500, detail=t(locale, "jobs.audioProcessingFailed", error=str(e)))
finally:
if tmp_path and os.path.exists(tmp_path):
os.unlink(tmp_path)
@@ -1254,6 +1314,7 @@ async def _get_audio_duration_ffprobe_signed(job_id: str, job, storage: StorageS
@router.post("/{job_id}/complete-review")
async def complete_review(
job_id: str,
request: Request,
background_tasks: BackgroundTasks,
auth_result: AuthResult = Depends(require_auth),
body: Optional[CompleteReviewRequest] = None
@@ -1270,18 +1331,19 @@ async def complete_review(
3. Worker uses OutputGenerator to create with_vocals.mkv
4. Job transitions to INSTRUMENTAL_SELECTED then GENERATING_VIDEO
"""
locale = get_locale_from_request(request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to modify this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=f"Job not in review state (current status: {job.status})"
detail=t(locale, "jobs.reviewNotInState", status=job.status)
)
# Check for 0-segment lyrics — fail early with user-friendly message
@@ -1296,12 +1358,7 @@ async def complete_review(
if segment_count == 0 and len(corrected_segments) == 0:
raise HTTPException(
status_code=400,
detail=(
"Cannot complete review: no lyrics were detected in the audio. "
"This can happen when the input audio has no vocals (e.g. a karaoke track or instrumental). "
"You can go back and paste lyrics manually using 'Replace All', "
"or cancel this job and try again with an audio file that contains vocals."
)
detail=t(locale, "jobs.noLyricsDetected")
)
try:
@@ -1328,18 +1385,19 @@ async def complete_review(
return {
"status": "success",
"job_status": "review_complete",
"message": "Review complete. Video rendering started."
"message": t(locale, "jobs.reviewCompleteStartRendering")
}
except Exception as e:
logger.error(f"Error completing review for job {job_id}: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail=t(locale, "jobs.reviewCompleteError", job_id=job_id, error=str(e)))
@router.post("/{job_id}/select-instrumental")
async def select_instrumental(
job_id: str,
selection: InstrumentalSelection,
request: Request,
background_tasks: BackgroundTasks,
auth_result: AuthResult = Depends(require_auth)
) -> dict:
@@ -1359,18 +1417,19 @@ async def select_instrumental(
Returns:
Status and confirmation of selection
"""
locale = get_locale_from_request(request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to access this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
if job.status != JobStatus.AWAITING_INSTRUMENTAL_SELECTION:
raise HTTPException(
status_code=400,
detail=f"Job not awaiting instrumental selection (current status: {job.status})"
detail=t(locale, "jobs.reviewNotInState", status=job.status)
)
try:
@@ -1396,17 +1455,18 @@ async def select_instrumental(
"status": "success",
"job_status": "instrumental_selected",
"selection": selection.selection,
"message": "Instrumental selected. Video generation started."
"message": t(locale, "jobs.instrumentalSelected")
}
except Exception as e:
logger.error(f"Error selecting instrumental for job {job_id}: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail=t(locale, "jobs.instrumentalSelectionError", job_id=job_id, error=str(e)))
@router.get("/{job_id}/download-urls")
async def get_download_urls(
job_id: str,
request: Request,
auth_result: AuthResult = Depends(require_auth)
) -> dict:
"""
@@ -1415,26 +1475,21 @@ async def get_download_urls(
Returns a dictionary mapping file types to download URLs.
Uses the streaming download endpoint which proxies through the backend.
"""
locale = get_locale_from_request(request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to access this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
if job.status != JobStatus.COMPLETE:
raise HTTPException(
status_code=400,
detail=f"Job not complete (current status: {job.status})"
)
file_urls = job.file_urls or {}
download_urls = {}
# Build download URLs using the streaming endpoint
base_url = f"/api/jobs/{job_id}/download"
for category, files in file_urls.items():
if isinstance(files, dict):
download_urls[category] = {}
@@ -1444,7 +1499,7 @@ async def get_download_urls(
elif isinstance(files, str) and files:
# For single-file categories, use the category name as the file_key
download_urls[category] = f"{base_url}/{category}/{category}"
return {
"job_id": job_id,
"artist": job.artist,
@@ -1471,6 +1526,7 @@ async def download_file(
job_id: str,
category: str,
file_key: str,
request: Request,
auth_result: AuthResult = Depends(require_auth)
):
"""
@@ -1479,23 +1535,18 @@ async def download_file(
This endpoint proxies the file from GCS through the backend,
so no client-side authentication is required.
"""
locale = get_locale_from_request(request)
from fastapi.responses import StreamingResponse
import tempfile
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to access this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
if job.status != JobStatus.COMPLETE:
raise HTTPException(
status_code=400,
detail=f"Job not complete (current status: {job.status})"
)
file_urls = job.file_urls or {}
category_files = file_urls.get(category)
@@ -1587,6 +1638,7 @@ async def download_file(
async def cancel_job(
job_id: str,
request: CancelJobRequest,
http_request: Request,
auth_result: AuthResult = Depends(require_auth)
) -> dict:
"""
@@ -1594,13 +1646,14 @@ async def cancel_job(
Jobs can be cancelled at any stage before completion.
"""
locale = get_locale_from_request(http_request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to cancel this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
success = job_manager.cancel_job(job_id, reason=request.reason)
@@ -1617,6 +1670,7 @@ async def cancel_job(
@router.post("/{job_id}/retry")
async def retry_job(
job_id: str,
request: Request,
background_tasks: BackgroundTasks,
auth_result: AuthResult = Depends(require_auth)
) -> dict:
@@ -1632,20 +1686,21 @@ async def retry_job(
The retry logic determines the appropriate stage to resume from
based on what files/state already exist.
"""
locale = get_locale_from_request(request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to retry this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
if job.status not in [JobStatus.FAILED, JobStatus.CANCELLED]:
raise HTTPException(
status_code=400,
detail=f"Only failed or cancelled jobs can be retried (current status: {job.status})"
detail=t(locale, "jobs.notCompleted", status=job.status)
)
try:
# Determine retry point based on what's already complete
error_details = job.error_details or {}
@@ -1693,11 +1748,14 @@ async def retry_job(
"retry_stage": "video_generation"
}
# If we have corrections and screens but no video, retry render
elif (file_urls.get('lyrics', {}).get('corrections') and
file_urls.get('screens', {}).get('title')):
logger.info(f"Job {job_id}: Has corrections and screens, retrying from render stage")
# If we have corrections, screens, AND review was completed, retry render
# Review completion is proven by instrumental_selection in state_data
# (set only when user submits the review endpoint)
elif (file_urls.get('lyrics', {}).get('corrections') and
file_urls.get('screens', {}).get('title') and
state_data.get('instrumental_selection')):
logger.info(f"Job {job_id}: Has corrections, screens, and completed review — retrying from render stage")
# Clear error state and reset worker progress for idempotency
job_manager.update_job(job_id, {
@@ -1717,16 +1775,48 @@ async def retry_job(
status_code=500,
detail="Failed to transition job status for retry"
)
# Trigger render video worker
background_tasks.add_task(worker_service.trigger_render_video_worker, job_id)
return {
"status": "success",
"job_status": "review_complete",
"message": "Job retry started from render stage",
"retry_stage": "render_video"
}
# If we have corrections and screens but review was NOT completed,
# return to awaiting_review so the user can review lyrics
elif (file_urls.get('lyrics', {}).get('corrections') and
file_urls.get('screens', {}).get('title')):
logger.info(f"Job {job_id}: Has corrections and screens but review not completed — returning to review")
# Clear error state
job_manager.update_job(job_id, {
'error_message': None,
'error_details': None,
})
# Transition to AWAITING_REVIEW so user can review lyrics
if not job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_REVIEW,
progress=55,
message=f"Ready for review. Please review lyrics and select your instrumental."
):
raise HTTPException(
status_code=500,
detail="Failed to transition job status for retry"
)
return {
"status": "success",
"job_status": "awaiting_review",
"message": "Job retry: returning to lyrics review (review was not completed before failure)",
"retry_stage": "awaiting_review"
}
# If we have stems and corrections, retry from screens generation
elif (file_urls.get('stems', {}).get('instrumental_clean') and
@@ -1859,6 +1949,7 @@ async def retry_job(
@router.get("/{job_id}/logs")
async def get_worker_logs(
job_id: str,
request: Request,
since_index: int = 0,
worker: Optional[str] = None,
auth_result: AuthResult = Depends(require_auth)
@@ -1885,13 +1976,14 @@ async def get_worker_logs(
"total_logs": 42
}
"""
locale = get_locale_from_request(request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership - users can only see logs for their own jobs
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to access logs for this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
logs = job_manager.get_worker_logs(job_id, since_index=since_index, worker=worker)
total = job_manager.get_worker_logs_count(job_id)
@@ -1906,6 +1998,7 @@ async def get_worker_logs(
@router.post("/{job_id}/cleanup-distribution")
async def cleanup_distribution(
job_id: str,
request: Request,
delete_job: bool = True,
auth_result: AuthResult = Depends(require_admin)
) -> dict:
@@ -1925,9 +2018,10 @@ async def cleanup_distribution(
Returns:
Cleanup results for each service
"""
locale = get_locale_from_request(request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
state_data = job.state_data or {}
results = {
@@ -2144,6 +2238,8 @@ async def create_job_from_search(
Credit deduction happens here (inside job_manager.create_job).
"""
locale = get_locale_from_request(request)
# Lazy imports from audio_search to avoid circular imports at module level
from backend.api.routes.audio_search import (
_validate_and_prepare_selection,
@@ -2154,7 +2250,7 @@ async def create_job_from_search(
try:
user_email = auth_result.user_email
if not user_email:
raise HTTPException(status_code=401, detail="Authentication required")
raise HTTPException(status_code=401, detail=t(locale, "jobs.authError"))
# Read the session non-destructively for validation.
# consume_search_session (atomic read+delete) is called later, just before job creation,
@@ -2281,7 +2377,7 @@ async def create_job_from_search(
from backend.api.routes.file_upload import _prepare_theme_for_job
try:
style_params_path, theme_style_assets, youtube_desc = _prepare_theme_for_job(
job_id, effective_theme_id, {}
job_id, effective_theme_id, {}, locale=locale
)
theme_update = {
'style_params_gcs_path': style_params_path,
@@ -2342,6 +2438,7 @@ async def create_job_from_search(
async def change_visibility(
job_id: str,
request: ChangeVisibilityRequest,
http_request: Request,
auth_result: AuthResult = Depends(require_auth),
):
"""
@@ -2355,10 +2452,11 @@ async def change_visibility(
- Resets custom styling to default Nomad theme
- Regenerates screens, re-renders video, publishes publicly
"""
locale = get_locale_from_request(http_request)
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
user_email = auth_result.user_email or "unknown"
is_admin = auth_result.is_admin
+24 -12
View File
@@ -18,6 +18,7 @@ from backend.config import get_settings
from backend.api.dependencies import require_auth, require_admin
from backend.services.auth_service import AuthResult
from backend.services.push_notification_service import get_push_notification_service
from backend.i18n import t, get_locale_from_request
logger = logging.getLogger(__name__)
@@ -127,18 +128,20 @@ async def subscribe_push(
1. Request body tenant_id field (explicit from frontend)
2. Tenant middleware (X-Tenant-ID header or subdomain detection)
"""
locale = get_locale_from_request(http_request)
settings = get_settings()
if not settings.enable_push_notifications:
raise HTTPException(status_code=503, detail="Push notifications are not enabled")
raise HTTPException(status_code=503, detail=t(locale, "push.disabled"))
if not auth_result.user_email:
raise HTTPException(status_code=401, detail="User email not available")
raise HTTPException(status_code=401, detail=t(locale, "push.userEmailNotAvailable"))
push_service = get_push_notification_service()
# Validate keys
if "p256dh" not in subscribe_request.keys or "auth" not in subscribe_request.keys:
raise HTTPException(status_code=400, detail="Missing required keys (p256dh, auth)")
raise HTTPException(status_code=400, detail=t(locale, "push.missingEncryptionKeys"))
# Resolve tenant_id: prefer explicit from body, fall back to middleware
tenant_id = subscribe_request.tenant_id
@@ -154,17 +157,18 @@ async def subscribe_push(
)
if not success:
raise HTTPException(status_code=500, detail="Failed to save subscription")
raise HTTPException(status_code=500, detail=t(locale, "push.subscriptionSaveFailed"))
return SubscribeResponse(
status="success",
message="Push subscription registered successfully"
message=t(locale, "push.subscriptionRegistered")
)
@router.post("/unsubscribe", response_model=UnsubscribeResponse)
async def unsubscribe_push(
request: UnsubscribeRequest,
http_request: Request,
auth_result: AuthResult = Depends(require_auth)
):
"""
@@ -172,8 +176,10 @@ async def unsubscribe_push(
Requires authentication. Users can only remove their own subscriptions.
"""
locale = get_locale_from_request(http_request)
if not auth_result.user_email:
raise HTTPException(status_code=401, detail="User email not available")
raise HTTPException(status_code=401, detail=t(locale, "push.userEmailNotAvailable"))
push_service = get_push_notification_service()
@@ -186,17 +192,18 @@ async def unsubscribe_push(
# Don't error if subscription wasn't found - might already be removed
return UnsubscribeResponse(
status="success",
message="Subscription removed (or was not found)"
message=t(locale, "push.subscriptionNotFound")
)
return UnsubscribeResponse(
status="success",
message="Push subscription removed successfully"
message=t(locale, "push.subscriptionRemoved")
)
@router.get("/subscriptions", response_model=SubscriptionsListResponse)
async def list_subscriptions(
request: Request,
auth_result: AuthResult = Depends(require_auth)
):
"""
@@ -204,8 +211,10 @@ async def list_subscriptions(
Requires authentication.
"""
locale = get_locale_from_request(request)
if not auth_result.user_email:
raise HTTPException(status_code=401, detail="User email not available")
raise HTTPException(status_code=401, detail=t(locale, "push.userEmailNotAvailable"))
push_service = get_push_notification_service()
@@ -220,6 +229,7 @@ async def list_subscriptions(
@router.post("/test", response_model=TestNotificationResponse)
async def send_test_notification(
request: TestNotificationRequest,
http_request: Request,
auth_result: AuthResult = Depends(require_admin)
):
"""
@@ -227,12 +237,14 @@ async def send_test_notification(
Admin only. Useful for testing push notification setup.
"""
locale = get_locale_from_request(http_request)
settings = get_settings()
if not settings.enable_push_notifications:
raise HTTPException(status_code=503, detail="Push notifications are not enabled")
raise HTTPException(status_code=503, detail=t(locale, "push.disabled"))
if not auth_result.user_email:
raise HTTPException(status_code=401, detail="User email not available")
raise HTTPException(status_code=401, detail=t(locale, "push.userEmailNotAvailable"))
push_service = get_push_notification_service()
@@ -247,5 +259,5 @@ async def send_test_notification(
return TestNotificationResponse(
status="success",
sent_count=sent_count,
message=f"Test notification sent to {sent_count} device(s)"
message=t(locale, "push.testNotificationSent", sent_count=sent_count)
)
+22 -21
View File
@@ -10,12 +10,13 @@ import logging
from datetime import datetime
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel
from backend.api.dependencies import require_admin
from backend.services.auth_service import AuthResult
from backend.services.email_validation_service import get_email_validation_service, EmailValidationService
from backend.i18n import t, get_locale_from_request
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/admin/rate-limits", tags=["admin", "rate-limits"])
@@ -106,13 +107,13 @@ async def add_disposable_domain(
domain = request.domain.lower().strip()
if not domain or "." not in domain:
raise HTTPException(status_code=400, detail="Invalid domain format")
raise HTTPException(status_code=400, detail=t("en", "admin.invalidDomainFormat"))
email_validation.add_disposable_domain(domain, auth_result.user_email)
return SuccessResponse(
success=True,
message=f"Domain '{domain}' added to disposable domains blocklist"
message=t("en", "admin.domainAddedToBl", domain=domain)
)
@@ -126,11 +127,11 @@ async def remove_disposable_domain(
domain = domain.lower().strip()
if not email_validation.remove_disposable_domain(domain, auth_result.user_email):
raise HTTPException(status_code=404, detail="Domain not found in blocklist")
raise HTTPException(status_code=404, detail=t("en", "admin.domainNotFoundInBl"))
return SuccessResponse(
success=True,
message=f"Domain '{domain}' removed from disposable domains blocklist"
message=t("en", "admin.domainRemovedFromBl", domain=domain)
)
@@ -143,9 +144,9 @@ async def add_allowlisted_domain(
email_validation = get_email_validation_service()
domain = request.domain.lower().strip()
if not domain or "." not in domain:
raise HTTPException(status_code=400, detail="Invalid domain format")
raise HTTPException(status_code=400, detail=t("en", "admin.invalidDomainFormat"))
email_validation.add_allowlisted_domain(domain, auth_result.user_email)
return SuccessResponse(success=True, message=f"Domain '{domain}' added to allowlist")
return SuccessResponse(success=True, message=t("en", "admin.domainAddedToAllowlist", domain=domain))
@router.delete("/blocklists/allowlisted-domains/{domain}", response_model=SuccessResponse)
@@ -157,8 +158,8 @@ async def remove_allowlisted_domain(
email_validation = get_email_validation_service()
domain = domain.lower().strip()
if not email_validation.remove_allowlisted_domain(domain, auth_result.user_email):
raise HTTPException(status_code=404, detail="Domain not found in allowlist")
return SuccessResponse(success=True, message=f"Domain '{domain}' removed from allowlist")
raise HTTPException(status_code=404, detail=t("en", "admin.domainNotFoundInAllowlist"))
return SuccessResponse(success=True, message=t("en", "admin.domainRemovedFromAllowlist", domain=domain))
@router.post("/blocklists/sync", response_model=SuccessResponse)
@@ -181,7 +182,7 @@ async def trigger_sync(
return SuccessResponse(
success=True,
message=f"Synced {result['external_count']} external domains ({result['added']} added, {result['removed']} removed)"
message=t("en", "admin.syncComplete", external_count=result['external_count'], added=result['added'], removed=result['removed'])
)
@@ -195,13 +196,13 @@ async def add_blocked_email(
email = request.email.lower().strip()
if not email or "@" not in email:
raise HTTPException(status_code=400, detail="Invalid email format")
raise HTTPException(status_code=400, detail=t("en", "admin.invalidEmailFormat"))
email_validation.add_blocked_email(email, auth_result.user_email)
return SuccessResponse(
success=True,
message=f"Email '{email}' added to blocked emails list"
message=t("en", "admin.emailAddedToBl", email=email)
)
@@ -215,11 +216,11 @@ async def remove_blocked_email(
email = email.lower().strip()
if not email_validation.remove_blocked_email(email, auth_result.user_email):
raise HTTPException(status_code=404, detail="Email not found in blocklist")
raise HTTPException(status_code=404, detail=t("en", "admin.emailNotFoundInBl"))
return SuccessResponse(
success=True,
message=f"Email '{email}' removed from blocked emails list"
message=t("en", "admin.emailRemovedFromBl", email=email)
)
@@ -233,13 +234,13 @@ async def add_blocked_ip(
ip_address = request.ip_address.strip()
if not ip_address:
raise HTTPException(status_code=400, detail="Invalid IP address")
raise HTTPException(status_code=400, detail=t("en", "admin.invalidIPAddress"))
email_validation.add_blocked_ip(ip_address, auth_result.user_email)
return SuccessResponse(
success=True,
message=f"IP '{ip_address}' added to blocked IPs list"
message=t("en", "admin.ipAddedToBl", ip_address=ip_address)
)
@@ -253,11 +254,11 @@ async def remove_blocked_ip(
ip_address = ip_address.strip()
if not email_validation.remove_blocked_ip(ip_address, auth_result.user_email):
raise HTTPException(status_code=404, detail="IP not found in blocklist")
raise HTTPException(status_code=404, detail=t("en", "admin.ipNotFoundInBl"))
return SuccessResponse(
success=True,
message=f"IP '{ip_address}' removed from blocked IPs list"
message=t("en", "admin.ipRemovedFromBl", ip_address=ip_address)
)
@@ -303,12 +304,12 @@ async def retry_youtube_upload(
if not queue_service.retry_upload(job_id):
raise HTTPException(
status_code=404,
detail=f"Upload not found or not in retryable state for job {job_id}"
detail=t("en", "admin.youtubeUploadNotFound", job_id=job_id)
)
return SuccessResponse(
success=True,
message=f"YouTube upload for job {job_id} queued for retry"
message=t("en", "admin.youtubeUploadQueuedForRetry", job_id=job_id)
)
@@ -341,5 +342,5 @@ async def trigger_youtube_queue_processing(
return SuccessResponse(
success=True,
message="YouTube queue processing started in background"
message=t("en", "admin.youtubeQueueProcessingStarted")
)
+374
View File
@@ -0,0 +1,374 @@
"""
Referral API routes.
Handles:
- Public referral interstitial (click tracking)
- Authenticated referral dashboard
- Stripe Connect onboarding
- Admin vanity link creation and link management
"""
import logging
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from fastapi.responses import Response
from pydantic import BaseModel, Field
from backend.api.dependencies import require_auth, require_admin
from backend.models.referral import (
CreateReferralLinkRequest,
UpdateReferralLinkRequest,
ReferralInterstitialResponse,
)
from backend.services.flyer_service import get_flyer_service, FlyerError
from backend.services.referral_service import get_referral_service
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/referrals", tags=["referrals"])
class GenerateFlyerRequest(BaseModel):
theme: str = Field(..., pattern="^(light|dark)$")
qr_data_url: str = Field(..., max_length=500_000)
# ============================================================================
# Public endpoints
# ============================================================================
@router.get("/r/{code}", response_model=ReferralInterstitialResponse)
async def get_referral_interstitial(code: str, no_track: bool = False):
"""
Public endpoint: get interstitial data for a referral link.
Increments click count unless no_track=true. Returns valid=False if code not found.
"""
service = get_referral_service()
link = service.get_link_by_code(code)
if not link:
return ReferralInterstitialResponse(valid=False)
# Track the click (skip when fetching for display purposes)
if not no_track:
try:
service.increment_clicks(code)
except Exception:
logger.warning("Failed to increment clicks for code %s", code, exc_info=True)
return ReferralInterstitialResponse(
valid=True,
referral_code=link.code,
referrer_display_name=link.display_name,
discount_percent=link.discount_percent,
discount_duration_days=link.discount_duration_days,
custom_message=link.custom_message,
)
# ============================================================================
# Authenticated user endpoints
# ============================================================================
@router.get("/me")
async def get_my_dashboard(auth=Depends(require_auth)):
"""Get referral dashboard data for the authenticated user."""
service = get_referral_service()
return service.get_dashboard_data(auth.user_email)
@router.put("/me")
async def update_my_link(
updates: UpdateReferralLinkRequest,
auth=Depends(require_auth),
):
"""Update display_name and custom_message on the user's own referral link."""
service = get_referral_service()
link = service.get_or_create_link(auth.user_email)
update_fields = {}
if updates.display_name is not None:
update_fields["display_name"] = updates.display_name
if updates.custom_message is not None:
update_fields["custom_message"] = updates.custom_message
if not update_fields:
return {"ok": True, "message": "No changes"}
success, message = service.update_link(link.code, **update_fields)
if not success:
raise HTTPException(status_code=400, detail=message)
return {"ok": True, "message": message}
@router.post("/me/connect")
async def start_stripe_connect(auth=Depends(require_auth)):
"""Start Stripe Connect onboarding for the authenticated user."""
# Check if user already has a Connect account
from backend.services.user_service import get_user_service
user_service = get_user_service()
user = user_service.get_user(auth.user_email)
if user and user.stripe_connect_account_id:
raise HTTPException(status_code=400, detail="Stripe Connect account already configured")
service = get_referral_service()
account_id, onboarding_url = service.create_connect_account(auth.user_email)
if not account_id:
raise HTTPException(status_code=500, detail="Failed to create Stripe Connect account")
user_service.update_user(auth.user_email, stripe_connect_account_id=account_id)
return {"account_id": account_id, "onboarding_url": onboarding_url}
@router.post("/me/connect/dashboard-link")
async def get_connect_dashboard_link(auth=Depends(require_auth)):
"""Get a login link to the Stripe Express dashboard for managing payout settings."""
from backend.services.user_service import get_user_service
user = get_user_service().get_user(auth.user_email)
if not user or not user.stripe_connect_account_id:
raise HTTPException(status_code=400, detail="No Stripe Connect account configured")
service = get_referral_service()
url = service.create_connect_login_link(user.stripe_connect_account_id)
if not url:
raise HTTPException(status_code=500, detail="Failed to create dashboard link")
return {"url": url}
@router.post("/me/connect/update-link")
async def get_connect_update_link(auth=Depends(require_auth)):
"""Get a link to update Stripe Connect account info (re-onboarding)."""
from backend.services.user_service import get_user_service
user = get_user_service().get_user(auth.user_email)
if not user or not user.stripe_connect_account_id:
raise HTTPException(status_code=400, detail="No Stripe Connect account configured")
service = get_referral_service()
url = service.create_connect_update_link(user.stripe_connect_account_id)
if not url:
raise HTTPException(status_code=500, detail="Failed to create update link")
return {"url": url}
class VanityRequest(BaseModel):
desired_code: str = Field(..., min_length=2, max_length=30, pattern="^[a-z0-9-]+$")
@router.post("/me/vanity-request")
async def request_vanity_url(
request: VanityRequest,
auth=Depends(require_auth),
):
"""Request a custom vanity referral URL. Sends email to admin for review."""
from backend.services.email_service import get_email_service
service = get_referral_service()
link = service.get_or_create_link(auth.user_email)
# Check if code is already taken
existing = service.get_link_by_code(request.desired_code)
if existing:
raise HTTPException(status_code=409, detail="That code is already taken. Please try another.")
email_service = get_email_service()
email_service.provider.send_email(
to_email="andrew@nomadkaraoke.com",
subject=f"Vanity referral URL request: {request.desired_code}",
html_content=f"""
<h2>Vanity Referral URL Request</h2>
<p><strong>User:</strong> {auth.user_email}</p>
<p><strong>Current code:</strong> {link.code}</p>
<p><strong>Desired vanity code:</strong> {request.desired_code}</p>
<p>To approve, create the vanity link in the <a href="https://gen.nomadkaraoke.com/admin/referrals">admin dashboard</a>.</p>
""",
text_content=f"Vanity URL request from {auth.user_email}: {request.desired_code} (current: {link.code})",
)
logger.info("Vanity URL request from %s: %s", auth.user_email, request.desired_code)
return {"ok": True, "message": "Request sent"}
@router.post("/me/flyer")
async def generate_flyer(
request: GenerateFlyerRequest,
auth=Depends(require_auth),
):
"""Generate a personalized referral flyer PDF."""
service = get_referral_service()
link = service.get_or_create_link(auth.user_email)
try:
flyer_service = get_flyer_service()
pdf_bytes = flyer_service.generate_pdf(
theme=request.theme,
referral_code=link.code,
discount_percent=link.discount_percent,
qr_data_url=request.qr_data_url,
)
except FlyerError as e:
raise HTTPException(status_code=400, detail=str(e))
return Response(
content=pdf_bytes,
media_type="application/pdf",
headers={
"Content-Disposition": 'attachment; filename="nomad-karaoke-referral-flyer.pdf"',
},
)
# ============================================================================
# Admin endpoints
# ============================================================================
@router.post("/admin/vanity")
async def create_vanity_link(
request: CreateReferralLinkRequest,
auth=Depends(require_admin),
):
"""Admin: create a vanity referral link."""
if not request.vanity_code:
raise HTTPException(status_code=400, detail="vanity_code is required")
service = get_referral_service()
success, link, message = service.create_vanity_link(
code=request.vanity_code,
owner_email=request.owner_email,
display_name=request.display_name,
custom_message=request.custom_message,
discount_percent=request.discount_percent,
kickback_percent=request.kickback_percent,
discount_duration_days=request.discount_duration_days,
earning_duration_days=request.earning_duration_days,
)
if not success:
raise HTTPException(status_code=400, detail=message)
return {"ok": True, "code": link.code, "message": message}
@router.get("/admin/links")
async def list_links(
limit: int = Query(50, ge=1, le=200),
offset: int = Query(0, ge=0),
auth=Depends(require_admin),
):
"""Admin: list all referral links."""
service = get_referral_service()
links = service.list_links(limit=limit, offset=offset)
return {
"links": [link.model_dump(mode="json") for link in links],
"count": len(links),
}
@router.post("/admin/apply-discount")
async def admin_apply_discount(
request: Request,
auth=Depends(require_admin),
):
"""Admin: apply a referral discount to any user, even without a referral link."""
from backend.services.user_service import get_user_service
body = await request.json()
user_email = body.get("email", "").lower()
discount_percent = body.get("discount_percent", 10)
duration_days = body.get("duration_days", 30)
referral_code = body.get("referral_code", "admin-grant")
if not user_email:
raise HTTPException(status_code=400, detail="Email is required")
user_service = get_user_service()
user = user_service.get_user(user_email)
if not user:
raise HTTPException(status_code=404, detail="User not found")
from datetime import datetime, timedelta
now = datetime.utcnow()
user_service.update_user(
user_email,
referred_by_code=referral_code,
referred_at=now,
referral_discount_expires_at=now + timedelta(days=duration_days),
)
# Create/ensure the Stripe coupon exists for this discount percent
service = get_referral_service()
service.get_or_create_stripe_coupon(discount_percent)
logger.info(f"Admin applied {discount_percent}% discount for {duration_days} days to {user_email}")
return {
"ok": True,
"message": f"Applied {discount_percent}% discount for {duration_days} days",
"discount_expires_at": (now + timedelta(days=duration_days)).isoformat(),
}
@router.put("/admin/links/{code}")
async def update_link(
code: str,
updates: UpdateReferralLinkRequest,
auth=Depends(require_admin),
):
"""Admin: update any referral link's settings."""
service = get_referral_service()
update_fields = {
k: v for k, v in updates.model_dump().items() if v is not None
}
if not update_fields:
return {"ok": True, "message": "No changes"}
success, message = service.update_link(code, **update_fields)
if not success:
raise HTTPException(status_code=404, detail=message)
return {"ok": True, "message": message}
@router.post("/admin/links/{code}/flyer")
async def admin_generate_flyer(
code: str,
request: GenerateFlyerRequest,
auth=Depends(require_admin),
):
"""Admin: generate a personalized referral flyer PDF for any code."""
service = get_referral_service()
link = service.get_link_by_code(code)
if not link:
raise HTTPException(status_code=404, detail=f"Referral link '{code}' not found")
try:
flyer_service = get_flyer_service()
pdf_bytes = flyer_service.generate_pdf(
theme=request.theme,
referral_code=link.code,
discount_percent=link.discount_percent,
qr_data_url=request.qr_data_url,
)
except FlyerError as e:
raise HTTPException(status_code=400, detail=str(e))
return Response(
content=pdf_bytes,
media_type="application/pdf",
headers={
"Content-Disposition": f'attachment; filename="nomad-karaoke-flyer-{link.code}.pdf"',
},
)
+201 -48
View File
@@ -19,7 +19,7 @@ import json
import os
import tempfile
from pathlib import Path
from typing import Dict, Any, Set, Tuple
from typing import Dict, Any, List, Optional, Set, Tuple
from fastapi import APIRouter, HTTPException, Request, Depends
from fastapi.responses import FileResponse, RedirectResponse, StreamingResponse
@@ -36,6 +36,7 @@ from backend.services.encoding_service import get_encoding_service
from backend.api.dependencies import require_auth, require_review_auth
from backend.services.auth_service import UserType
from backend.config import get_settings
from backend.i18n import t, get_locale_from_request
# LyricsTranscriber imports for preview generation
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
@@ -113,12 +114,12 @@ async def get_correction_data(
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=f"Job not ready for review (current status: {job.status})"
detail=t("en", "review.reviewNotReady", status=job.status)
)
# Check for updated corrections first (from previous review sessions where user edited lyrics)
@@ -139,7 +140,7 @@ async def get_correction_data(
if not storage.file_exists(corrections_gcs):
raise HTTPException(
status_code=404,
detail="Corrections data not found. Lyrics processing may not be complete."
detail=t("en", "review.correctionsNotFound")
)
# Download and return corrections data
@@ -224,7 +225,7 @@ async def get_correction_data(
except Exception as e:
logger.error(f"Job {job_id}: Error loading corrections: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error loading corrections: {str(e)}")
raise HTTPException(status_code=500, detail=t("en", "review.correctionsLoadFailed", error=str(e)))
@router.get("/{job_id}/audio/{audio_hash}")
@@ -260,11 +261,11 @@ async def _stream_audio(job_id: str):
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
audio_gcs_path = job.input_media_gcs_path
if not audio_gcs_path:
raise HTTPException(status_code=404, detail="Audio file not found")
raise HTTPException(status_code=404, detail=t("en", "review.audioNotFound"))
try:
transcoding = AudioTranscodingService()
@@ -274,7 +275,7 @@ async def _stream_audio(job_id: str):
except Exception as e:
logger.error(f"Job {job_id}: Error generating audio signed URL: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error serving audio: {str(e)}")
raise HTTPException(status_code=500, detail=t("en", "review.audioServeError", error=str(e)))
@router.post("/{job_id}/complete")
@@ -298,12 +299,12 @@ async def complete_review(
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=f"Job not in review state (current status: {job.status})"
detail=t("en", "review.reviewNotReady", status=job.status)
)
# === Require instrumental selection ===
@@ -311,7 +312,7 @@ async def complete_review(
if not instrumental_selection:
raise HTTPException(
status_code=400,
detail="instrumental_selection is required. Must be 'clean' or 'with_backing'."
detail=t("en", "review.instrumentalSelectionRequired")
)
valid_selections = ["clean", "with_backing"]
@@ -323,7 +324,7 @@ async def complete_review(
if instrumental_selection not in valid_selections:
raise HTTPException(
status_code=400,
detail=f"Invalid instrumental_selection. Must be one of: {valid_selections}"
detail=t("en", "review.invalidInstrumentalSelection", valid_selections=valid_selections)
)
try:
@@ -331,12 +332,16 @@ async def complete_review(
# (it's stored separately in state_data)
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
# Save updated corrections to GCS
corrections_gcs_path = f"jobs/{job_id}/lyrics/corrections_updated.json"
storage.upload_json(corrections_gcs_path, corrections_to_save)
job_manager.update_file_url(job_id, 'lyrics', 'corrections_updated', corrections_gcs_path)
logger.info(f"Job {job_id}: Saved updated corrections")
# Only write corrections_updated.json if there's actual correction data.
# Writing an empty dict causes KeyError downstream when render workers
# try to access updated_data["corrections"].
if corrections_to_save and "corrections" in corrections_to_save:
corrections_gcs_path = f"jobs/{job_id}/lyrics/corrections_updated.json"
storage.upload_json(corrections_gcs_path, corrections_to_save)
job_manager.update_file_url(job_id, 'lyrics', 'corrections_updated', corrections_gcs_path)
logger.info(f"Job {job_id}: Saved updated corrections")
else:
logger.info(f"Job {job_id}: No corrections data in request, skipping corrections_updated.json")
# === Store instrumental selection in state_data ===
# This will be used by render_video_worker to skip AWAITING_INSTRUMENTAL_SELECTION
@@ -380,7 +385,7 @@ async def complete_review(
raise
except Exception as e:
logger.error(f"Job {job_id}: Error completing review: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error completing review: {str(e)}")
raise HTTPException(status_code=500, detail=t("en", "review.reviewCompletedError", error=str(e)))
@router.post("/{job_id}/handlers")
@@ -396,7 +401,7 @@ async def update_handlers(
would require re-running correction.
"""
logger.info(f"Job {job_id}: Handler update requested (not implemented)")
return {"status": "success", "message": "Handler updates not yet implemented"}
return {"status": "success", "message": t("en", "review.handlersUpdateNotImplemented")}
@router.post("/{job_id}/add-lyrics")
@@ -416,19 +421,21 @@ async def add_lyrics(
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
# Job must be in review state to add lyrics
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=f"Job not in review state (current status: {job.status})"
detail=t("en", "review.reviewNotReady", status=job.status)
)
source = data.get("source", "").strip()
lyrics_text = data.get("lyrics", "").strip()
logger.info(f"Job {job_id}: Adding lyrics source '{source}' with {len(lyrics_text)} characters")
raw_force = data.get("force", False)
force = raw_force if isinstance(raw_force, bool) else str(raw_force).lower() == "true"
logger.info(f"Job {job_id}: Adding lyrics source '{source}' with {len(lyrics_text)} characters (force={force})")
# Use tracing and job_log_context for full observability
with create_span("add-lyrics", {"job_id": job_id, "source": source, "lyrics_length": len(lyrics_text)}) as span:
@@ -465,7 +472,8 @@ async def add_lyrics(
source=source,
lyrics_text=lyrics_text,
cache_dir=cache_dir,
logger=logger
logger=logger,
force=force,
)
add_span_event("correction_complete", {
"new_segments": len(updated_result.corrected_segments) if updated_result.corrected_segments else 0,
@@ -494,11 +502,156 @@ async def add_lyrics(
# ValueError from CorrectionOperations (e.g., duplicate source name)
logger.warning(f"Job {job_id}: Invalid add lyrics request: {e}")
span.set_attribute("error", str(e))
raise HTTPException(status_code=400, detail=str(e))
raise HTTPException(status_code=400, detail=t("en", "review.lyricsAddInvalidRequest", error=str(e)))
except Exception as e:
logger.error(f"Job {job_id}: Failed to add lyrics: {e}", exc_info=True)
span.set_attribute("error", str(e))
raise HTTPException(status_code=500, detail=f"Failed to add lyrics: {str(e)}")
raise HTTPException(status_code=500, detail=t("en", "review.lyricsAddError", error=str(e)))
@router.post("/{job_id}/search-lyrics")
async def search_lyrics(
job_id: str,
data: Dict[str, Any],
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
"""
Search for lyrics using an alternate artist/title and rerun correction.
Queries all configured lyrics providers (Genius, Spotify, Musixmatch, LRCLIB)
with the supplied artist and title, then runs the correction pipeline (which
includes the relevance filter). Sources that pass the filter are added to the
job's corrections.json and returned to the frontend.
Request body:
artist (str): Artist name to search.
title (str): Song title to search.
force_sources (list[str], optional): Provider names whose results should
bypass the relevance filter.
Response:
200 {"status": "success", "data": {...CorrectionData...}, "sources_added": [...],
"sources_rejected": {...}, "sources_not_found": [...]}
200 {"status": "no_results", "message": "...", "sources_rejected": {...},
"sources_not_found": [...]}
400 on invalid request / wrong job state
500 on internal error
"""
job_manager = JobManager()
storage = StorageService()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=t("en", "review.reviewNotReady", status=job.status)
)
artist = (data.get("artist") or "").strip()
title = (data.get("title") or "").strip()
force_sources: List[str] = data.get("force_sources") or []
if not artist or not title:
raise HTTPException(status_code=400, detail="artist and title are required")
logger.info(f"Job {job_id}: Searching lyrics for '{artist}' - '{title}' (force={force_sources})")
with create_span("search-lyrics", {"job_id": job_id, "artist": artist, "title": title}) as span:
with job_log_context(job_id, worker="search-lyrics"):
try:
with tempfile.TemporaryDirectory() as temp_dir:
# Download current corrections.json
with create_span("download-corrections") as download_span:
corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
corrections_path = os.path.join(temp_dir, "corrections.json")
storage.download_file(corrections_gcs, corrections_path)
download_span.set_attribute("gcs_path", corrections_gcs)
with open(corrections_path, "r", encoding="utf-8") as f:
original_data = json.load(f)
correction_result = CorrectionResult.from_dict(original_data)
add_span_event("corrections_loaded", {
"segments": len(correction_result.corrected_segments) if correction_result.corrected_segments else 0,
"reference_sources": len(correction_result.reference_lyrics) if correction_result.reference_lyrics else 0,
})
cache_dir = os.path.join(temp_dir, "cache")
os.makedirs(cache_dir, exist_ok=True)
with create_span("correction-operations-search-lyrics") as correction_span:
correction_span.set_attribute("artist", artist)
correction_span.set_attribute("title", title)
search_result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist=artist,
title=title,
cache_dir=cache_dir,
force_sources=force_sources,
logger=logger,
)
sources_added = search_result["sources_added"]
sources_rejected = search_result["sources_rejected"]
sources_not_found = search_result["sources_not_found"]
updated_result = search_result["updated_result"]
if not sources_added or updated_result is None:
logger.info(
f"Job {job_id}: No valid lyrics found via search "
f"(rejected={list(sources_rejected.keys())}, not_found={sources_not_found})"
)
span.set_attribute("success", False)
return {
"status": "no_results",
"message": t("en", "review.lyricsSearchNoResults"),
"sources_added": [],
"sources_rejected": sources_rejected,
"sources_not_found": sources_not_found,
}
# Add audio hash / job metadata for the frontend
audio_hash = _get_audio_hash(job_id)
if not updated_result.metadata:
updated_result.metadata = {}
updated_result.metadata["audio_hash"] = audio_hash
updated_result.metadata["artist"] = job.artist
updated_result.metadata["title"] = job.title
# Upload updated corrections back to GCS
with create_span("upload-corrections") as upload_span:
updated_data = updated_result.to_dict()
storage.upload_json(corrections_gcs, updated_data)
upload_span.set_attribute("gcs_path", corrections_gcs)
logger.info(
f"Job {job_id}: Search complete — added={sources_added}, "
f"rejected={list(sources_rejected.keys())}, not_found={sources_not_found}"
)
span.set_attribute("success", True)
span.set_attribute("sources_added", len(sources_added))
return {
"status": "success",
"data": updated_data,
"sources_added": sources_added,
"sources_rejected": sources_rejected,
"sources_not_found": sources_not_found,
}
except HTTPException:
raise
except ValueError as e:
logger.warning(f"Job {job_id}: Invalid search lyrics request: {e}")
span.set_attribute("error", str(e))
raise HTTPException(status_code=400, detail=t("en", "review.lyricsSearchInvalidRequest", error=str(e)))
except Exception as e:
logger.error(f"Job {job_id}: Failed to search lyrics: {e}", exc_info=True)
span.set_attribute("error", str(e))
raise HTTPException(status_code=500, detail=t("en", "review.lyricsSearchError", error=str(e)))
@router.post("/{job_id}/preview-video")
@@ -523,13 +676,13 @@ async def generate_preview_video(
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
# Job must be in review state to generate preview
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=f"Job not in review state (current status: {job.status})"
detail=t("en", "review.reviewNotReady", status=job.status)
)
# Check if GCE preview encoding is enabled
@@ -703,7 +856,7 @@ async def generate_preview_video(
span.set_attribute("error", str(e))
raise HTTPException(
status_code=500,
detail=f"Failed to generate preview video: {e}"
detail=t("en", "review.previewVideoGenerationError", error=str(e))
) from e
@@ -724,7 +877,7 @@ async def get_preview_video(
# Try standard path
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
if not storage.file_exists(preview_gcs_path):
raise HTTPException(status_code=404, detail="Preview video not found")
raise HTTPException(status_code=404, detail=t("en", "review.previewVideoNotFound"))
try:
# Download to temp file and stream
@@ -749,7 +902,7 @@ async def get_preview_video(
except Exception as e:
logger.error(f"Job {job_id}: Error streaming preview video: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error streaming preview video: {str(e)}")
raise HTTPException(status_code=500, detail=t("en", "review.previewVideoStreamError", error=str(e)))
@router.post("/{job_id}/v1/annotations")
@@ -789,7 +942,7 @@ async def submit_annotation(
except Exception as e:
logger.error(f"Job {job_id}: Error saving annotations: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail=t("en", "review.annotationSaveError", error=str(e)))
@router.get("/{job_id}/v1/annotations/stats")
@@ -830,7 +983,7 @@ async def get_instrumental_analysis(
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
# Get backing vocals analysis from state_data
backing_analysis = job.state_data.get('backing_vocals_analysis', {})
@@ -870,7 +1023,7 @@ async def get_instrumental_analysis(
"has_audible_content": backing_analysis.get('has_audible_content', False),
"total_duration_seconds": backing_analysis.get('total_duration_seconds', 0),
"audible_segments": backing_analysis.get('audible_segments', []),
"recommended_selection": backing_analysis.get('recommended_selection', 'with_backing'),
"recommended_selection": backing_analysis.get('recommended_selection', 'clean'),
"total_audible_duration_seconds": backing_analysis.get('total_audible_duration_seconds', 0),
"audible_percentage": backing_analysis.get('audible_percentage', 0),
"silence_threshold_db": backing_analysis.get('silence_threshold_db', -40),
@@ -898,7 +1051,7 @@ async def get_waveform_data(
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
# Get backing vocals path
stems = job.file_urls.get('stems', {})
@@ -909,7 +1062,7 @@ async def get_waveform_data(
backing_vocals_path = job.input_media_gcs_path
if not backing_vocals_path:
raise HTTPException(status_code=404, detail="No audio available for waveform")
raise HTTPException(status_code=404, detail=t("en", "review.waveformNoAudio"))
try:
analysis_service = AudioAnalysisService()
@@ -927,7 +1080,7 @@ async def get_waveform_data(
}
except Exception as e:
logger.error(f"Job {job_id}: Error generating waveform data: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error generating waveform: {str(e)}")
raise HTTPException(status_code=500, detail=t("en", "review.waveformGenerationError", error=str(e)))
# ============================================
@@ -959,11 +1112,11 @@ async def save_review_session(
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
correction_data = data.get("correction_data")
if not correction_data:
raise HTTPException(status_code=400, detail="correction_data is required")
raise HTTPException(status_code=400, detail=t("en", "review.sessionSaveError"))
# Compute hash for deduplication
data_json = json.dumps(correction_data, sort_keys=True, default=str)
@@ -1132,7 +1285,7 @@ async def save_audio_edit_session(
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
user_email = auth_info[0] if isinstance(auth_info, tuple) else ""
edit_data = data.get("edit_data", {})
@@ -1325,7 +1478,7 @@ async def get_input_audio_info(
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
if not job.input_media_gcs_path:
raise HTTPException(status_code=404, detail="No input audio available")
@@ -1432,7 +1585,7 @@ async def apply_audio_edit(
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
@@ -1529,7 +1682,7 @@ async def undo_audio_edit(
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
@@ -1576,7 +1729,7 @@ async def redo_audio_edit(
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
@@ -1632,7 +1785,7 @@ async def upload_audio_for_join(
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
@@ -1725,7 +1878,7 @@ async def submit_audio_edit(
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
+2 -1
View File
@@ -12,6 +12,7 @@ from fastapi import APIRouter, Query, Request
from backend.models.tenant import TenantConfigResponse, TenantPublicConfig
from backend.services.tenant_service import get_tenant_service
from backend.i18n import t, get_locale_from_request
logger = logging.getLogger(__name__)
@@ -115,6 +116,6 @@ async def get_tenant_asset(tenant_id: str, asset_name: str):
if not url:
from fastapi import HTTPException
raise HTTPException(status_code=404, detail="Asset not found")
raise HTTPException(status_code=404, detail=t("en", "tenant.assetNotFound"))
return RedirectResponse(url=url)
+18 -13
View File
@@ -9,10 +9,11 @@ before job creation.
import logging
from typing import Optional
from fastapi import APIRouter, HTTPException
from fastapi import APIRouter, HTTPException, Request
from backend.models.theme import ThemeDetailResponse, ThemesListResponse
from backend.services.theme_service import get_theme_service
from backend.i18n import t, get_locale_from_request
logger = logging.getLogger(__name__)
@@ -20,7 +21,7 @@ router = APIRouter(prefix="/themes", tags=["themes"])
@router.get("", response_model=ThemesListResponse)
async def list_themes() -> ThemesListResponse:
async def list_themes(request: Request) -> ThemesListResponse:
"""
List all available themes.
@@ -29,6 +30,7 @@ async def list_themes() -> ThemesListResponse:
This endpoint is public and does not require authentication.
"""
locale = get_locale_from_request(request)
try:
theme_service = get_theme_service()
themes = theme_service.list_themes()
@@ -37,12 +39,12 @@ async def list_themes() -> ThemesListResponse:
logger.error(f"Error listing themes: {e}")
raise HTTPException(
status_code=500,
detail="Failed to load themes"
detail=t(locale, "themes.themesLoadError")
)
@router.get("/{theme_id}", response_model=ThemeDetailResponse)
async def get_theme(theme_id: str) -> ThemeDetailResponse:
async def get_theme(theme_id: str, request: Request) -> ThemeDetailResponse:
"""
Get detailed information about a specific theme.
@@ -58,6 +60,7 @@ async def get_theme(theme_id: str) -> ThemeDetailResponse:
Raises:
404: Theme not found
"""
locale = get_locale_from_request(request)
try:
theme_service = get_theme_service()
theme = theme_service.get_theme(theme_id)
@@ -65,7 +68,7 @@ async def get_theme(theme_id: str) -> ThemeDetailResponse:
if theme is None:
raise HTTPException(
status_code=404,
detail=f"Theme not found: {theme_id}"
detail=t(locale, "themes.themeNotFound", theme_id=theme_id)
)
return ThemeDetailResponse(theme=theme)
@@ -75,12 +78,12 @@ async def get_theme(theme_id: str) -> ThemeDetailResponse:
logger.error(f"Error getting theme {theme_id}: {e}")
raise HTTPException(
status_code=500,
detail="Failed to load theme"
detail=t(locale, "themes.themeLoadError")
)
@router.get("/{theme_id}/preview")
async def get_theme_preview(theme_id: str) -> dict:
async def get_theme_preview(theme_id: str, request: Request) -> dict:
"""
Get a signed URL for the theme's preview image.
@@ -96,20 +99,21 @@ async def get_theme_preview(theme_id: str) -> dict:
Raises:
404: Theme not found or no preview available
"""
locale = get_locale_from_request(request)
try:
theme_service = get_theme_service()
if not theme_service.theme_exists(theme_id):
raise HTTPException(
status_code=404,
detail=f"Theme not found: {theme_id}"
detail=t(locale, "themes.themeNotFound", theme_id=theme_id)
)
theme = theme_service.get_theme(theme_id)
if theme is None or theme.preview_url is None:
raise HTTPException(
status_code=404,
detail=f"No preview available for theme: {theme_id}"
detail=t(locale, "themes.previewNotAvailable", theme_id=theme_id)
)
return {"preview_url": theme.preview_url}
@@ -119,12 +123,12 @@ async def get_theme_preview(theme_id: str) -> dict:
logger.error(f"Error getting preview for theme {theme_id}: {e}")
raise HTTPException(
status_code=500,
detail="Failed to load theme preview"
detail=t(locale, "themes.previewLoadError")
)
@router.get("/{theme_id}/youtube-description")
async def get_theme_youtube_description(theme_id: str) -> dict:
async def get_theme_youtube_description(theme_id: str, request: Request) -> dict:
"""
Get the YouTube description template for a theme.
@@ -141,13 +145,14 @@ async def get_theme_youtube_description(theme_id: str) -> dict:
Raises:
404: Theme not found
"""
locale = get_locale_from_request(request)
try:
theme_service = get_theme_service()
if not theme_service.theme_exists(theme_id):
raise HTTPException(
status_code=404,
detail=f"Theme not found: {theme_id}"
detail=t(locale, "themes.youtubeDescriptionNotFound", theme_id=theme_id)
)
description = theme_service.get_youtube_description(theme_id)
@@ -158,5 +163,5 @@ async def get_theme_youtube_description(theme_id: str) -> dict:
logger.error(f"Error getting YouTube description for theme {theme_id}: {e}")
raise HTTPException(
status_code=500,
detail="Failed to load YouTube description"
detail=t(locale, "themes.youtubeDescriptionLoadError")
)
+221 -52
View File
@@ -10,6 +10,7 @@ Handles:
"""
import hashlib
import logging
import threading
from datetime import datetime
from typing import Optional, Tuple
@@ -34,6 +35,7 @@ def _mask_email(email: str) -> str:
from fastapi import APIRouter, HTTPException, Depends, Request, Header
from pydantic import BaseModel, EmailStr
from backend.i18n import t, get_locale_from_request
from backend.services.email_validation_service import get_email_validation_service
from backend.models.user import (
UserRole,
@@ -62,6 +64,52 @@ from backend.services.auth_service import AuthResult
from backend.api.routes.file_upload import _prepare_theme_for_job
from backend.services.auth_service import UserType
from backend.utils.test_data import is_test_email
def _build_user_public(user, role_override=None, feedback_eligible=False):
"""Build UserPublic with computed referral discount status."""
from datetime import datetime
has_discount = False
discount_percent = None
discount_expires = None
if user.referral_discount_expires_at:
expires = user.referral_discount_expires_at
if isinstance(expires, datetime):
# Firestore returns timezone-aware datetimes; ensure comparison is compatible
now = datetime.utcnow()
if expires.tzinfo is not None:
now = now.replace(tzinfo=expires.tzinfo)
has_discount = expires > now
discount_expires = expires.isoformat() if has_discount else None
if has_discount and user.referred_by_code:
# Look up the discount percent from the referral link
try:
from backend.services.referral_service import get_referral_service
link = get_referral_service().get_link_by_code(user.referred_by_code)
if link:
discount_percent = link.discount_percent
except Exception:
discount_percent = 10 # default fallback
return UserPublic(
email=user.email,
role=role_override or user.role,
credits=user.credits,
display_name=user.display_name,
total_jobs_created=user.total_jobs_created,
total_jobs_completed=user.total_jobs_completed,
tenant_id=getattr(user, 'tenant_id', None),
feedback_eligible=feedback_eligible,
total_spent=getattr(user, 'total_spent', 0),
referral_code=user.referral_code,
has_active_referral_discount=has_discount,
referral_discount_percent=discount_percent,
referral_discount_expires_at=discount_expires,
referred_by_code=user.referred_by_code,
)
from backend.services.youtube_download_service import (
get_youtube_download_service,
YouTubeDownloadError,
@@ -132,6 +180,32 @@ class LogoutResponse(BaseModel):
# Magic Link Authentication
# =============================================================================
def _precompute_credit_eval(token: str, email: str) -> None:
"""Run credit evaluation in background and store result on magic link doc.
Called in a background thread after sending a magic link for new users.
If the user clicks the link before this finishes, verify_magic_link falls
back to inline evaluation (same as before this optimization).
"""
try:
from backend.services.credit_evaluation_service import get_credit_evaluation_service
from backend.services.user_service import get_user_service, MAGIC_LINKS_COLLECTION
eval_service = get_credit_evaluation_service()
evaluation = eval_service.evaluate(email, "welcome")
user_service = get_user_service()
user_service.db.collection(MAGIC_LINKS_COLLECTION).document(token).update({
"credit_eval_decision": evaluation.decision,
"credit_eval_reasoning": evaluation.reasoning,
"credit_eval_error": evaluation.error,
})
logger.info(f"Pre-computed credit eval for {_mask_email(email)}: {evaluation.decision}")
except Exception:
logger.exception(f"Background credit eval failed for {_mask_email(email)} — verify will compute inline")
@router.post("/auth/magic-link", response_model=SendMagicLinkResponse)
async def send_magic_link(
request: SendMagicLinkRequest,
@@ -155,18 +229,20 @@ async def send_magic_link(
# (done before email service check so we can reject without needing email config)
email_validation = get_email_validation_service()
locale = get_locale_from_request(http_request)
if email_validation.is_disposable_domain(email):
logger.warning(f"Blocked disposable email signup attempt: {_mask_email(email)}")
raise HTTPException(
status_code=422,
detail="disposable_email_not_allowed"
detail=t(locale, "users.disposableEmailBlocked")
)
if email_validation.is_email_blocked(email):
logger.warning(f"Blocked email signup attempt: {_mask_email(email)}")
return SendMagicLinkResponse(
status="success",
message="If this email is registered, you will receive a sign-in link shortly."
message=t(locale, "users.magicLinkSent")
)
ip_address = get_client_ip(http_request)
@@ -174,7 +250,7 @@ async def send_magic_link(
logger.warning(f"Blocked IP signup attempt: {ip_address}")
return SendMagicLinkResponse(
status="success",
message="If this email is registered, you will receive a sign-in link shortly."
message=t(locale, "users.magicLinkSent")
)
# Per-IP and per-fingerprint signup rate limit (only for new users)
@@ -190,7 +266,7 @@ async def send_magic_link(
# Silent reject (anti-enumeration)
return SendMagicLinkResponse(
status="success",
message="If this email is registered, you will receive a sign-in link shortly."
message=t(locale, "users.magicLinkSent")
)
# Check if email service is configured
@@ -198,7 +274,7 @@ async def send_magic_link(
logger.error("Email service not configured - cannot send magic links")
raise HTTPException(
status_code=503,
detail="Email service is not available. Please contact support."
detail=t(locale, "users.emailServiceNotConfigured")
)
# Get tenant context from middleware
@@ -212,7 +288,7 @@ async def send_magic_link(
# Return success anyway to prevent email enumeration
return SendMagicLinkResponse(
status="success",
message="If this email is registered, you will receive a sign-in link shortly."
message=t(locale, "users.magicLinkSent")
)
# Get client info for security logging (ip_address already extracted above for blocklist check)
@@ -225,6 +301,7 @@ async def send_magic_link(
user_agent=user_agent,
tenant_id=tenant_id,
device_fingerprint=device_fingerprint,
referral_code=request.referral_code,
)
# Get tenant-specific email configuration
@@ -243,6 +320,8 @@ async def send_magic_link(
sender_email=sender_email,
tenant_frontend_url=tenant_frontend_url,
tenant_name=tenant_name,
locale=locale,
referral_code=request.referral_code,
)
if not sent:
@@ -250,9 +329,21 @@ async def send_magic_link(
# Don't reveal failure to prevent email enumeration
# Still return success
# Pre-compute credit evaluation in background for new users.
# By the time they check their email and click the link, the decision
# will be ready and verification will be instant.
# Skip for test emails — they get auto-granted without evaluation.
if existing_user is None and not is_test_email(email):
thread = threading.Thread(
target=_precompute_credit_eval,
args=(magic_link.token, email),
daemon=True,
)
thread.start()
return SendMagicLinkResponse(
status="success",
message="If this email is registered, you will receive a sign-in link shortly."
message=t(locale, "users.magicLinkSent")
)
@@ -269,9 +360,11 @@ async def verify_magic_link(
Returns a session token that should be stored and used for subsequent requests.
The session will be associated with the tenant from the magic link.
"""
locale = get_locale_from_request(http_request)
# Reject empty tokens early to avoid invalid Firestore document paths
if not token or not token.strip():
raise HTTPException(status_code=401, detail="Invalid token")
raise HTTPException(status_code=401, detail=t(locale, "users.invalidToken"))
# Get client info
ip_address = get_client_ip(http_request)
@@ -295,12 +388,23 @@ async def verify_magic_link(
success, user, message = user_service.verify_magic_link(token)
if not success or not user:
raise HTTPException(status_code=401, detail=message)
raise HTTPException(status_code=401, detail=t(locale, "users.verifyError", message=message))
# Grant welcome credits on first verification (with AI abuse evaluation)
# Use pre-computed evaluation from magic link if available (computed at send time)
precomputed_eval = None
if magic_link_doc.exists:
precomputed_eval = {
k: magic_link_data.get(k)
for k in ("credit_eval_decision", "credit_eval_reasoning", "credit_eval_error")
if magic_link_data.get(k) is not None
} or None
credits_granted = 0
credit_status = "not_applicable" # returning user, not first login
granted, credit_status = user_service.grant_welcome_credits_if_eligible(user.email)
granted, credit_status = user_service.grant_welcome_credits_if_eligible(
user.email, precomputed_eval=precomputed_eval,
)
if granted:
credits_granted = user_service.NEW_USER_FREE_CREDITS
logger.info(f"Granted {credits_granted} welcome credits to {_mask_email(user.email)}")
@@ -309,6 +413,35 @@ async def verify_magic_link(
elif credit_status == "denied":
logger.info(f"Welcome credits denied for {_mask_email(user.email)}")
# Referral attribution: try header first (cookie path), then magic link token (email path), then URL param
referral_code = (
http_request.headers.get("x-referral-code")
or (magic_link_data.get("referral_code") if magic_link_doc.exists else None)
)
if referral_code and not user.referred_by_code:
try:
from backend.services.referral_service import get_referral_service
referral_svc = get_referral_service()
attr_success, attr_msg = referral_svc.attribute_referral(
referred_email=user.email,
referral_code=referral_code,
)
if attr_success:
attr_data = referral_svc.get_attribution_data(referral_code)
if attr_data:
user_service.update_user(user.email, **attr_data)
user = user_service.get_user(user.email) # Refresh to include referral data
logger.info(f"Referral attributed for {_mask_email(user.email)} via code '{referral_code}'")
except Exception as ref_err:
logger.warning(f"Referral attribution failed for {_mask_email(user.email)}: {ref_err}")
# Persist user's locale preference (from Accept-Language header)
if locale and locale != (user.locale or "en"):
try:
user_service.update_user(user.email, locale=locale)
except Exception:
pass # Non-critical — don't block login
# 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
session = user_service.create_session(
@@ -321,18 +454,10 @@ async def verify_magic_link(
# Send welcome email to first-time users
if is_first_login:
email_service.send_welcome_email(user.email, user.credits)
email_service.send_welcome_email(user.email, user.credits, locale=locale)
# Return user info with tenant_id
user_public = UserPublic(
email=user.email,
role=user.role,
credits=user.credits,
display_name=user.display_name,
total_jobs_created=user.total_jobs_created,
total_jobs_completed=user.total_jobs_completed,
tenant_id=user.tenant_id,
)
user_public = _build_user_public(user)
# Resolve tenant subdomain for cross-domain redirect safety
tenant_subdomain = None
@@ -347,7 +472,7 @@ async def verify_magic_link(
status="success",
session_token=session.token,
user=user_public,
message="Successfully signed in",
message=t(locale, "users.magicLinkSuccess"),
tenant_subdomain=tenant_subdomain,
credits_granted=credits_granted,
credit_status=credit_status,
@@ -356,21 +481,23 @@ async def verify_magic_link(
@router.post("/auth/logout", response_model=LogoutResponse)
async def logout(
request: Request,
authorization: Optional[str] = Header(None),
user_service: UserService = Depends(get_user_service),
):
"""
Logout and invalidate the current session.
"""
locale = get_locale_from_request(request)
if not authorization:
return LogoutResponse(status="success", message="Already logged out")
return LogoutResponse(status="success", message=t(locale, "users.logoutSuccess"))
# Extract token from "Bearer <token>"
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
user_service.revoke_session(token)
return LogoutResponse(status="success", message="Successfully logged out")
return LogoutResponse(status="success", message=t(locale, "users.logoutSuccess"))
# =============================================================================
@@ -379,6 +506,7 @@ async def logout(
@router.get("/me", response_model=UserProfileResponse)
async def get_current_user(
request: Request,
authorization: Optional[str] = Header(None),
user_service: UserService = Depends(get_user_service),
):
@@ -387,10 +515,11 @@ async def get_current_user(
Requires a valid session token or admin token.
"""
locale = get_locale_from_request(request)
from backend.services.auth_service import get_auth_service
if not authorization:
raise HTTPException(status_code=401, detail="Not authenticated")
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
# Extract token
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
@@ -406,13 +535,9 @@ async def get_current_user(
user.total_jobs_completed >= 2
and not user.has_submitted_feedback
)
user_public = UserPublic(
email=user.email,
role=user.role if not auth_result.is_admin else UserRole.ADMIN,
credits=user.credits,
display_name=user.display_name,
total_jobs_created=user.total_jobs_created,
total_jobs_completed=user.total_jobs_completed,
user_public = _build_user_public(
user,
role_override=UserRole.ADMIN if auth_result.is_admin else None,
feedback_eligible=feedback_eligible,
)
return UserProfileResponse(user=user_public, has_session=True)
@@ -421,21 +546,13 @@ async def get_current_user(
valid, user, message = user_service.validate_session(token)
if not valid or not user:
raise HTTPException(status_code=401, detail=message)
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
feedback_eligible = (
user.total_jobs_completed >= 2
and not user.has_submitted_feedback
)
user_public = UserPublic(
email=user.email,
role=user.role,
credits=user.credits,
display_name=user.display_name,
total_jobs_created=user.total_jobs_created,
total_jobs_completed=user.total_jobs_completed,
feedback_eligible=feedback_eligible,
)
user_public = _build_user_public(user, feedback_eligible=feedback_eligible)
return UserProfileResponse(user=user_public, has_session=True)
@@ -479,9 +596,21 @@ async def create_checkout(
if not stripe_service.is_configured():
raise HTTPException(status_code=503, detail="Payment processing is not available")
# Check for referral discount
referral_coupon_id = None
try:
from backend.services.referral_service import get_referral_service
referral_svc = get_referral_service()
discount_info = referral_svc.get_discount_for_checkout(request.email)
if discount_info:
referral_coupon_id = discount_info["coupon_id"]
except Exception as ref_err:
logger.warning(f"Referral discount lookup failed: {ref_err}")
success, checkout_url, message = stripe_service.create_checkout_session(
package_id=request.package_id,
user_email=request.email,
coupon_id=referral_coupon_id,
)
if not success or not checkout_url:
@@ -950,6 +1079,25 @@ async def stripe_webhook(
# Send confirmation email
email_service.send_credits_added(user_email, credits, new_balance)
logger.info(f"Added {credits} credits to {user_email}, new balance: {new_balance}")
# Record referral earning if applicable
try:
from backend.services.referral_service import get_referral_service
referral_svc = get_referral_service()
amount_charged = session.get("amount_total", 0)
if amount_charged > 0:
earning_result = referral_svc.record_earning(
referred_email=user_email,
stripe_session_id=session_id,
purchase_amount_cents=amount_charged,
)
if earning_result:
logger.info(
f"Referral earning: ${earning_result['earning_amount_cents'] / 100:.2f} "
f"for {earning_result['referrer_email']}"
)
except Exception as ref_err:
logger.warning(f"Referral earning recording failed: {ref_err}")
else:
logger.error(f"Failed to add credits: {credit_msg}")
@@ -1094,6 +1242,7 @@ async def stripe_webhook(
@router.get("/feedback/eligibility", response_model=FeedbackEligibilityResponse)
async def check_feedback_eligibility(
request: Request,
authorization: Optional[str] = Header(None),
user_service: UserService = Depends(get_user_service),
):
@@ -1102,8 +1251,9 @@ async def check_feedback_eligibility(
Eligible if: total_jobs_completed >= 2 AND has not already submitted feedback.
"""
locale = get_locale_from_request(request)
if not authorization:
raise HTTPException(status_code=401, detail="Authentication required")
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
@@ -1118,7 +1268,7 @@ async def check_feedback_eligibility(
else:
valid, user, message = user_service.validate_session(token)
if not valid or not user:
raise HTTPException(status_code=401, detail=message)
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
eligible = user.total_jobs_completed >= 2 and not user.has_submitted_feedback
@@ -1132,6 +1282,7 @@ async def check_feedback_eligibility(
@router.post("/feedback", response_model=UserFeedbackResponse)
async def submit_user_feedback(
http_request: Request,
request: UserFeedbackRequest,
authorization: Optional[str] = Header(None),
user_service: UserService = Depends(get_user_service),
@@ -1143,8 +1294,9 @@ async def submit_user_feedback(
not have already submitted feedback. At least one text field
must have >50 characters.
"""
locale = get_locale_from_request(http_request)
if not authorization:
raise HTTPException(status_code=401, detail="Authentication required")
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
@@ -1159,20 +1311,20 @@ async def submit_user_feedback(
else:
valid, user, message = user_service.validate_session(token)
if not valid or not user:
raise HTTPException(status_code=401, detail=message)
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
# Check eligibility: must have completed 2+ jobs
if user.total_jobs_completed < 2:
raise HTTPException(
status_code=400,
detail="You need to complete at least 2 karaoke videos before submitting feedback."
detail=t(locale, "users.feedbackNotEligible")
)
# Check if already submitted
if user.has_submitted_feedback:
raise HTTPException(
status_code=400,
detail="You have already submitted feedback. Thank you!"
detail=t(locale, "users.feedbackNotEligible")
)
# Validate: at least one text field has >50 characters
@@ -1340,6 +1492,10 @@ class UserDetailResponse(BaseModel):
device_fingerprint: Optional[str] = None
welcome_credits_granted: bool = False
has_submitted_feedback: bool = False
# Referral fields
referred_by_code: Optional[str] = None
referral_discount_expires_at: Optional[str] = None
referral_code: Optional[str] = None
# Recent session details (IP, user agent, fingerprint)
recent_sessions: list[dict] = []
@@ -1445,12 +1601,14 @@ async def list_users(
@router.get("/admin/users/{email}/detail", response_model=UserDetailResponse)
async def get_user_detail(
email: str,
request: Request,
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
"""
Get detailed user information including credit history and recent jobs (admin only).
"""
locale = get_locale_from_request(request)
from google.cloud import firestore
from google.cloud.firestore_v1 import FieldFilter
from urllib.parse import unquote
@@ -1460,7 +1618,7 @@ async def get_user_detail(
user = user_service.get_user(email)
if not user:
raise HTTPException(status_code=404, detail="User not found")
raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound"))
db = user_service.db
@@ -1533,6 +1691,9 @@ async def get_user_detail(
device_fingerprint=user.device_fingerprint,
welcome_credits_granted=user.welcome_credits_granted,
has_submitted_feedback=user.has_submitted_feedback,
referred_by_code=user.referred_by_code,
referral_discount_expires_at=user.referral_discount_expires_at.isoformat() if user.referral_discount_expires_at and hasattr(user.referral_discount_expires_at, 'isoformat') else str(user.referral_discount_expires_at) if user.referral_discount_expires_at else None,
referral_code=user.referral_code,
recent_sessions=active_sessions,
)
@@ -1577,18 +1738,20 @@ async def add_credits_to_user(
@router.post("/admin/users/{email}/disable")
async def disable_user(
email: str,
request: Request,
auth_data: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
"""
Disable a user account (admin only).
"""
locale = get_locale_from_request(request)
admin_id = auth_data.user_email or "admin:unknown"
success = user_service.disable_user(email, admin_email=admin_id)
if not success:
raise HTTPException(status_code=404, detail="User not found")
raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound"))
return {"status": "success", "message": f"User {email} has been disabled"}
@@ -1596,18 +1759,20 @@ async def disable_user(
@router.post("/admin/users/{email}/enable")
async def enable_user(
email: str,
request: Request,
auth_data: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
"""
Enable a user account (admin only).
"""
locale = get_locale_from_request(request)
admin_id = auth_data.user_email or "admin:unknown"
success = user_service.enable_user(email, admin_email=admin_id)
if not success:
raise HTTPException(status_code=404, detail="User not found")
raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound"))
return {"status": "success", "message": f"User {email} has been enabled"}
@@ -1615,6 +1780,7 @@ async def enable_user(
@router.delete("/admin/users/{email}")
async def delete_user(
email: str,
request: Request,
auth_data: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
@@ -1623,6 +1789,7 @@ async def delete_user(
Jobs are NOT deleted - they remain as historical records.
"""
locale = get_locale_from_request(request)
admin_id = auth_data.user_email or "admin:unknown"
try:
@@ -1631,7 +1798,7 @@ async def delete_user(
raise HTTPException(status_code=400, detail=str(e))
if not success:
raise HTTPException(status_code=404, detail="User not found")
raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound"))
return {"status": "success", "message": f"User {email} has been deleted"}
@@ -1640,18 +1807,20 @@ async def delete_user(
async def set_user_role(
email: str,
role: UserRole,
request: Request,
auth_data: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
"""
Set a user's role (admin only).
"""
locale = get_locale_from_request(request)
admin_id = auth_data.user_email or "admin:unknown"
success = user_service.set_user_role(email, role, admin_email=admin_id)
if not success:
raise HTTPException(status_code=404, detail="User not found")
raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound"))
return {"status": "success", "message": f"User {email} role set to {role.value}"}
+35
View File
@@ -0,0 +1,35 @@
# Cloud Build config for GPU base image
#
# Builds the CUDA + PyTorch + models base image used by the audio worker.
# This image is large (~10GB) so builds take 15-30 minutes.
#
# Trigger manually:
# gcloud builds submit --config=backend/cloudbuild-gpu-base.yaml --project=nomadkaraoke --timeout=3600s
#
# The app-layer Dockerfile uses this as its BASE_IMAGE for audio worker deploys.
steps:
- name: 'gcr.io/cloud-builders/docker'
args:
- 'build'
- '-f'
- 'backend/Dockerfile.gpu-base'
- '-t'
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:latest'
- '-t'
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:$BUILD_ID'
- '--build-arg'
- 'BUILD_DATE=$_BUILD_DATE'
- '--build-arg'
- 'BUILD_ID=$BUILD_ID'
- '.'
images:
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:latest'
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:$BUILD_ID'
timeout: '3600s'
options:
machineType: 'E2_HIGHCPU_32'
diskSizeGb: 100
+4
View File
@@ -32,6 +32,10 @@ class Settings(BaseSettings):
# Authentication
admin_tokens: Optional[str] = os.getenv("ADMIN_TOKENS") # Comma-separated list
scheduler_service_account: str = os.getenv(
"SCHEDULER_SERVICE_ACCOUNT",
"karaoke-backend@nomadkaraoke.iam.gserviceaccount.com"
)
# Application
environment: str = os.getenv("ENVIRONMENT", "development")
+99
View File
@@ -0,0 +1,99 @@
"""
Lightweight i18n utility for backend translations.
Usage:
from backend.i18n import t, get_locale_from_request, SUPPORTED_LOCALES
# In a route handler:
locale = get_locale_from_request(request)
message = t(locale, "auth.userNotFound")
message = t(locale, "jobs.notFound", job_id="abc123")
"""
import json
from functools import lru_cache
from pathlib import Path
from typing import Any
from starlette.requests import Request
SUPPORTED_LOCALES = ("en", "es", "de")
DEFAULT_LOCALE = "en"
TRANSLATIONS_DIR = Path(__file__).parent / "translations"
@lru_cache(maxsize=len(SUPPORTED_LOCALES))
def _load_translations(locale: str) -> dict[str, Any]:
"""Load and cache translation file for a locale."""
path = TRANSLATIONS_DIR / f"{locale}.json"
if not path.exists():
if locale != DEFAULT_LOCALE:
return _load_translations(DEFAULT_LOCALE)
return {}
with open(path, encoding="utf-8") as f:
result: dict[str, Any] = json.load(f)
return result
def t(locale: str, key: str, **kwargs: Any) -> str:
"""Get a translated string by dotted key path.
Args:
locale: Language code (en, es, de)
key: Dotted path like "auth.userNotFound" or "emails.magicLink.subject"
**kwargs: Interpolation variables (e.g., job_id="abc123")
Returns:
Translated string with variables interpolated, or the key itself if not found.
"""
if locale not in SUPPORTED_LOCALES:
locale = DEFAULT_LOCALE
translations = _load_translations(locale)
# Walk the dotted path
value: Any = translations
for part in key.split("."):
if isinstance(value, dict) and part in value:
value = value[part]
else:
# Key not found — fall back to English
if locale != DEFAULT_LOCALE:
return t(DEFAULT_LOCALE, key, **kwargs)
return key # Return the key itself as last resort
if not isinstance(value, str):
return key
result: str = value
# Interpolate variables
if kwargs:
try:
result = result.format(**kwargs)
except KeyError:
pass # Missing variable — return template as-is
return result
def get_locale_from_request(request: Request) -> str:
"""Extract locale from Accept-Language header.
Returns the first supported locale found, or DEFAULT_LOCALE.
"""
accept_lang = request.headers.get("accept-language", "")
# Simple parsing — Accept-Language can be "de", "de-DE", "en-US,en;q=0.9,de;q=0.8"
for part in accept_lang.split(","):
lang = part.split(";")[0].strip().split("-")[0].lower()
if lang in SUPPORTED_LOCALES:
return lang
return DEFAULT_LOCALE
def get_locale_prefix(locale: str) -> str:
"""Get URL locale prefix for frontend URLs (e.g., '/en', '/es')."""
if locale not in SUPPORTED_LOCALES:
locale = DEFAULT_LOCALE
return f"/{locale}"
+6 -2
View File
@@ -159,6 +159,8 @@ app.include_router(auth.router, prefix="/api") # OAuth credential management
app.include_router(audio_search.router, prefix="/api") # Audio search (artist+title mode)
app.include_router(themes.router, prefix="/api") # Theme selection for styles
app.include_router(users.router, prefix="/api") # User auth, credits, and Stripe webhooks
from backend.api.routes import referrals
app.include_router(referrals.router, prefix="/api") # Referral links and payouts
app.include_router(admin.router, prefix="/api") # Admin dashboard and management
app.include_router(rate_limits.router, prefix="/api") # Rate limits admin management
app.include_router(push.router, prefix="/api") # Push notification subscription management
@@ -170,18 +172,20 @@ app.include_router(tenant.router) # Tenant/white-label configuration (no /api p
from fastapi import Request
from fastapi.responses import JSONResponse
from backend.exceptions import InsufficientCreditsError
from backend.i18n import t, get_locale_from_request
@app.exception_handler(InsufficientCreditsError)
async def insufficient_credits_exception_handler(request: Request, exc: InsufficientCreditsError):
"""Handle insufficient credits errors with 402 Payment Required status."""
locale = get_locale_from_request(request)
return JSONResponse(
status_code=402,
content={
"detail": exc.message,
"detail": t(locale, "errors.insufficientCredits"),
"credits_available": exc.credits_available,
"credits_required": exc.credits_required,
"buy_url": "/#pricing",
"buy_url": t(locale, "errors.insufficientCreditsBuyUrl"),
},
)
+178
View File
@@ -0,0 +1,178 @@
"""
Referral system models.
Supports:
- Referral link creation and management
- Earnings tracking from referred purchases
- Payout processing via Stripe Connect
- API request/response shapes for referral endpoints
"""
from datetime import datetime
from typing import Optional, List
from pydantic import BaseModel, Field
# ============================================================================
# Firestore Document Models
# ============================================================================
class ReferralLinkStats(BaseModel):
"""Aggregated statistics for a referral link."""
clicks: int = 0
signups: int = 0
purchases: int = 0
total_earned_cents: int = 0
class ReferralLink(BaseModel):
"""
Referral link stored in Firestore.
Each user can have one referral link. Vanity links use a custom code
(e.g., "karaoke-king") while standard links use a generated code.
"""
code: str # Unique referral code (URL slug)
owner_email: str # Email of the referrer
display_name: Optional[str] = None # Public name shown on interstitial
custom_message: Optional[str] = None # Optional message on interstitial
# Reward configuration
discount_percent: int = 10 # Discount for referred user
kickback_percent: int = 20 # Earnings for referrer
discount_duration_days: int = 30 # How long the discount lasts
earning_duration_days: int = 365 # How long referrer earns from this link
# Stripe
stripe_coupon_id: Optional[str] = None # Stripe coupon for this link
# Flags
is_vanity: bool = False # Custom vanity code vs generated
enabled: bool = True # Can be disabled without deleting
# Timestamps
created_at: datetime = Field(default_factory=datetime.utcnow)
updated_at: datetime = Field(default_factory=datetime.utcnow)
# Aggregated stats
stats: ReferralLinkStats = Field(default_factory=ReferralLinkStats)
class ReferralEarning(BaseModel):
"""
Record of a single earning from a referred purchase.
Created when a referred user completes a Stripe checkout.
"""
id: str
referrer_email: str
referred_email: str
referral_code: str
stripe_session_id: str
purchase_amount_cents: int
earning_amount_cents: int
status: str = "pending" # pending, paid, cancelled
created_at: datetime = Field(default_factory=datetime.utcnow)
paid_at: Optional[datetime] = None
payout_id: Optional[str] = None
class ReferralPayout(BaseModel):
"""
Record of a payout to a referrer via Stripe Connect.
Groups multiple earnings into a single transfer.
"""
id: str
referrer_email: str
stripe_transfer_id: str
amount_cents: int
earnings_included: List[str] # List of ReferralEarning IDs
status: str = "processing" # processing, completed, failed
created_at: datetime = Field(default_factory=datetime.utcnow)
# ============================================================================
# API Request Models
# ============================================================================
class CreateReferralLinkRequest(BaseModel):
"""Admin request to create a vanity referral link."""
vanity_code: Optional[str] = None
owner_email: str
display_name: Optional[str] = None
custom_message: Optional[str] = None
discount_percent: int = 10
kickback_percent: int = 20
discount_duration_days: int = 30
earning_duration_days: int = 365
class UpdateReferralLinkRequest(BaseModel):
"""Request to update a referral link (user: name/message only, admin: all fields)."""
display_name: Optional[str] = None
custom_message: Optional[str] = None
discount_percent: Optional[int] = None
kickback_percent: Optional[int] = None
discount_duration_days: Optional[int] = None
earning_duration_days: Optional[int] = None
enabled: Optional[bool] = None
# ============================================================================
# API Response Models
# ============================================================================
class ReferralLinkResponse(BaseModel):
"""Public referral link information."""
code: str
owner_email: str
display_name: Optional[str] = None
custom_message: Optional[str] = None
discount_percent: int
kickback_percent: int
is_vanity: bool
enabled: bool
stats: ReferralLinkStats
created_at: datetime
class ReferralEarningResponse(BaseModel):
"""Public earning information (for referrer dashboard)."""
id: str
referred_email: str
referral_code: str
purchase_amount_cents: int
earning_amount_cents: int
status: str
created_at: datetime
paid_at: Optional[datetime] = None
class ReferralPayoutResponse(BaseModel):
"""Public payout information (for referrer dashboard)."""
id: str
amount_cents: int
earnings_count: int
status: str
created_at: datetime
class ReferralDashboardResponse(BaseModel):
"""Full referral dashboard data for the referrer."""
referral_link: ReferralLinkResponse
recent_earnings: List[ReferralEarningResponse]
recent_payouts: List[ReferralPayoutResponse]
total_earned_cents: int
total_paid_cents: int
pending_balance_cents: int
stripe_connect_onboarded: bool
class ReferralInterstitialResponse(BaseModel):
"""Data for the referral landing/interstitial page."""
valid: bool = True
referral_code: str = ""
referrer_display_name: Optional[str] = None
discount_percent: int = 0
discount_duration_days: int = 0
custom_message: Optional[str] = None
+24
View File
@@ -91,6 +91,9 @@ class User(BaseModel):
# Optional profile fields for future use
display_name: Optional[str] = None
# i18n locale preference (set from Accept-Language on login, used for emails/push)
locale: Optional[str] = None
# Push notification subscriptions (Web Push API)
# Users can subscribe from multiple devices/browsers
push_subscriptions: List[PushSubscription] = Field(default_factory=list)
@@ -105,6 +108,13 @@ class User(BaseModel):
# Flag to prevent duplicate welcome credit grants (idempotency)
welcome_credits_granted: bool = False
# Referral system
referral_code: Optional[str] = None # User's own referral code
referred_by_code: Optional[str] = None # Code used when this user signed up
referred_at: Optional[datetime] = None # When the referral was applied
referral_discount_expires_at: Optional[datetime] = None # When referral discount ends
stripe_connect_account_id: Optional[str] = None # For receiving referral payouts
class MagicLinkToken(BaseModel):
"""
@@ -129,6 +139,14 @@ class MagicLinkToken(BaseModel):
# Multi-tenant support (None = default Nomad Karaoke)
tenant_id: Optional[str] = None
# Referral attribution (travels with magic link for cross-device support)
referral_code: Optional[str] = None
# Pre-computed credit evaluation (set asynchronously after magic link is sent)
credit_eval_decision: Optional[str] = None # "grant", "deny", "pending_review"
credit_eval_reasoning: Optional[str] = None
credit_eval_error: Optional[str] = None
class Session(BaseModel):
"""
@@ -159,6 +177,7 @@ class SendMagicLinkRequest(BaseModel):
"""Request to send a magic link email."""
email: str
device_fingerprint: Optional[str] = None
referral_code: Optional[str] = None # From referral interstitial
class SendMagicLinkResponse(BaseModel):
@@ -194,6 +213,11 @@ class UserPublic(BaseModel):
tenant_id: Optional[str] = None
feedback_eligible: bool = False
total_spent: int = 0
referral_code: Optional[str] = None
has_active_referral_discount: bool = False
referral_discount_percent: Optional[int] = None
referral_discount_expires_at: Optional[str] = None # ISO string
referred_by_code: Optional[str] = None
created_at: Optional[str] = None
last_login_at: Optional[str] = None
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
"""
Download ensemble preset models at Docker build time.
Bakes models into the image so they're available immediately at runtime,
avoiding cold-start model download latency in Cloud Run Jobs.
Usage: python backend/scripts/download_models.py /models
"""
import json
import sys
import logging
import importlib.resources as resources
from audio_separator.separator import Separator
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Presets to bake into the GPU image
PRESETS_TO_DOWNLOAD = ["instrumental_clean", "karaoke"]
def download_preset_models(model_dir: str) -> None:
"""Download all models for the configured presets individually.
Ensemble presets resolve to multiple model filenames. We must download
each model individually via load_model(model_filename) — calling
load_model() with no args on an ensemble preset doesn't trigger downloads.
"""
with resources.open_text("audio_separator", "ensemble_presets.json") as f:
presets = json.load(f)["presets"]
models_to_download = set()
for preset_name in PRESETS_TO_DOWNLOAD:
models_to_download.update(presets[preset_name]["models"])
logger.info(f"Downloading {len(models_to_download)} models for presets: {PRESETS_TO_DOWNLOAD}")
for model in sorted(models_to_download):
logger.info(f" Downloading: {model}")
sep = Separator(model_file_dir=model_dir)
sep.load_model(model)
logger.info(f" Done: {model}")
if __name__ == "__main__":
model_dir = sys.argv[1] if len(sys.argv) > 1 else "/models"
download_preset_models(model_dir)
logger.info(f"All preset models downloaded to {model_dir}")
+61
View File
@@ -3,6 +3,7 @@ Authentication service for karaoke backend.
Provides token-based authentication with support for:
- Admin tokens (hardcoded in environment)
- Google OIDC tokens (from Cloud Scheduler / Cloud Tasks service accounts)
- Admin by email domain (@nomadkaraoke.com)
- User tokens (stored in Firestore auth_tokens collection)
- Session tokens (stored in Firestore sessions collection, from magic link auth)
@@ -19,6 +20,9 @@ from enum import Enum
from typing import Optional, Tuple, Dict, Any, List
from datetime import datetime
from google.auth.transport import requests as google_auth_requests
from google.oauth2 import id_token as google_id_token
from backend.services.firestore_service import FirestoreService
from backend.config import get_settings
from backend.models.user import UserRole
@@ -72,6 +76,7 @@ class AuthService:
self.firestore = FirestoreService()
self.settings = get_settings()
self._init_admin_tokens()
self._scheduler_service_account = self.settings.scheduler_service_account
def _init_admin_tokens(self):
"""Load admin tokens from environment variables."""
@@ -83,6 +88,56 @@ class AuthService:
logger.info(f"Loaded {len(self.admin_tokens)} admin token(s)")
else:
logger.warning("No admin tokens configured! Set ADMIN_TOKENS environment variable.")
def _validate_oidc_token(self, token: str) -> Optional[AuthResult]:
"""
Validate a Google OIDC token (from Cloud Scheduler or Cloud Tasks).
Returns AuthResult if token is a valid Google OIDC JWT from an allowed
service account, None if the token is not a JWT or validation fails.
"""
# Quick check: JWTs have 3 dot-separated parts
if token.count('.') != 2:
return None
try:
# Verify the token signature and claims with Google
# audience=None skips audience check — Cloud Scheduler sets audience
# to the endpoint URL, which varies per endpoint
claims = google_id_token.verify_oauth2_token(
token,
google_auth_requests.Request(),
audience=None,
)
token_email = claims.get("email", "")
# Only accept tokens from the configured service account
if token_email != self._scheduler_service_account:
logger.warning(
f"OIDC token from unexpected service account: {token_email} "
f"(expected {self._scheduler_service_account})"
)
return None
logger.info(f"OIDC token validated for service account: {token_email}")
return AuthResult(
is_valid=True,
user_type=UserType.ADMIN,
remaining_uses=-1,
message="OIDC service account access granted",
user_email=token_email,
is_admin=True,
)
except ValueError as e:
# verify_oauth2_token raises ValueError for invalid/expired tokens
logger.debug(f"OIDC token validation failed: {e}")
return None
except Exception as e:
# Network errors fetching Google certs, etc.
logger.warning(f"OIDC token verification error: {e}")
return None
def validate_token(self, token: str) -> Tuple[bool, UserType, int, str]:
"""
@@ -213,6 +268,12 @@ class AuthService:
is_admin=True
)
# Check for Google OIDC tokens (Cloud Scheduler / Cloud Tasks)
# Done before Firestore lookup to avoid wasting a read on JWT strings
oidc_result = self._validate_oidc_token(token)
if oidc_result is not None:
return oidc_result
# Check stored tokens in Firestore (auth_tokens collection)
token_data = self.firestore.get_token(token)
+189 -154
View File
@@ -19,6 +19,7 @@ from typing import Optional, List
from zoneinfo import ZoneInfo
from backend.config import get_settings
from backend.i18n import t, get_locale_prefix
from karaoke_gen.utils import sanitize_filename
@@ -249,6 +250,8 @@ class EmailService:
sender_email: Optional[str] = None,
tenant_frontend_url: Optional[str] = None,
tenant_name: Optional[str] = None,
locale: str = "en",
referral_code: Optional[str] = None,
) -> bool:
"""
Send a magic link email for authentication.
@@ -264,10 +267,12 @@ class EmailService:
True if email was sent successfully
"""
base_url = tenant_frontend_url or self.frontend_url
magic_link_url = f"{base_url}/auth/verify?token={token}"
magic_link_url = f"{base_url}{get_locale_prefix(locale)}/auth/verify?token={token}"
if referral_code:
magic_link_url += f"&ref={referral_code}"
brand_name = tenant_name or "Nomad Karaoke"
subject = f"Sign in to {brand_name}"
subject = t(locale, "emails.magicLink.subject", brand_name=brand_name)
extra_styles = """
.warning {
@@ -280,39 +285,52 @@ class EmailService:
}
"""
content = f"""
<p>Hi there,</p>
referral_banner = (
'<div style="background: linear-gradient(135deg, #7c3aed10, #a855f710); '
'border: 1px solid #a855f730; border-radius: 8px; padding: 16px; margin: 16px 0; '
'text-align: center;">'
'<p style="color: #a855f7; font-weight: 600; margin: 0;">&#127873; '
'Your referral discount is waiting!</p>'
'<p style="color: #666; font-size: 14px; margin: 4px 0 0;">'
'Sign in to claim your discount on credit purchases</p></div>'
if referral_code else ""
)
<p>Click the button below to sign in to {html.escape(brand_name)}:</p>
content = f"""
<p>{t(locale, "emails.magicLink.greeting")}</p>
<p>{t(locale, "emails.magicLink.signInPrompt", brand_name=html.escape(brand_name))}</p>
<p style="text-align: center;">
<a href="{magic_link_url}" class="button">Sign In</a>
<a href="{magic_link_url}" class="button">{t(locale, "emails.magicLink.signInButton")}</a>
</p>
{referral_banner}
<div class="warning">
⏰ This link expires in 15 minutes and can only be used once.
⏰ {t(locale, "emails.magicLink.expiryWarning")}
</div>
<p>If the button doesn't work, copy and paste this link into your browser:</p>
<p>{t(locale, "emails.magicLink.fallbackLink")}</p>
<p style="word-break: break-all; font-size: 14px; color: #666;">
{magic_link_url}
</p>
<p>If you didn't request this email, you can safely ignore it.</p>
<p>{t(locale, "emails.magicLink.ignoreNote")}</p>
"""
html_content = self._build_email_html(content, extra_styles)
html_content = self._build_email_html(content, extra_styles, locale=locale)
text_content = f"""
Sign in to {brand_name}
{t(locale, "emails.magicLink.signInButton")}
========================
Click this link to sign in:
{t(locale, "emails.magicLink.signInPrompt", brand_name=brand_name)}
{magic_link_url}
This link expires in 15 minutes and can only be used once.
{t(locale, "emails.magicLink.expiryWarning")}
If you didn't request this email, you can safely ignore it.
{t(locale, "emails.magicLink.ignoreNote")}
---
© {self._get_year()} {brand_name}
@@ -322,7 +340,7 @@ If you didn't request this email, you can safely ignore it.
email, subject, html_content, text_content, from_email_override=sender_email
)
def send_credits_added(self, email: str, credits: int, total_credits: int) -> bool:
def send_credits_added(self, email: str, credits: int, total_credits: int, locale: str = "en") -> bool:
"""
Send notification when credits are added to account.
@@ -334,7 +352,7 @@ If you didn't request this email, you can safely ignore it.
Returns:
True if email was sent successfully
"""
subject = f"🎉 {credits} credits added to your Nomad Karaoke account"
subject = t(locale, "emails.creditsAdded.subject", credits=credits)
extra_styles = f"""
.credits-box {{
@@ -353,39 +371,39 @@ If you didn't request this email, you can safely ignore it.
"""
content = f"""
<p>Great news!</p>
<p>{t(locale, "emails.creditsAdded.greatNews")}</p>
<p><strong>{credits} credits</strong> have been added to your account.</p>
<p><strong>{t(locale, "emails.creditsAdded.creditsAddedMessage", credits=credits)}</strong></p>
<div class="credits-box">
<div>Your balance:</div>
<div>{t(locale, "emails.creditsAdded.yourBalance")}</div>
<div class="credits-number">{total_credits}</div>
<div>credits</div>
<div>{t(locale, "emails.creditsAdded.credits")}</div>
</div>
<p>Each credit lets you create one professional karaoke video with:</p>
<p>{t(locale, "emails.creditsAdded.eachCreditLets")}</p>
<ul>
<li>AI-powered vocal/instrumental separation</li>
<li>Synchronized lyrics with word-level timing</li>
<li>4K video output</li>
<li>YouTube upload</li>
<li>{t(locale, "emails.creditsAdded.featureVocalSeparation")}</li>
<li>{t(locale, "emails.creditsAdded.featureLyrics")}</li>
<li>{t(locale, "emails.creditsAdded.feature4k")}</li>
<li>{t(locale, "emails.creditsAdded.featureYoutube")}</li>
</ul>
<p style="text-align: center;">
<a href="{self.frontend_url}" class="button">Create Karaoke Now</a>
<a href="{self.frontend_url}{get_locale_prefix(locale)}" class="button">{t(locale, "emails.creditsAdded.createButton")}</a>
</p>
"""
html_content = self._build_email_html(content, extra_styles)
html_content = self._build_email_html(content, extra_styles, locale=locale)
text_content = f"""
{credits} credits added to your Nomad Karaoke account!
{t(locale, "emails.creditsAdded.creditsAddedMessage", credits=credits)}
Your new balance: {total_credits} credits
{t(locale, "emails.creditsAdded.yourBalance")} {total_credits} {t(locale, "emails.creditsAdded.credits")}
Each credit lets you create one professional karaoke video.
{t(locale, "emails.creditsAdded.eachCreditLets")}
Start creating: {self.frontend_url}
{self.frontend_url}{get_locale_prefix(locale)}
---
© {self._get_year()} Nomad Karaoke
@@ -393,7 +411,7 @@ Start creating: {self.frontend_url}
return self.provider.send_email(email, subject, html_content, text_content)
def send_welcome_email(self, email: str, credits: int = 0) -> bool:
def send_welcome_email(self, email: str, credits: int = 0, locale: str = "en") -> bool:
"""
Send welcome email to new users.
@@ -404,7 +422,7 @@ Start creating: {self.frontend_url}
Returns:
True if email was sent successfully
"""
subject = "Welcome to Nomad Karaoke! 🎤"
subject = t(locale, "emails.welcome.subject")
extra_styles = """
.credits-box {
@@ -447,87 +465,87 @@ Start creating: {self.frontend_url}
credits_box = f"""
<div class="credits-box">
<div class="credits-number">{credits}</div>
<div class="credits-label">Free Credits</div>
<div class="credits-note">Each credit creates one professional karaoke video</div>
<div class="credits-label">{t(locale, "emails.welcome.freeCreditsLabel")}</div>
<div class="credits-note">{t(locale, "emails.welcome.freeCreditsNote")}</div>
</div>
"""
content = f"""
<p>Welcome to Nomad Karaoke!</p>
<p>{t(locale, "emails.welcome.welcomeGreeting")}</p>
<p>Turn any song into a professional karaoke video in minutes.</p>
<p>{t(locale, "emails.welcome.turnAnySong")}</p>
{credits_box}
<p><strong>Here's how it works:</strong></p>
<p><strong>{t(locale, "emails.welcome.howItWorks")}</strong></p>
<div class="feature">
<span class="feature-icon">🎵</span>
<div>
<strong>1. Search for a song</strong><br>
Enter the artist and title, and we'll find high-quality audio.
<strong>{t(locale, "emails.welcome.step1Title")}</strong><br>
{t(locale, "emails.welcome.step1Desc")}
</div>
</div>
<div class="feature">
<span class="feature-icon">✨</span>
<div>
<strong>2. Our system works its magic</strong><br>
We separate vocals, transcribe lyrics, and sync everything perfectly.
<strong>{t(locale, "emails.welcome.step2Title")}</strong><br>
{t(locale, "emails.welcome.step2Desc")}
</div>
</div>
<div class="feature">
<span class="feature-icon">✏️</span>
<div>
<strong>3. Review & customize</strong><br>
Fine-tune the lyrics if needed, choose your instrumental.
<strong>{t(locale, "emails.welcome.step3Title")}</strong><br>
{t(locale, "emails.welcome.step3Desc")}
</div>
</div>
<div class="feature">
<span class="feature-icon">🎬</span>
<div>
<strong>4. Get your video</strong><br>
Download your 4K karaoke video or upload directly to YouTube.
<strong>{t(locale, "emails.welcome.step4Title")}</strong><br>
{t(locale, "emails.welcome.step4Desc")}
</div>
</div>
<p style="text-align: center; font-size: 14px; color: #999; margin-top: 20px;">
Complete 2 videos and earn 2 more free credits by sharing your feedback!
{t(locale, "emails.welcome.feedbackBonus")}
</p>
<p style="text-align: center;">
<a href="{self.frontend_url}" class="button">Get Started</a>
<a href="{self.frontend_url}{get_locale_prefix(locale)}" class="button">{t(locale, "emails.welcome.getStartedButton")}</a>
</p>
"""
html_content = self._build_email_html(content, extra_styles)
html_content = self._build_email_html(content, extra_styles, locale=locale)
credits_text = f"\nYou have {credits} free credits to get started!\nEach credit creates one professional karaoke video.\n" if credits > 0 else ""
credits_text = f"\n{t(locale, 'emails.welcome.freeCreditsNote')}: {credits}\n" if credits > 0 else ""
text_content = f"""
Welcome to Nomad Karaoke!
{t(locale, "emails.welcome.welcomeGreeting")}
Turn any song into a professional karaoke video in minutes.
{t(locale, "emails.welcome.turnAnySong")}
{credits_text}
Here's how it works:
{t(locale, "emails.welcome.howItWorks")}
1. Search for a song
Enter the artist and title, and we'll find high-quality audio.
{t(locale, "emails.welcome.step1Title")}
{t(locale, "emails.welcome.step1Desc")}
2. Our system works its magic
We separate vocals, transcribe lyrics, and sync everything perfectly.
{t(locale, "emails.welcome.step2Title")}
{t(locale, "emails.welcome.step2Desc")}
3. Review & customize
Fine-tune the lyrics if needed, choose your instrumental.
{t(locale, "emails.welcome.step3Title")}
{t(locale, "emails.welcome.step3Desc")}
4. Get your video
Download your 4K karaoke video or upload directly to YouTube.
{t(locale, "emails.welcome.step4Title")}
{t(locale, "emails.welcome.step4Desc")}
Complete 2 videos and earn 2 more free credits by sharing your feedback!
{t(locale, "emails.welcome.feedbackBonus")}
Get started: {self.frontend_url}
{self.frontend_url}{get_locale_prefix(locale)}
---
© {self._get_year()} Nomad Karaoke
@@ -553,10 +571,10 @@ Get started: {self.frontend_url}
</div>
"""
def _get_email_footer(self) -> str:
def _get_email_footer(self, locale: str = "en") -> str:
"""Get the standard email footer with support message and signature."""
return f"""
<p style="margin-top: 30px; font-style: italic; color: #666;">If anything isn't perfect, just reply to this email and I'll fix it!</p>
<p style="margin-top: 30px; font-style: italic; color: #666;">{t(locale, "emails.shared.footerHelp")}</p>
<div class="signature">
{self._get_email_signature()}
@@ -599,13 +617,14 @@ Get started: {self.frontend_url}
}}
"""
def _build_email_html(self, content: str, extra_styles: str = "", extra_header_content: str = "") -> str:
def _build_email_html(self, content: str, extra_styles: str = "", extra_header_content: str = "", locale: str = "en") -> str:
"""Build a complete HTML email with standard header, footer, and styles.
Args:
content: The main body content of the email
extra_styles: Additional CSS styles specific to this email type
extra_header_content: Optional extra content to add in header (e.g., beta badge)
locale: Locale for footer localization
Returns:
Complete HTML email string
@@ -624,7 +643,7 @@ Get started: {self.frontend_url}
{content}
{self._get_email_footer()}
{self._get_email_footer(locale)}
</body>
</html>
"""
@@ -870,6 +889,7 @@ Get started: {self.frontend_url}
title: Optional[str] = None,
brand_code: Optional[str] = None,
cc_admin: bool = True,
locale: str = "en",
) -> bool:
"""
Send job completion email with the rendered template content.
@@ -891,11 +911,11 @@ Get started: {self.frontend_url}
safe_artist = sanitize_filename(artist) if artist else None
safe_title = sanitize_filename(title) if title else None
if brand_code and safe_artist and safe_title:
subject = f"{brand_code}: {safe_artist} - {safe_title} (Your karaoke video is ready!)"
subject = t(locale, "emails.jobCompletion.subjectWithBrand", brand_code=brand_code, artist=safe_artist, title=safe_title)
elif safe_artist and safe_title:
subject = f"{safe_artist} - {safe_title} (Your karaoke video is ready!)"
subject = t(locale, "emails.jobCompletion.subject", artist=safe_artist, title=safe_title)
else:
subject = "Your karaoke video is ready!"
subject = t(locale, "emails.jobCompletion.subjectFallback")
extra_styles = """
.content {
@@ -907,7 +927,7 @@ Get started: {self.frontend_url}
<div class="content">{html.escape(message_content)}</div>
"""
html_content = self._build_email_html(content, extra_styles)
html_content = self._build_email_html(content, extra_styles, locale=locale)
cc_emails = ["gen@nomadkaraoke.com"] if cc_admin else None
@@ -927,6 +947,7 @@ Get started: {self.frontend_url}
action_type: str,
artist: Optional[str] = None,
title: Optional[str] = None,
locale: str = "en",
) -> bool:
"""
Send action-needed reminder email.
@@ -942,13 +963,26 @@ Get started: {self.frontend_url}
True if email was sent successfully
"""
# Build subject based on action type
song_info = f" for {artist} - {title}" if artist and title else ""
if action_type == "lyrics":
subject = f"Action needed: Review lyrics{song_info}"
if artist and title:
subject = t(locale, "emails.actionReminder.lyricsSubject", artist=artist, title=title)
else:
subject = t(locale, "emails.actionReminder.lyricsSubjectFallback")
elif action_type == "instrumental":
subject = f"Action needed: Select instrumental{song_info}"
if artist and title:
subject = t(locale, "emails.actionReminder.instrumentalSubject", artist=artist, title=title)
else:
subject = t(locale, "emails.actionReminder.instrumentalSubjectFallback")
elif action_type == "audio_edit":
if artist and title:
subject = t(locale, "emails.actionReminder.audioEditSubject", artist=artist, title=title)
else:
subject = t(locale, "emails.actionReminder.audioEditSubjectFallback")
else:
subject = f"Action needed{song_info}"
if artist and title:
subject = t(locale, "emails.actionReminder.audioEditSubject", artist=artist, title=title)
else:
subject = t(locale, "emails.actionReminder.audioEditSubjectFallback")
extra_styles = """
.alert {
@@ -966,13 +1000,13 @@ Get started: {self.frontend_url}
content = f"""
<div class="alert">
⏰ Your karaoke video needs input from you!
⏰ {t(locale, "emails.actionReminder.alertHeading")}
</div>
<div class="content">{html.escape(message_content)}</div>
"""
html_content = self._build_email_html(content, extra_styles)
html_content = self._build_email_html(content, extra_styles, locale=locale)
return self.provider.send_email(
to_email=to_email,
@@ -987,6 +1021,7 @@ Get started: {self.frontend_url}
artist: Optional[str] = None,
title: Optional[str] = None,
job_id: Optional[str] = None,
locale: str = "en",
) -> bool:
"""
Send 24h review reminder email with expiry warning.
@@ -1003,10 +1038,13 @@ Get started: {self.frontend_url}
Returns:
True if email was sent successfully
"""
song_info = f" — {artist} - {title}" if artist and title else ""
subject = f"Reminder: Your karaoke video is waiting for review{song_info}"
if artist and title:
subject = t(locale, "emails.reviewReminder.subject", artist=artist, title=title)
else:
subject = t(locale, "emails.reviewReminder.subjectFallback")
review_url = f"{self.frontend_url}/app/jobs#/{job_id}/review" if job_id else f"{self.frontend_url}/app"
locale_prefix = get_locale_prefix(locale)
review_url = f"{self.frontend_url}{locale_prefix}/app/jobs#/{job_id}/review" if job_id else f"{self.frontend_url}{locale_prefix}/app"
extra_styles = """
.alert {
@@ -1039,36 +1077,35 @@ Get started: {self.frontend_url}
"""
song_name = f" for <strong>{html.escape(artist)} - {html.escape(title)}</strong>" if artist and title else ""
song_name_text = f" for {artist} - {title}" if artist and title else ""
content = f"""
<div class="alert">
⏰ Your karaoke video is waiting for you!
⏰ {t(locale, "emails.reviewReminder.alertHeading")}
</div>
<p>Hi there! Just a friendly reminder that your karaoke video{song_name} is ready for review.</p>
<p>{t(locale, "emails.reviewReminder.reminderIntro", song_name=song_name)}</p>
<p style="text-align: center;">
<a href="{html.escape(review_url)}" class="review-btn">Review Your Video</a>
<a href="{html.escape(review_url)}" class="review-btn">{t(locale, "emails.reviewReminder.reviewButton")}</a>
</p>
<p>During the review, you can check the lyrics are correct and choose your preferred instrumental track. It usually only takes a few minutes!</p>
<p>{t(locale, "emails.reviewReminder.reviewInstructions")}</p>
<p>If you're having any trouble with the review process, just reply to this email and I'll be happy to help you out.</p>
<p>{t(locale, "emails.reviewReminder.helpOffer")}</p>
<div class="expiry-warning">
⚠️ Please note: if the review isn't completed within the next <strong>24 hours</strong>,
the job will automatically expire and your credit will be refunded.
⚠️ {t(locale, "emails.reviewReminder.expiryWarning")}
</div>
"""
html_content = self._build_email_html(content, extra_styles)
html_content = self._build_email_html(content, extra_styles, locale=locale)
text_content = (
f"Reminder: Your karaoke video{' for ' + artist + ' - ' + title if artist and title else ''} is ready for review.\n\n"
f"Review it here: {review_url}\n\n"
"If you're having trouble with the review process, just reply to this email and I'll help you out.\n\n"
"Please note: if the review isn't completed within the next 24 hours, "
"the job will automatically expire and your credit will be refunded."
f"{t(locale, 'emails.reviewReminder.reminderIntro', song_name=song_name_text)}\n\n"
f"{t(locale, 'emails.reviewReminder.reviewButton')}: {review_url}\n\n"
f"{t(locale, 'emails.reviewReminder.helpOffer')}\n\n"
f"{t(locale, 'emails.reviewReminder.expiryWarning')}"
)
return self.provider.send_email(
@@ -1084,6 +1121,7 @@ Get started: {self.frontend_url}
artist: Optional[str] = None,
title: Optional[str] = None,
credits_balance: int = 0,
locale: str = "en",
) -> bool:
"""
Send review expiry notification email.
@@ -1100,8 +1138,10 @@ Get started: {self.frontend_url}
Returns:
True if email was sent successfully
"""
song_info = f" — {artist} - {title}" if artist and title else ""
subject = f"Your karaoke video has expired{song_info}"
if artist and title:
subject = t(locale, "emails.reviewExpired.subject", artist=artist, title=title)
else:
subject = t(locale, "emails.reviewExpired.subjectFallback")
extra_styles = """
.info-box {
@@ -1133,33 +1173,32 @@ Get started: {self.frontend_url}
"""
song_name = f" for <strong>{html.escape(artist)} - {html.escape(title)}</strong>" if artist and title else ""
song_name_text = f" for {artist} - {title}" if artist and title else ""
credits_word = t(locale, "emails.reviewExpired.creditSingular") if credits_balance == 1 else t(locale, "emails.reviewExpired.creditPlural")
content = f"""
<div class="info-box">
Your karaoke video{song_name} has been automatically cancelled because the review
wasn't completed within 48 hours.
{t(locale, "emails.reviewExpired.cancelNotice", song_name=song_name)}
</div>
<p>Don't worry — your credit has been refunded! Your current balance is
<span class="credit-badge">{credits_balance} credit{'s' if credits_balance != 1 else ''}</span>.</p>
<p>{t(locale, "emails.reviewExpired.refundNotice", credits_balance=credits_balance, credits_word=credits_word)}</p>
<p>You can create a new karaoke video anytime using your credits:</p>
<p>{t(locale, "emails.reviewExpired.createNewPrompt")}</p>
<p style="text-align: center;">
<a href="{html.escape(self.frontend_url)}/app" class="create-btn">Create New Video</a>
<a href="{html.escape(self.frontend_url)}{get_locale_prefix(locale)}/app" class="create-btn">{t(locale, "emails.reviewExpired.createButton")}</a>
</p>
<p>If you had any trouble with the review process or need help, just reply to this email — I'd love to help!</p>
<p>{t(locale, "emails.reviewExpired.helpOffer")}</p>
"""
html_content = self._build_email_html(content, extra_styles)
html_content = self._build_email_html(content, extra_styles, locale=locale)
text_content = (
f"Your karaoke video{' for ' + artist + ' - ' + title if artist and title else ''} has been "
"automatically cancelled because the review wasn't completed within 48 hours.\n\n"
f"Your credit has been refunded. Current balance: {credits_balance} credit{'s' if credits_balance != 1 else ''}.\n\n"
f"Create a new video anytime: {self.frontend_url}/app\n\n"
"If you had any trouble or need help, just reply to this email."
f"{t(locale, 'emails.reviewExpired.cancelNotice', song_name=song_name_text)}\n\n"
f"{t(locale, 'emails.reviewExpired.refundNotice', credits_balance=credits_balance, credits_word=credits_word)}\n\n"
f"{self.frontend_url}{get_locale_prefix(locale)}/app\n\n"
f"{t(locale, 'emails.reviewExpired.helpOffer')}"
)
return self.provider.send_email(
@@ -1176,6 +1215,7 @@ Get started: {self.frontend_url}
artist: Optional[str] = None,
title: Optional[str] = None,
brand_code: Optional[str] = None,
locale: str = "en",
) -> bool:
"""
Send follow-up email when a deferred YouTube upload completes.
@@ -1193,11 +1233,11 @@ Get started: {self.frontend_url}
safe_artist = sanitize_filename(artist) if artist else None
safe_title = sanitize_filename(title) if title else None
if brand_code and safe_artist and safe_title:
subject = f"{brand_code}: {safe_artist} - {safe_title} (YouTube upload ready!)"
subject = t(locale, "emails.youtubeUpload.subjectWithBrand", brand_code=brand_code, artist=safe_artist, title=safe_title)
elif safe_artist and safe_title:
subject = f"{safe_artist} - {safe_title} (YouTube upload ready!)"
subject = t(locale, "emails.youtubeUpload.subject", artist=safe_artist, title=safe_title)
else:
subject = "Your YouTube upload is ready!"
subject = t(locale, "emails.youtubeUpload.subjectFallback")
extra_styles = """
.content {
@@ -1209,7 +1249,7 @@ Get started: {self.frontend_url}
<div class="content">{html.escape(message_content)}</div>
"""
html_content = self._build_email_html(content, extra_styles)
html_content = self._build_email_html(content, extra_styles, locale=locale)
return self.provider.send_email(
to_email=to_email,
@@ -1226,6 +1266,7 @@ Get started: {self.frontend_url}
title: str,
job_id: str,
notes: Optional[str] = None,
locale: str = "en",
) -> bool:
"""
Send order confirmation email to customer for made-for-you orders.
@@ -1240,7 +1281,7 @@ Get started: {self.frontend_url}
Returns:
True if email was sent successfully
"""
subject = f"Order Confirmed: {artist} - {title} | Nomad Karaoke"
subject = t(locale, "emails.madeForYouConfirmation.subject", artist=artist, title=title)
extra_styles = """
.order-details {
@@ -1266,42 +1307,42 @@ Get started: {self.frontend_url}
notes_html = ""
notes_text = ""
if notes:
notes_html = f"<p><strong>Your Notes:</strong> {html.escape(notes)}</p>"
notes_text = f"\nYour Notes: {notes}"
notes_html = f"<p><strong>{t(locale, 'emails.madeForYouConfirmation.yourNotes')}</strong> {html.escape(notes)}</p>"
notes_text = f"\n{t(locale, 'emails.madeForYouConfirmation.yourNotes')} {notes}"
content = f"""
<h2>Thank You for Your Order!</h2>
<h2>{t(locale, "emails.madeForYouConfirmation.thankYou")}</h2>
<div class="order-details">
<h3>Order Details</h3>
<p><strong>Order ID:</strong> {html.escape(job_id)}</p>
<p><strong>Artist:</strong> {html.escape(artist)}</p>
<p><strong>Title:</strong> {html.escape(title)}</p>
<h3>{t(locale, "emails.madeForYouConfirmation.orderDetails")}</h3>
<p><strong>{t(locale, "emails.madeForYouConfirmation.orderId")}</strong> {html.escape(job_id)}</p>
<p><strong>{t(locale, "emails.madeForYouConfirmation.artist")}</strong> {html.escape(artist)}</p>
<p><strong>{t(locale, "emails.madeForYouConfirmation.title")}</strong> {html.escape(title)}</p>
{notes_html}
</div>
<p>Our team will create your custom karaoke video within <span class="highlight">24 hours</span>.</p>
<p>{t(locale, "emails.madeForYouConfirmation.deliveryTime", hours=24)}</p>
<p>You'll receive an email with download links as soon as your video is ready.</p>
<p>{t(locale, "emails.madeForYouConfirmation.deliveryNotice")}</p>
<p><strong>No action needed</strong> - sit back and we'll take care of everything!</p>
<p><strong>{t(locale, "emails.madeForYouConfirmation.noAction")}</strong></p>
"""
text_content = f"""Thank You for Your Order!
text_content = f"""{t(locale, "emails.madeForYouConfirmation.thankYou")}
Order Details:
Order ID: {job_id}
Artist: {artist}
Title: {title}{notes_text}
{t(locale, "emails.madeForYouConfirmation.orderDetails")}:
{t(locale, "emails.madeForYouConfirmation.orderId")} {job_id}
{t(locale, "emails.madeForYouConfirmation.artist")} {artist}
{t(locale, "emails.madeForYouConfirmation.title")} {title}{notes_text}
Our team will create your custom karaoke video within 24 hours.
{t(locale, "emails.madeForYouConfirmation.deliveryTime", hours=24)}
You'll receive an email with download links as soon as your video is ready.
{t(locale, "emails.madeForYouConfirmation.deliveryNotice")}
No action needed - sit back and we'll take care of everything!
{t(locale, "emails.madeForYouConfirmation.noAction")}
"""
html_content = self._build_email_html(content, extra_styles)
html_content = self._build_email_html(content, extra_styles, locale=locale)
return self.provider.send_email(
to_email=to_email,
@@ -1662,59 +1703,53 @@ If the user looks legitimate, grant them credits from their admin page.
text_content=text_content,
)
def send_credit_denied_email(self, email: str, grant_type: str = "welcome") -> bool:
def send_credit_denied_email(self, email: str, grant_type: str = "welcome", locale: str = "en") -> 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"
subject = t(locale, "emails.creditDenied.subject")
credit_type = "welcome credits" if grant_type == "welcome" else "feedback bonus credits"
credit_type = t(locale, "emails.creditDenied.welcomeCredits") if grant_type == "welcome" else t(locale, "emails.creditDenied.feedbackCredits")
content = f"""
<p>Hi there,</p>
<p>{t(locale, "emails.creditDenied.greeting")}</p>
<p>Thanks for signing up for Nomad Karaoke!</p>
<p>{t(locale, "emails.creditDenied.thankYou")}</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>{t(locale, "emails.creditDenied.deniedMessage", credit_type=credit_type)}</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>{t(locale, "emails.creditDenied.mistakeNote")}</p>
<p>If you'd like to get started right away, you can also purchase credits:</p>
<p>{t(locale, "emails.creditDenied.buyPrompt")}</p>
<p style="text-align: center;">
<a href="{self.buy_url}" class="button">Buy Credits</a>
<a href="{self.buy_url}" class="button">{t(locale, "emails.creditDenied.buyButton")}</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>
<p style="color: #999; font-size: 14px;">{t(locale, "emails.creditDenied.costNote")}</p>
{self._get_email_signature()}
"""
text_content = f"""Hi there,
text_content = f"""{t(locale, "emails.creditDenied.greeting")}
Thanks for signing up for Nomad Karaoke!
{t(locale, "emails.creditDenied.thankYou")}
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.
{t(locale, "emails.creditDenied.deniedMessage", credit_type=credit_type)}
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.
{t(locale, "emails.creditDenied.mistakeNote")}
If you'd like to get started right away, you can also purchase credits:
{t(locale, "emails.creditDenied.buyPrompt")}
{self.buy_url}
---
© {self._get_year()} Nomad Karaoke
"""
html_content = self._build_email_html(content)
html_content = self._build_email_html(content, locale=locale)
return self.provider.send_email(
to_email=email,
@@ -212,9 +212,11 @@ class EmailValidationService:
effective_domains = (external | manual) - allowlisted
else:
# Old data model (pre-migration): use disposable_domains + defaults
allowlisted = set()
effective_domains = set(data.get("disposable_domains", [])) | DEFAULT_DISPOSABLE_DOMAINS
config = {
"disposable_domains": effective_domains,
"allowlisted_domains": allowlisted,
"blocked_emails": set(data.get("blocked_emails", [])),
"blocked_ips": set(data.get("blocked_ips", [])),
"verified_clean_domains": data.get("verified_clean_domains", {}),
@@ -222,6 +224,7 @@ class EmailValidationService:
else:
config = {
"disposable_domains": DEFAULT_DISPOSABLE_DOMAINS.copy(),
"allowlisted_domains": set(),
"blocked_emails": set(),
"blocked_ips": set(),
"verified_clean_domains": {},
@@ -267,6 +270,12 @@ class EmailValidationService:
if domain in config["disposable_domains"]:
return True
# Tier 1.5: Explicitly allowlisted domains skip external API checks.
# Without this, external APIs can override admin allowlist decisions
# (e.g. inbox.testmail.app is a legitimate testing domain we allow).
if domain in config.get("allowlisted_domains", set()):
return False
# Tier 2: Recently verified clean? Skip API calls
if self._is_domain_verified_clean(domain, config):
return False
+134
View File
@@ -115,6 +115,28 @@ class EncodingService:
"""Check if GCE preview encoding is enabled and configured."""
return self.settings.use_gce_preview_encoding and self.is_configured
def _warmup_encoding_worker_fallback(self, job_id: str) -> None:
"""Safety net: try to start the encoding worker VM on first connection failure.
If the worker_manager is available, calls ensure_primary_running() so the VM
starts booting during the retry window. If worker_manager is not set (e.g. dev
mode with static URL), this is a no-op.
"""
if not self._worker_manager:
return
try:
result = self._worker_manager.ensure_primary_running()
if result["started"]:
logger.warning(
f"[job:{job_id}] Encoding worker unreachable — started VM {result['vm_name']} as fallback"
)
else:
logger.info(
f"[job:{job_id}] Encoding worker unreachable — VM {result['vm_name']} already running/starting"
)
except Exception as e:
logger.warning(f"[job:{job_id}] Encoding worker warmup fallback failed (non-fatal): {e}")
async def _request_with_retry(
self,
method: str,
@@ -176,6 +198,8 @@ class EncodingService:
}
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError, asyncio.TimeoutError) as e:
last_exception = e
if attempt == 0:
self._warmup_encoding_worker_fallback(job_id)
if attempt < MAX_RETRIES:
logger.warning(
f"[job:{job_id}] GCE worker connection failed (attempt {attempt + 1}/{MAX_RETRIES + 1}): {e}. "
@@ -560,6 +584,116 @@ class EncodingService:
timeout=timeout,
)
async def submit_render_video_job(
self,
job_id: str,
render_config: Dict[str, Any],
) -> Dict[str, Any]:
"""
Submit a render-video job to the GCE worker.
Args:
job_id: Unique job identifier
render_config: Configuration dict containing original_corrections_gcs_path,
audio_gcs_path, output_gcs_prefix, artist, title, and any other render params.
Returns:
Response from the encoding worker
Raises:
RuntimeError: If submission fails
"""
self._load_credentials()
if not self.is_configured:
raise RuntimeError("Encoding service not configured")
url = f"{self._get_worker_url()}/render-video"
headers = {"X-API-Key": self._api_key, "Content-Type": "application/json"}
payload = {"job_id": job_id, **render_config}
logger.info(f"[job:{job_id}] Submitting render-video job to GCE worker: {url}")
resp = await self._request_with_retry(
method="POST",
url=url,
headers=headers,
json_payload=payload,
timeout=30.0,
job_id=job_id,
)
if resp["status"] == 401:
raise RuntimeError("Invalid API key for encoding worker")
if resp["status"] == 409:
# Job already exists on worker — check if it already completed
logger.warning(f"[job:{job_id}] GCE worker returned 409, checking job status")
try:
status = await self.get_job_status(job_id)
job_status = status.get("status", "unknown")
if job_status == "complete":
logger.info(f"[job:{job_id}] Render-video job already complete on GCE worker, returning cached result")
return {
"status": "cached",
"job_id": job_id,
"output_files": status.get("output_files"),
"metadata": status.get("metadata"),
}
elif job_status in ("pending", "running"):
logger.info(f"[job:{job_id}] Render-video job still in progress on GCE worker")
return {"status": "in_progress", "job_id": job_id}
else:
raise RuntimeError(f"Render-video job {job_id} already exists with status: {job_status}")
except RuntimeError as e:
if "not found" in str(e).lower():
raise RuntimeError(f"Render-video job {job_id} conflict: 409 but job not found on status check")
raise
if resp["status"] != 200:
raise RuntimeError(f"Failed to submit render-video job: {resp['status']} - {resp['text']}")
return resp["json"]
async def render_video_on_gce(
self,
job_id: str,
render_config: Dict[str, Any],
progress_callback=None,
) -> Dict[str, Any]:
"""
Submit render-video job and wait for completion.
This is a convenience method that combines submit + wait.
Args:
job_id: Unique job identifier
render_config: Configuration dict for the render-video worker endpoint
progress_callback: Optional callback for progress updates
Returns:
Final job status with output files and metadata
"""
# Submit the job
submit_result = await self.submit_render_video_job(job_id, render_config)
# If cached, return immediately — rendering already done
submit_status = submit_result.get("status")
if submit_status == "cached":
logger.info(f"[job:{job_id}] Render-video already cached, returning immediately")
return {
"status": "complete",
"output_files": submit_result.get("output_files"),
"metadata": submit_result.get("metadata"),
}
# If in_progress, another request is rendering it — just wait for that
if submit_status == "in_progress":
logger.info(f"[job:{job_id}] Render-video already in progress, joining poll")
# Wait for completion
return await self.wait_for_completion(
job_id, progress_callback=progress_callback
)
async def health_check(self) -> Dict[str, Any]:
"""
Check the health of the encoding worker.
@@ -0,0 +1 @@
"""Production error monitoring service for Nomad Karaoke."""
+177
View File
@@ -0,0 +1,177 @@
"""Configuration for the production error monitoring service.
All constants, service lists, and environment-driven configuration
functions used across the error monitor modules.
"""
import os
# ---------------------------------------------------------------------------
# GCP project settings
# ---------------------------------------------------------------------------
GCP_PROJECT: str = os.environ.get("GCP_PROJECT", "nomadkaraoke")
GCP_REGION: str = os.environ.get("GCP_REGION", "us-central1")
# ---------------------------------------------------------------------------
# Log querying settings
# ---------------------------------------------------------------------------
#: How far back to look for errors on each run (minutes).
LOOKBACK_MINUTES: int = 15
#: Maximum number of log entries to fetch per service per run.
MAX_LOG_ENTRIES: int = 500
# ---------------------------------------------------------------------------
# Monitored services
# ---------------------------------------------------------------------------
MONITORED_CLOUD_RUN_SERVICES: list[str] = [
"karaoke-backend",
"karaoke-decide",
"audio-separator",
# Gen2 Cloud Functions appear as Cloud Run services in logs
"gdrive-validator",
"github-runner-manager",
"backup-to-aws",
"divebar-mirror",
"kn-data-sync",
"divebar-lookup",
"encoding-worker-idle-shutdown",
]
MONITORED_CLOUD_RUN_JOBS: list[str] = [
"video-encoding-job",
"lyrics-transcription-job",
"audio-separation-job",
"audio-download-job",
]
# Gen2 Cloud Functions log as cloud_run_revision, not cloud_function.
# Their names are in MONITORED_CLOUD_RUN_SERVICES above.
MONITORED_CLOUD_FUNCTIONS: list[str] = []
MONITORED_GCE_INSTANCES: list[str] = [
"encoding-worker-a",
"encoding-worker-b",
"flacfetch-vm",
"divebar-sync-vm",
]
# ---------------------------------------------------------------------------
# Service dependency map
# Human-readable description of which services depend on which workers.
# Used as LLM context when generating root-cause analysis.
# ---------------------------------------------------------------------------
SERVICE_DEPENDENCY_MAP: str = """\
karaoke-backend (main API)
→ video-encoding-job (Cloud Run Job, triggered per order)
→ lyrics-transcription-job (Cloud Run Job, triggered after audio-sep)
→ audio-separation-job (Cloud Run Job, runs on Cloud Run GPU)
→ audio-download-job (Cloud Run Job, uses flacfetch-vm)
→ gdrive-validator (Cloud Function, validates output files)
→ encoding-worker-a/b (GCE VMs, long-running encoding workers)
karaoke-decide (catalog / discovery API)
→ kn_data_sync (Cloud Function, syncs KaraokeNerds catalog)
→ divebar_mirror (Cloud Function, mirrors Divebar catalog)
→ divebar_lookup (Cloud Function, single-song lookup)
audio-separator (Cloud Run service, GPU stem separation)
→ audio-separation-job (Cloud Run Job, launched by audio-separator)
flacfetch-vm (GCE VM)
→ audio-download-job (initiated by karaoke-backend)
divebar-sync-vm (GCE VM)
→ divebar_mirror (Cloud Function, reads from this VM)
Shared infrastructure:
→ runner_manager (Cloud Function, manages encoding worker lifecycle)
→ encoding_worker_idle (Cloud Function, shuts down idle encoding workers)
→ backup_to_aws (Cloud Function, daily GCS → S3 backup)
"""
# ---------------------------------------------------------------------------
# LLM analysis settings
# ---------------------------------------------------------------------------
LLM_ANALYSIS_MODEL: str = os.environ.get("LLM_ANALYSIS_MODEL", "gemini-2.0-flash-001")
LLM_VERTEX_LOCATION: str = os.environ.get("LLM_VERTEX_LOCATION", "us-central1")
#: Minimum number of active error patterns required before triggering LLM analysis.
MIN_PATTERNS_FOR_ANALYSIS: int = 3
# ---------------------------------------------------------------------------
# Spike detection
# ---------------------------------------------------------------------------
#: An error count is a spike if it exceeds SPIKE_MULTIPLIER × baseline average.
SPIKE_MULTIPLIER: float = 5.0
#: Minimum absolute error count before spike detection fires (avoids noise).
SPIKE_MIN_COUNT: int = 5
# ---------------------------------------------------------------------------
# Auto-resolution settings
# ---------------------------------------------------------------------------
#: Multiply LOOKBACK_MINUTES by this to get auto-resolve window in minutes.
AUTO_RESOLVE_MULTIPLIER: int = 8
#: Minimum hours before a pattern can be auto-resolved.
AUTO_RESOLVE_MIN_HOURS: int = 6
#: Maximum hours before a pattern is force-resolved even if still active.
AUTO_RESOLVE_MAX_HOURS: int = 168 # 1 week
#: Fallback resolve window (hours) if baseline data is unavailable.
AUTO_RESOLVE_FALLBACK_HOURS: int = 48
# ---------------------------------------------------------------------------
# Discord settings
# ---------------------------------------------------------------------------
#: Maximum Discord messages to send per monitor run (rate-limit guard).
MAX_DISCORD_MESSAGES_PER_RUN: int = 10
#: Discord API hard limit on message length.
DISCORD_MAX_MESSAGE_LENGTH: int = 2000
# ---------------------------------------------------------------------------
# Pattern tracking settings
# ---------------------------------------------------------------------------
#: Maximum number of active error patterns to track in Firestore.
MAX_ACTIVE_PATTERNS: int = 500
#: Rolling window used when computing error baselines.
ROLLING_WINDOW_DAYS: int = 7
#: Maximum length of a normalized error message stored in Firestore.
MAX_NORMALIZED_MESSAGE_LENGTH: int = 200
# ---------------------------------------------------------------------------
# Helper functions
# ---------------------------------------------------------------------------
def get_llm_enabled() -> bool:
"""Return True if LLM analysis is enabled via the LLM_ANALYSIS_ENABLED env var."""
return os.environ.get("LLM_ANALYSIS_ENABLED", "false").strip().lower() == "true"
def get_discord_webhook_secret_name() -> str:
"""Return the Secret Manager secret name for the Discord webhook URL."""
return os.environ.get("DISCORD_WEBHOOK_SECRET_NAME", "error-monitor-discord-webhook")
def get_digest_mode() -> bool:
"""Return True if the monitor should run in digest mode (batch alerts instead of immediate).
In digest mode all alerts are bundled into a single Discord message sent at
the end of the run, rather than sending one message per error pattern.
"""
return os.environ.get("DIGEST_MODE", "false").strip().lower() == "true"
+323
View File
@@ -0,0 +1,323 @@
"""Discord alert client for the production error monitoring service.
Provides formatting functions for each alert type, and an ErrorMonitorDiscord
webhook client that rate-limits outbound messages to MAX_DISCORD_MESSAGES_PER_RUN
per monitor run.
Usage:
from backend.services.error_monitor.discord import (
ErrorMonitorDiscord,
format_new_pattern_alert,
format_incident_alert,
format_auto_resolved_alert,
format_spike_alert,
format_daily_digest,
)
discord = ErrorMonitorDiscord(webhook_url="https://discord.com/api/webhooks/...")
msg = format_new_pattern_alert(...)
discord.send_message(msg)
"""
import logging
from datetime import datetime
from zoneinfo import ZoneInfo
import requests
from backend.services.error_monitor.config import (
DISCORD_MAX_MESSAGE_LENGTH,
MAX_DISCORD_MESSAGES_PER_RUN,
)
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
SEVERITY_EMOJI: dict[str, str] = {
"P0": "🚨",
"P1": "🔴",
"P2": "⚠️",
"P3": "🟡",
}
_EASTERN = ZoneInfo("America/New_York")
# ---------------------------------------------------------------------------
# Private helpers
# ---------------------------------------------------------------------------
def _now_eastern() -> str:
"""Return the current Eastern time as 'HH:MM AM/PM ET' (DST-aware)."""
now = datetime.now(tz=_EASTERN)
return now.strftime("%I:%M %p ET").lstrip("0")
def _truncate(msg: str) -> str:
"""Truncate *msg* to DISCORD_MAX_MESSAGE_LENGTH characters."""
if len(msg) <= DISCORD_MAX_MESSAGE_LENGTH:
return msg
suffix = "…"
return msg[: DISCORD_MAX_MESSAGE_LENGTH - len(suffix)] + suffix
# ---------------------------------------------------------------------------
# Formatting functions
# ---------------------------------------------------------------------------
def format_new_pattern_alert(
service: str,
resource_type: str,
normalized_message: str,
sample_message: str,
count: int,
first_seen: str,
) -> str:
"""Format a Discord alert for a newly-detected error pattern.
Args:
service: Name of the service emitting the error.
resource_type: GCP resource type (e.g. 'cloud_run_service', 'gce_instance').
normalized_message: Normalised error pattern string.
sample_message: A representative raw log message.
count: Number of occurrences seen so far.
first_seen: ISO 8601 timestamp when the pattern was first seen.
Returns:
Formatted Discord message string, truncated to 2000 chars.
"""
lines = [
f"🔴 **New Error Pattern Detected**",
f"",
f"**Service:** {service}",
f"**Resource type:** {resource_type}",
f"**Pattern:** {normalized_message}",
f"**Sample:** {sample_message}",
f"**Count:** {count}",
f"**First seen:** {first_seen}",
f"**Alerted at:** {_now_eastern()}",
f"",
f"To investigate: `/prod-investigate {service} \"{normalized_message}\"`",
]
return _truncate("\n".join(lines))
def format_incident_alert(
title: str,
severity: str,
root_cause: str,
suggested_fix: str,
primary_service: str,
patterns: list[dict],
) -> str:
"""Format a Discord alert for an analysed incident (LLM-generated).
Args:
title: Short incident title.
severity: Severity level — one of P0, P1, P2, P3.
root_cause: Human-readable root-cause analysis.
suggested_fix: Recommended remediation steps.
primary_service: The main service involved in the incident.
patterns: List of dicts, each with keys: service, normalized_message, count.
Only the first 5 are shown; normalized_message is truncated to 80 chars.
Returns:
Formatted Discord message string, truncated to 2000 chars.
"""
emoji = SEVERITY_EMOJI.get(severity, "⚠️")
lines = [
f"{emoji} **[{severity}] {title}**",
f"",
f"**Primary service:** {primary_service}",
f"**Root cause:** {root_cause}",
f"**Suggested fix:** {suggested_fix}",
]
shown_patterns = patterns[:5]
if shown_patterns:
lines.append("")
lines.append(f"**Patterns ({len(shown_patterns)} of {len(patterns)}):**")
for p in shown_patterns:
svc = p.get("service", "unknown")
msg = p.get("normalized_message", "")[:80]
cnt = p.get("count", 0)
lines.append(f" • `{svc}` — {msg} ({cnt}x)")
lines.append("")
lines.append(f"**Alerted at:** {_now_eastern()}")
return _truncate("\n".join(lines))
def format_auto_resolved_alert(resolved_patterns: list[dict]) -> str:
"""Format a consolidated auto-resolved alert.
Args:
resolved_patterns: List of dicts, each with keys: service, message, hours_silent.
Only the first 8 are shown; message is truncated to 60 chars.
Returns:
Formatted Discord message string, truncated to 2000 chars.
"""
lines = [
f"✅ **Patterns Auto-Resolved**",
f"",
]
shown = resolved_patterns[:8]
if shown:
for p in shown:
svc = p.get("service", "unknown")
msg = p.get("message", "")[:60]
hours = p.get("hours_silent", 0)
lines.append(f" • `{svc}` — {msg} (silent {hours}h)")
else:
lines.append(" *(no patterns)*")
if len(resolved_patterns) > 8:
lines.append(f" … and {len(resolved_patterns) - 8} more")
lines.append("")
lines.append(f"**Resolved at:** {_now_eastern()}")
return _truncate("\n".join(lines))
def format_spike_alert(
service: str,
normalized_message: str,
current_count: int,
rolling_average: float,
) -> str:
"""Format a Discord alert for an error rate spike.
Args:
service: Name of the service.
normalized_message: Normalised error pattern string.
current_count: Error count in the current window.
rolling_average: Baseline rolling average count.
Returns:
Formatted Discord message string, truncated to 2000 chars.
"""
if rolling_average > 0:
multiplier = current_count / rolling_average
multiplier_str = f"{multiplier:.1f}x"
else:
multiplier_str = "∞x"
lines = [
f"⚠️ **Error Rate Spike Detected**",
f"",
f"**Service:** {service}",
f"**Pattern:** {normalized_message}",
f"**Current count:** {current_count}",
f"**Normal (rolling avg):** {rolling_average}",
f"**Multiplier:** {multiplier_str} above normal",
f"",
f"**Alerted at:** {_now_eastern()}",
]
return _truncate("\n".join(lines))
def format_daily_digest(
total_errors: int,
new_patterns: int,
resolved_patterns: int,
active_patterns: int,
per_service_counts: dict,
) -> str:
"""Format the daily 24h error digest.
Args:
total_errors: Total error count in the last 24 hours.
new_patterns: Number of new error patterns detected.
resolved_patterns: Number of patterns auto-resolved.
active_patterns: Total number of currently active patterns.
per_service_counts: Mapping of service name → error count.
Displayed sorted by count descending.
Returns:
Formatted Discord message string, truncated to 2000 chars.
"""
lines = [
f"📊 **Daily Error Digest (24h)**",
f"",
f"**Total errors:** {total_errors}",
f"**New patterns:** {new_patterns}",
f"**Resolved patterns:** {resolved_patterns}",
f"**Active patterns:** {active_patterns}",
]
if per_service_counts:
lines.append("")
lines.append("**Per-service breakdown:**")
sorted_services = sorted(per_service_counts.items(), key=lambda kv: kv[1], reverse=True)
for svc, cnt in sorted_services:
lines.append(f" • `{svc}`: {cnt}")
lines.append("")
lines.append(f"**Generated at:** {_now_eastern()}")
return _truncate("\n".join(lines))
# ---------------------------------------------------------------------------
# Discord webhook client
# ---------------------------------------------------------------------------
class ErrorMonitorDiscord:
"""Webhook client for sending error monitor alerts to Discord.
Enforces a per-run rate limit of MAX_DISCORD_MESSAGES_PER_RUN to avoid
flooding the channel during high-volume incident windows.
Attributes:
webhook_url: The Discord incoming webhook URL.
messages_sent: Counter of messages attempted this run (success or failure).
"""
def __init__(self, webhook_url: str) -> None:
self.webhook_url = webhook_url
self.messages_sent: int = 0
def send_message(self, content: str) -> bool:
"""Send a message to the configured Discord webhook.
Rate-limits: if messages_sent >= MAX_DISCORD_MESSAGES_PER_RUN, the
message is silently skipped and False is returned without incrementing
the counter.
Args:
content: The message text to send (should be pre-formatted and
pre-truncated to ≤2000 chars).
Returns:
True if the message was sent successfully, False otherwise.
"""
if self.messages_sent >= MAX_DISCORD_MESSAGES_PER_RUN:
logger.warning(
"Discord rate limit reached (%d messages sent this run); skipping message.",
self.messages_sent,
)
return False
try:
response = requests.post(
self.webhook_url,
json={"content": content, "flags": 4}, # SUPPRESS_EMBEDS
timeout=30,
)
response.raise_for_status()
logger.debug("Discord message sent successfully.")
return True
except Exception as exc:
logger.error("Failed to send Discord message: %s", exc)
return False
finally:
self.messages_sent += 1
@@ -0,0 +1,489 @@
"""Firestore adapter for the production error monitoring service.
Handles all CRUD for three Firestore collections:
- error_patterns: normalized error patterns (pattern_id as doc ID)
- error_incidents: groups of related patterns (incident_id as doc ID)
- discord_alerts: audit trail for Discord messages (alert_id as doc ID)
"""
from __future__ import annotations
import secrets
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from typing import Any
from backend.services.error_monitor.config import (
AUTO_RESOLVE_FALLBACK_HOURS,
AUTO_RESOLVE_MAX_HOURS,
AUTO_RESOLVE_MIN_HOURS,
AUTO_RESOLVE_MULTIPLIER,
ROLLING_WINDOW_DAYS,
)
# ---------------------------------------------------------------------------
# Data classes
# ---------------------------------------------------------------------------
@dataclass
class PatternData:
"""Input data for creating or updating an error pattern."""
pattern_id: str
service: str
resource_type: str
normalized_message: str
sample_message: str
count: int
timestamp: datetime
@dataclass
class UpsertResult:
"""Result of an upsert_pattern operation."""
pattern_id: str
is_new: bool
previous_status: str | None = None
# ---------------------------------------------------------------------------
# Collection names
# ---------------------------------------------------------------------------
_COL_PATTERNS = "error_patterns"
_COL_INCIDENTS = "error_incidents"
_COL_ALERTS = "discord_alerts"
# Statuses that can be queried as "active"
_ACTIVE_STATUSES = ["new", "acknowledged", "known"]
# Statuses from which a pattern is reactivated when the error recurs
_REACTIVATION_STATUSES = {"auto_resolved", "fixed"}
# Statuses eligible for auto-resolve checking
_AUTO_RESOLVE_ELIGIBLE = {"new", "acknowledged"}
def _utcnow() -> datetime:
"""Return current UTC datetime."""
return datetime.now(tz=timezone.utc)
def _iso(dt: datetime) -> str:
"""Serialise a datetime to ISO-8601 string."""
return dt.isoformat()
def _generate_id(prefix: str, fmt: str) -> str:
"""Generate a time-stamped ID with 8 hex random suffix.
Args:
prefix: e.g. "inc" or "alert"
fmt: strftime format string applied to utcnow(), e.g. "%Y%m%d_%H%M"
"""
ts = _utcnow().strftime(fmt)
suffix = secrets.token_hex(4) # 8 hex chars
return f"{prefix}_{ts}_{suffix}"
# ---------------------------------------------------------------------------
# Adapter
# ---------------------------------------------------------------------------
class ErrorPatternsAdapter:
"""Firestore CRUD adapter for error monitoring collections.
Args:
db: Optional Firestore client. If omitted, a default client for the
``nomadkaraoke`` GCP project is constructed on first use.
"""
def __init__(self, db=None) -> None:
if db is None:
from google.cloud import firestore # type: ignore[import]
db = firestore.Client(project="nomadkaraoke")
self._db = db
# ------------------------------------------------------------------
# Patterns — read
# ------------------------------------------------------------------
def get_pattern(self, pattern_id: str) -> dict | None:
"""Return the pattern document as a dict, or None if it doesn't exist.
Args:
pattern_id: Firestore document ID in the ``error_patterns`` collection.
"""
snap = self._db.collection(_COL_PATTERNS).document(pattern_id).get()
if not snap.exists:
return None
return snap.to_dict()
def get_active_patterns(self) -> list[dict]:
"""Return all patterns with status in [new, acknowledged, known]."""
query = self._db.collection(_COL_PATTERNS).where(
"status", "in", _ACTIVE_STATUSES
)
return [snap.to_dict() for snap in query.stream()]
def get_patterns_for_auto_resolve(self) -> list[dict]:
"""Return active patterns eligible for auto-resolution (new or acknowledged)."""
query = self._db.collection(_COL_PATTERNS).where(
"status", "in", list(_AUTO_RESOLVE_ELIGIBLE)
)
return [snap.to_dict() for snap in query.stream()]
# ------------------------------------------------------------------
# Patterns — upsert
# ------------------------------------------------------------------
def upsert_pattern(self, data: PatternData) -> UpsertResult:
"""Create a new pattern or update an existing one.
New pattern:
- status="new", severity="P3"
- Initialize ``rolling_counts`` with one entry for this run.
Existing pattern:
- Increment ``total_count`` and append to ``rolling_counts``.
- If status was ``auto_resolved`` or ``fixed`` → reactivate (set status="new").
- Prune ``rolling_counts`` entries older than ROLLING_WINDOW_DAYS.
Returns:
UpsertResult with ``is_new=True`` for brand-new patterns *and* for
reactivated patterns (auto_resolved → new, fixed → new).
"""
doc_ref = self._db.collection(_COL_PATTERNS).document(data.pattern_id)
snap = doc_ref.get()
ts_iso = _iso(data.timestamp)
new_rolling_entry = {"ts": ts_iso, "count": data.count}
if not snap.exists:
# ── brand new pattern ──────────────────────────────────────────
doc_ref.set(
{
"pattern_id": data.pattern_id,
"service": data.service,
"resource_type": data.resource_type,
"normalized_message": data.normalized_message,
"sample_message": data.sample_message,
"status": "new",
"severity": "P3",
"total_count": data.count,
"rolling_counts": [new_rolling_entry],
"first_seen": ts_iso,
"last_seen": ts_iso,
"alerted_at": None,
"created_at": ts_iso,
"updated_at": ts_iso,
}
)
return UpsertResult(pattern_id=data.pattern_id, is_new=True)
# ── existing pattern ───────────────────────────────────────────────
existing = snap.to_dict()
prev_status = existing.get("status", "new")
rolling_counts: list[dict] = list(existing.get("rolling_counts") or [])
rolling_counts.append(new_rolling_entry)
rolling_counts = self._prune_rolling_counts(rolling_counts)
update: dict[str, Any] = {
"total_count": existing.get("total_count", 0) + data.count,
"rolling_counts": rolling_counts,
"last_seen": ts_iso,
"sample_message": data.sample_message,
"updated_at": ts_iso,
}
# Reactivation: pattern was considered resolved/fixed but error recurred
is_new = False
if prev_status in _REACTIVATION_STATUSES:
update["status"] = "new"
update["alerted_at"] = None
is_new = True
doc_ref.update(update)
return UpsertResult(
pattern_id=data.pattern_id,
is_new=is_new,
previous_status=prev_status,
)
# ------------------------------------------------------------------
# Patterns — status changes
# ------------------------------------------------------------------
def auto_resolve_pattern(self, pattern_id: str, hours_silent: float) -> None:
"""Mark a pattern as auto-resolved.
Args:
pattern_id: Firestore document ID.
hours_silent: How many hours the pattern has been silent.
"""
self._db.collection(_COL_PATTERNS).document(pattern_id).update(
{
"status": "auto_resolved",
"auto_resolve_hours_silent": hours_silent,
"auto_resolved_at": _iso(_utcnow()),
"updated_at": _iso(_utcnow()),
}
)
def resolve_pattern(
self,
pattern_id: str,
pr_url: str | None = None,
note: str = "",
) -> None:
"""Mark a pattern as fixed (human-resolved).
Args:
pattern_id: Firestore document ID.
pr_url: Optional URL of the PR that fixed this pattern.
note: Optional human-readable note about the fix.
"""
now_iso = _iso(_utcnow())
self._db.collection(_COL_PATTERNS).document(pattern_id).update(
{
"status": "fixed",
"fixed_by": {
"pr_url": pr_url,
"note": note,
"fixed_at": now_iso,
},
"updated_at": now_iso,
}
)
def update_pattern_alerted(self, pattern_id: str) -> None:
"""Set the ``alerted_at`` timestamp on a pattern.
Called after a Discord alert has been successfully sent for the pattern.
"""
self._db.collection(_COL_PATTERNS).document(pattern_id).update(
{
"alerted_at": _iso(_utcnow()),
"updated_at": _iso(_utcnow()),
}
)
def merge_pattern(self, source_id: str, target_id: str, reason: str) -> None:
"""Merge *source* into *target* by muting the source pattern.
Args:
source_id: Pattern to mute.
target_id: Pattern that the source is being merged into.
reason: Human-readable rationale for the merge.
"""
self._db.collection(_COL_PATTERNS).document(source_id).update(
{
"status": "muted",
"merged_into": target_id,
"merge_reason": reason,
"updated_at": _iso(_utcnow()),
}
)
# ------------------------------------------------------------------
# Auto-resolve logic
# ------------------------------------------------------------------
def check_auto_resolve(self, pattern: dict) -> float | None:
"""Determine whether *pattern* should be auto-resolved.
Computes the frequency-aware silence threshold and compares it against
how long the pattern has been silent.
Args:
pattern: A pattern document dict (as returned by get_pattern).
Returns:
The number of hours the pattern has been silent if the threshold is
exceeded, or ``None`` if the pattern should not yet be resolved.
"""
status = pattern.get("status", "")
if status not in _AUTO_RESOLVE_ELIGIBLE:
return None
last_seen_str = pattern.get("last_seen")
if not last_seen_str:
return None
last_seen = datetime.fromisoformat(last_seen_str)
now = datetime.now(tz=timezone.utc)
# Ensure both datetimes are tz-aware for subtraction
if last_seen.tzinfo is None:
last_seen = last_seen.replace(tzinfo=timezone.utc)
hours_silent = (now - last_seen).total_seconds() / 3600.0
rolling_counts = pattern.get("rolling_counts") or []
threshold = self._compute_resolve_threshold(rolling_counts)
if hours_silent >= threshold:
return hours_silent
return None
def _compute_resolve_threshold(self, rolling_counts: list[dict]) -> float:
"""Compute the frequency-aware auto-resolve threshold in hours.
Algorithm:
1. If fewer than 3 data points → return AUTO_RESOLVE_FALLBACK_HOURS (48).
2. Compute mean interval between consecutive timestamps.
3. threshold = mean_interval_hours * AUTO_RESOLVE_MULTIPLIER.
4. Clamp result to [AUTO_RESOLVE_MIN_HOURS, AUTO_RESOLVE_MAX_HOURS].
Args:
rolling_counts: List of ``{"ts": ISO-string, "count": int}`` dicts.
Returns:
Threshold in hours (float).
"""
if len(rolling_counts) < 3:
return float(AUTO_RESOLVE_FALLBACK_HOURS)
# Parse timestamps and sort ascending
timestamps: list[datetime] = []
for entry in rolling_counts:
ts = datetime.fromisoformat(entry["ts"])
if ts.tzinfo is None:
ts = ts.replace(tzinfo=timezone.utc)
timestamps.append(ts)
timestamps.sort()
# Compute pairwise intervals
intervals_hours: list[float] = []
for i in range(1, len(timestamps)):
delta = (timestamps[i] - timestamps[i - 1]).total_seconds() / 3600.0
intervals_hours.append(delta)
if not intervals_hours:
return float(AUTO_RESOLVE_FALLBACK_HOURS)
mean_interval = sum(intervals_hours) / len(intervals_hours)
threshold = mean_interval * AUTO_RESOLVE_MULTIPLIER
# Clamp to configured bounds
threshold = max(float(AUTO_RESOLVE_MIN_HOURS), threshold)
threshold = min(float(AUTO_RESOLVE_MAX_HOURS), threshold)
return threshold
def _prune_rolling_counts(self, rolling_counts: list[dict]) -> list[dict]:
"""Remove rolling_count entries older than ROLLING_WINDOW_DAYS.
Args:
rolling_counts: List of ``{"ts": ISO-string, "count": int}`` dicts.
Returns:
Filtered list with only recent entries.
"""
if not rolling_counts:
return []
cutoff = _utcnow() - timedelta(days=ROLLING_WINDOW_DAYS)
result = []
for entry in rolling_counts:
ts = datetime.fromisoformat(entry["ts"])
if ts.tzinfo is None:
ts = ts.replace(tzinfo=timezone.utc)
if ts >= cutoff:
result.append(entry)
return result
# ------------------------------------------------------------------
# Incidents
# ------------------------------------------------------------------
def create_incident(
self,
title: str,
root_cause: str,
severity: str,
suggested_fix: str,
primary_service: str,
pattern_ids: list[str],
used_llm: bool,
) -> str:
"""Create a new incident document and link associated patterns.
Args:
title: Short human-readable title.
root_cause: LLM-generated or manual root-cause description.
severity: Severity string (e.g. "P1", "P2", "P3").
suggested_fix: Suggested remediation steps.
primary_service: The primary affected service.
pattern_ids: List of pattern_ids that belong to this incident.
used_llm: Whether LLM analysis was used to generate this incident.
Returns:
The generated incident_id string.
"""
incident_id = _generate_id("inc", "%Y%m%d_%H%M")
now_iso = _iso(_utcnow())
self._db.collection(_COL_INCIDENTS).document(incident_id).set(
{
"incident_id": incident_id,
"title": title,
"root_cause": root_cause,
"severity": severity,
"suggested_fix": suggested_fix,
"primary_service": primary_service,
"pattern_ids": pattern_ids,
"used_llm": used_llm,
"created_at": now_iso,
"updated_at": now_iso,
"status": "open",
}
)
# Link each pattern back to this incident
for pattern_id in pattern_ids:
self._db.collection(_COL_PATTERNS).document(pattern_id).update(
{
"incident_id": incident_id,
"updated_at": now_iso,
}
)
return incident_id
# ------------------------------------------------------------------
# Discord audit trail
# ------------------------------------------------------------------
def log_discord_alert(
self,
alert_type: str,
content: str,
success: bool,
metadata: dict | None = None,
) -> None:
"""Write an audit record to the ``discord_alerts`` collection.
Args:
alert_type: Category of alert (e.g. "new_pattern", "digest").
content: The message body that was (or would have been) sent.
success: Whether the Discord webhook call succeeded.
metadata: Optional additional data (pattern_ids, incident_id, etc.).
"""
alert_id = _generate_id("alert", "%Y%m%d_%H%M%S")
now_iso = _iso(_utcnow())
self._db.collection(_COL_ALERTS).document(alert_id).set(
{
"alert_id": alert_id,
"alert_type": alert_type,
"content": content,
"success": success,
"metadata": metadata or {},
"created_at": now_iso,
}
)
@@ -0,0 +1,106 @@
"""Known infrastructure noise patterns for the production error monitoring service.
Filters out transient, expected log messages so the error monitor is not flooded
with Cloud Run cold-start probes, deploy events, spot VM preemptions, and similar
operational noise.
Usage:
from backend.services.error_monitor.known_issues import should_ignore
reason = should_ignore(service, message)
if reason:
# skip this log entry — it's known infrastructure noise
...
"""
import re
from dataclasses import dataclass
@dataclass
class IgnoreReason:
"""Describes why a log entry should be suppressed.
Attributes:
pattern_name: Machine-readable name of the matching ignore pattern.
reason: Human-readable explanation of why this is infrastructure noise.
"""
pattern_name: str
reason: str
# ---------------------------------------------------------------------------
# Compiled ignore patterns (applied in order)
# All patterns use re.IGNORECASE for case-insensitive matching.
# ---------------------------------------------------------------------------
_IGNORE_PATTERNS: list[tuple[str, re.Pattern, str]] = [
(
"startup_probe",
re.compile(r"startup probe failed", re.IGNORECASE),
"Cloud Run cold start — startup probe failure is transient and expected",
),
(
"ready_condition",
re.compile(r"ready condition status changed", re.IGNORECASE),
"Cloud Run deploy event — readiness condition change is expected on deploy",
),
(
"spot_preemption",
re.compile(r"instance was preempted", re.IGNORECASE),
"Spot/preemptible VM preemption — expected behaviour for spot instances",
),
(
"idle_shutdown",
re.compile(r"stopping idle encoding worker", re.IGNORECASE),
"Encoding worker idle shutdown — expected behaviour when no jobs are queued",
),
(
"health_check_404",
re.compile(
r"(?:GET|HEAD)\b[^\n]*?/health[^\n]*?\b(?:404|not found)\b",
re.IGNORECASE,
),
"Load balancer health check returning 404 — transient during cold start",
),
(
"scheduler_retry",
re.compile(r"cloud scheduler.*retry", re.IGNORECASE),
"Cloud Scheduler transient retry — expected on intermittent job failures",
),
(
"runner_startup",
re.compile(r"github\.runner\..*(?:starting|stopping|idle)", re.IGNORECASE),
"GitHub Actions runner lifecycle event — expected during runner start/stop",
),
(
"container_shutdown",
re.compile(r"container called exit\(0\)", re.IGNORECASE),
"Container clean exit — exit code 0 indicates a graceful, expected shutdown",
),
]
def should_ignore(service: str, message: str) -> IgnoreReason | None:
"""Check whether a log entry matches a known infrastructure noise pattern.
The check is purely message-based; ``service`` is accepted for API symmetry
and future service-specific overrides but does not gate any pattern today.
Args:
service: The originating service name (e.g. ``"karaoke-backend"``).
message: The raw log message string to evaluate.
Returns:
An :class:`IgnoreReason` if the message matches a known noise pattern,
or ``None`` if the message should be processed normally.
"""
if not message:
return None
for pattern_name, pattern, reason in _IGNORE_PATTERNS:
if pattern.search(message):
return IgnoreReason(pattern_name=pattern_name, reason=reason)
return None
@@ -0,0 +1,429 @@
"""LLM-powered incident analysis and duplicate detection for the error monitor.
Uses Gemini Flash via the google-generativeai library to:
1. Group related error patterns into incidents with root-cause analysis.
2. Identify near-duplicate patterns that the regex normalizer missed.
Both functions fall back gracefully when the LLM is unavailable or returns
unparseable output.
"""
from __future__ import annotations
import json
import logging
import re
import time
from collections import defaultdict
from dataclasses import dataclass, field
from google import genai
from google.genai import types as genai_types
from backend.services.error_monitor.config import (
GCP_PROJECT,
LLM_ANALYSIS_MODEL,
LLM_VERTEX_LOCATION,
MIN_PATTERNS_FOR_ANALYSIS,
SERVICE_DEPENDENCY_MAP,
)
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Dataclasses
# ---------------------------------------------------------------------------
@dataclass
class Incident:
"""A grouped incident produced by LLM analysis or the fallback grouper."""
title: str
root_cause: str | None
severity: str # P0 / P1 / P2 / P3
suggested_fix: str | None
primary_service: str
pattern_indices: list[int]
@dataclass
class IncidentAnalysis:
"""The result of an incident grouping pass."""
incidents: list[Incident]
used_llm: bool = True
@dataclass
class DuplicateGroup:
"""A canonical pattern plus the new patterns that duplicate it."""
canonical_index: int
duplicate_indices: list[int]
reason: str
# ---------------------------------------------------------------------------
# LLM call helper
# ---------------------------------------------------------------------------
_RETRY_ATTEMPTS = 3
_RETRY_BASE_DELAY = 2.0 # seconds
def _call_llm(
system_prompt: str,
user_prompt: str,
temperature: float = 0.2,
) -> str:
"""Call Gemini and return the response text.
Retries up to _RETRY_ATTEMPTS times with exponential back-off on failure.
Args:
system_prompt: System instruction for the model.
user_prompt: User-facing prompt content.
temperature: Sampling temperature (lower = more deterministic).
Returns:
The model's response text.
Raises:
Exception: Re-raises the last exception after all retries are exhausted.
"""
last_exc: Exception | None = None
for attempt in range(_RETRY_ATTEMPTS):
try:
client = genai.Client(
vertexai=True,
project=GCP_PROJECT,
location=LLM_VERTEX_LOCATION,
)
response = client.models.generate_content(
model=LLM_ANALYSIS_MODEL,
contents=user_prompt,
config=genai_types.GenerateContentConfig(
system_instruction=system_prompt,
temperature=temperature,
),
)
return response.text
except Exception as exc: # noqa: BLE001
last_exc = exc
delay = _RETRY_BASE_DELAY * (2**attempt)
logger.warning(
"LLM call failed (attempt %d/%d): %s — retrying in %.1fs",
attempt + 1,
_RETRY_ATTEMPTS,
exc,
delay,
)
time.sleep(delay)
raise last_exc # type: ignore[misc]
# ---------------------------------------------------------------------------
# Response parsing
# ---------------------------------------------------------------------------
_MD_CODE_BLOCK_RE = re.compile(r"```(?:json)?\s*([\s\S]*?)```", re.IGNORECASE)
def _strip_markdown_code_block(text: str) -> str:
"""Remove surrounding ```json ... ``` or ``` ... ``` fences if present."""
match = _MD_CODE_BLOCK_RE.search(text)
if match:
return match.group(1).strip()
return text.strip()
def _parse_llm_response(text: str) -> IncidentAnalysis | None:
"""Parse the LLM response text into an IncidentAnalysis.
Args:
text: Raw LLM output, possibly wrapped in a markdown code block.
Returns:
IncidentAnalysis on success, None on any parse failure.
"""
if not text:
return None
cleaned = _strip_markdown_code_block(text)
try:
data = json.loads(cleaned)
except json.JSONDecodeError:
logger.warning("LLM returned non-JSON response (first 200 chars): %.200s", text)
return None
if "incidents" not in data:
logger.warning("LLM response missing 'incidents' key: %s", list(data.keys()))
return None
incidents: list[Incident] = []
for raw in data["incidents"]:
try:
incidents.append(
Incident(
title=raw.get("title", "Unknown incident"),
root_cause=raw.get("root_cause"),
severity=raw.get("severity", "P2"),
suggested_fix=raw.get("suggested_fix"),
primary_service=raw.get("primary_service", "unknown"),
pattern_indices=raw.get("pattern_indices", []),
)
)
except Exception as exc: # noqa: BLE001
logger.warning("Skipping malformed incident entry: %s — %s", raw, exc)
return IncidentAnalysis(incidents=incidents, used_llm=True)
# ---------------------------------------------------------------------------
# Fallback grouper
# ---------------------------------------------------------------------------
def _fallback_group_by_service(patterns: list[dict]) -> IncidentAnalysis:
"""Group patterns by service name when the LLM is unavailable.
Each unique service becomes one P2 incident containing all of that
service's pattern indices.
Args:
patterns: List of error pattern dicts (must include 'service' key).
Returns:
IncidentAnalysis with used_llm=False.
"""
service_to_indices: dict[str, list[int]] = defaultdict(list)
for idx, pattern in enumerate(patterns):
service = pattern.get("service", "unknown")
service_to_indices[service].append(idx)
incidents = [
Incident(
title=f"Errors in {service}",
root_cause=None,
severity="P2",
suggested_fix=None,
primary_service=service,
pattern_indices=indices,
)
for service, indices in service_to_indices.items()
]
return IncidentAnalysis(incidents=incidents, used_llm=False)
# ---------------------------------------------------------------------------
# Main analysis functions
# ---------------------------------------------------------------------------
_ANALYZE_SYSTEM_PROMPT = f"""\
You are an expert site-reliability engineer for Nomad Karaoke, a karaoke video
generation platform running on Google Cloud Platform.
Your task is to analyse a list of active error patterns detected across
production services, group them into meaningful incidents, and identify root
causes.
## Service dependency map
{SERVICE_DEPENDENCY_MAP}
## Severity definitions
- P0: Service is completely down / total outage
- P1: Major pipeline broken — orders cannot complete
- P2: Degraded performance — some orders affected
- P3: Minor / cosmetic issue with no direct user impact
## Output format
Respond with a single JSON object (no markdown fencing) with this schema:
{{
"incidents": [
{{
"title": "<short human-readable title>",
"root_cause": "<root cause or null>",
"severity": "P0|P1|P2|P3",
"suggested_fix": "<actionable suggestion or null>",
"primary_service": "<service name>",
"pattern_indices": [<list of 0-based indices from the input list>]
}}
]
}}
Group related patterns together into a single incident where they share a
common root cause (e.g., a downstream dependency failure). Unrelated patterns
should be in separate incidents. Every input pattern must appear in exactly
one incident.
"""
_DEDUP_SYSTEM_PROMPT = """\
You are an expert at identifying near-duplicate error patterns in production
monitoring systems.
Your task is to compare a list of NEW error patterns against a list of
EXISTING (canonical) patterns and identify which new patterns are essentially
duplicates of existing ones — i.e., they describe the same underlying error
but with slightly different wording due to variation in log messages.
## Output format
Respond with a single JSON object (no markdown fencing) with this schema:
{
"duplicates": [
{
"canonical_index": <0-based index into the EXISTING patterns list>,
"duplicate_indices": [<0-based indices into the NEW patterns list>],
"reason": "<brief explanation>"
}
]
}
If no duplicates are found, return {"duplicates": []}.
"""
def analyze_patterns(patterns: list[dict]) -> IncidentAnalysis | None:
"""Group error patterns into incidents using Gemini LLM analysis.
Returns None if there are fewer than MIN_PATTERNS_FOR_ANALYSIS patterns.
Falls back to service-based grouping when the LLM fails or returns an
unparseable response.
Args:
patterns: List of error pattern dicts to analyse.
Returns:
IncidentAnalysis, or None if insufficient patterns.
"""
if len(patterns) < MIN_PATTERNS_FOR_ANALYSIS:
return None
user_prompt = _build_analyze_user_prompt(patterns)
try:
raw_response = _call_llm(_ANALYZE_SYSTEM_PROMPT, user_prompt, temperature=0.2)
result = _parse_llm_response(raw_response)
if result is not None:
return result
logger.warning("LLM returned unparseable response; falling back to service grouping")
except Exception as exc: # noqa: BLE001
logger.warning("LLM analysis failed: %s — falling back to service grouping", exc)
return _fallback_group_by_service(patterns)
def find_duplicate_patterns(
new_patterns: list[dict],
existing_patterns: list[dict],
) -> list[DuplicateGroup]:
"""Identify near-duplicate patterns that the regex normalizer missed.
Returns an empty list if either input list is empty, or if the LLM call
fails for any reason.
Args:
new_patterns: Newly detected error patterns to check.
existing_patterns: Currently tracked (canonical) error patterns.
Returns:
List of DuplicateGroup objects (may be empty).
"""
if not new_patterns or not existing_patterns:
return []
user_prompt = _build_dedup_user_prompt(new_patterns, existing_patterns)
try:
raw_response = _call_llm(_DEDUP_SYSTEM_PROMPT, user_prompt, temperature=0.1)
return _parse_duplicate_response(raw_response)
except Exception as exc: # noqa: BLE001
logger.warning("Duplicate detection LLM call failed: %s", exc)
return []
# ---------------------------------------------------------------------------
# Prompt builders
# ---------------------------------------------------------------------------
def _build_analyze_user_prompt(patterns: list[dict]) -> str:
"""Build the user prompt listing patterns for incident grouping."""
lines = ["Error patterns to analyse:\n"]
for idx, pattern in enumerate(patterns):
service = pattern.get("service", "unknown")
message = pattern.get("normalized_message", "")
count = pattern.get("count", 0)
lines.append(f"[{idx}] service={service!r} count={count} message={message!r}")
return "\n".join(lines)
def _build_dedup_user_prompt(
new_patterns: list[dict],
existing_patterns: list[dict],
) -> str:
"""Build the user prompt listing existing and new patterns for dedup."""
lines = ["EXISTING (canonical) patterns:\n"]
for idx, pattern in enumerate(existing_patterns):
service = pattern.get("service", "unknown")
message = pattern.get("normalized_message", "")
lines.append(f"[{idx}] service={service!r} message={message!r}")
lines.append("\nNEW patterns to check:\n")
for idx, pattern in enumerate(new_patterns):
service = pattern.get("service", "unknown")
message = pattern.get("normalized_message", "")
lines.append(f"[{idx}] service={service!r} message={message!r}")
return "\n".join(lines)
def _parse_duplicate_response(text: str) -> list[DuplicateGroup]:
"""Parse the LLM response for duplicate detection.
Args:
text: Raw LLM output.
Returns:
List of DuplicateGroup objects, or [] on any failure.
"""
if not text:
return []
cleaned = _strip_markdown_code_block(text)
try:
data = json.loads(cleaned)
except json.JSONDecodeError:
logger.warning("Dedup LLM returned non-JSON: %.200s", text)
return []
if "duplicates" not in data:
logger.warning("Dedup LLM response missing 'duplicates' key")
return []
groups: list[DuplicateGroup] = []
for raw in data["duplicates"]:
try:
groups.append(
DuplicateGroup(
canonical_index=int(raw["canonical_index"]),
duplicate_indices=list(raw.get("duplicate_indices", [])),
reason=raw.get("reason", ""),
)
)
except Exception as exc: # noqa: BLE001
logger.warning("Skipping malformed duplicate entry: %s — %s", raw, exc)
return groups
+641
View File
@@ -0,0 +1,641 @@
"""Monitor orchestrator for the production error monitoring service.
This is the main entry point. Run as::
python -m backend.services.error_monitor.monitor
The ``ErrorMonitor.run()`` method executes the full pipeline:
* Monitor cycle (default) — query Cloud Logging, detect new patterns, send
Discord alerts, check auto-resolution.
* Daily digest mode (``DIGEST_MODE=true``) — bundle 24h stats into one message.
"""
from __future__ import annotations
import logging
import os
from datetime import datetime, timedelta, timezone
from typing import Any
from google.cloud import logging as cloud_logging
from google.cloud import secretmanager
from backend.services.error_monitor.config import (
GCP_PROJECT,
LOOKBACK_MINUTES,
MAX_LOG_ENTRIES,
MONITORED_CLOUD_FUNCTIONS,
MONITORED_CLOUD_RUN_JOBS,
MONITORED_CLOUD_RUN_SERVICES,
MONITORED_GCE_INSTANCES,
SPIKE_MIN_COUNT,
SPIKE_MULTIPLIER,
get_digest_mode,
get_discord_webhook_secret_name,
get_llm_enabled,
)
from backend.services.error_monitor.discord import (
ErrorMonitorDiscord,
format_auto_resolved_alert,
format_daily_digest,
format_incident_alert,
format_new_pattern_alert,
format_spike_alert,
)
from backend.services.error_monitor.firestore_adapter import (
ErrorPatternsAdapter,
PatternData,
UpsertResult,
)
from backend.services.error_monitor.known_issues import should_ignore
from backend.services.error_monitor.llm_analysis import analyze_patterns, find_duplicate_patterns
from backend.services.error_monitor.normalizer import compute_pattern_hash, normalize_message
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Module-level constants
# ---------------------------------------------------------------------------
#: Maps log resource type → (label_key, service_name_list)
RESOURCE_TYPE_FILTERS: dict[str, tuple[str, list[str]]] = {
"cloud_run_revision": ("resource.labels.service_name", MONITORED_CLOUD_RUN_SERVICES),
"cloud_run_job": ("resource.labels.job_name", MONITORED_CLOUD_RUN_JOBS),
"cloud_function": ("resource.labels.function_name", MONITORED_CLOUD_FUNCTIONS),
"gce_instance": ('labels."compute.googleapis.com/resource_name"', MONITORED_GCE_INSTANCES),
}
#: Maps log resource type → canonical resource_type string stored in Firestore.
RESOURCE_TYPE_MAP: dict[str, str] = {
"cloud_run_revision": "cloud_run_service",
"cloud_run_job": "cloud_run_job",
"cloud_function": "cloud_function",
"gce_instance": "gce_instance",
}
# ---------------------------------------------------------------------------
# Free functions
# ---------------------------------------------------------------------------
def _build_log_filter(
resource_type: str,
resource_names: list[str],
lookback_minutes: int,
) -> str:
"""Build a Cloud Logging filter string.
Args:
resource_type: GCP resource type (e.g. ``"cloud_run_revision"``).
resource_names: List of service/job/function/instance names to include.
lookback_minutes: How many minutes back to query.
Returns:
A filter string suitable for ``logging_client.list_entries(filter_=...)``.
"""
label_key = RESOURCE_TYPE_FILTERS[resource_type][0]
cutoff = datetime.now(tz=timezone.utc) - timedelta(minutes=lookback_minutes)
cutoff_iso = cutoff.strftime("%Y-%m-%dT%H:%M:%SZ")
name_clause = " OR ".join(f'{label_key}="{name}"' for name in resource_names)
if len(resource_names) > 1:
name_clause = f"({name_clause})"
return (
f'resource.type="{resource_type}" '
f"severity>=ERROR "
f'timestamp>="{cutoff_iso}" '
f"{name_clause}"
)
def _extract_message(entry: Any) -> str | None:
"""Extract the log message text from a Cloud Logging entry.
Handles several payload shapes:
* ``str`` payload — returned directly.
* ``dict`` payload — tries ``"message"``, ``"textPayload"``, ``"error"``,
``"msg"`` keys in that order.
* ``None`` payload — returns ``None``.
Args:
entry: A Cloud Logging ``LogEntry`` object.
Returns:
The message string, or ``None`` if not extractable.
"""
payload = entry.payload
if payload is None:
return None
if isinstance(payload, str):
return payload if payload else None
if isinstance(payload, dict):
for key in ("message", "textPayload", "error", "msg"):
value = payload.get(key)
if value:
return str(value)
return None
# Fallback: convert to string representation
text = str(payload)
return text if text else None
def _extract_service_name(entry: Any, resource_type: str) -> str:
"""Extract the service/job/function/instance name from a log entry.
Args:
entry: A Cloud Logging ``LogEntry`` object.
resource_type: GCP log resource type string.
Returns:
The service name string (falls back to ``"unknown"`` if not found).
"""
labels = getattr(entry.resource, "labels", {}) or {}
entry_labels = getattr(entry, "labels", {}) or {}
if resource_type == "cloud_run_revision":
return labels.get("service_name") or "unknown"
if resource_type == "cloud_run_job":
return labels.get("job_name") or "unknown"
if resource_type == "cloud_function":
return labels.get("function_name") or "unknown"
if resource_type == "gce_instance":
# Prefer the human-readable resource name label
name = entry_labels.get("compute.googleapis.com/resource_name")
if name:
return name
return labels.get("instance_id") or "unknown"
return "unknown"
def _classify_resource_type(log_resource_type: str) -> str:
"""Map a Cloud Logging resource type to the canonical type stored in Firestore.
Args:
log_resource_type: Raw GCP resource type (e.g. ``"cloud_run_revision"``).
Returns:
Canonical resource type string (falls back to the input if not in map).
"""
return RESOURCE_TYPE_MAP.get(log_resource_type, log_resource_type)
def _group_by_pattern(entries: list[dict]) -> dict[str, dict]:
"""Group normalised log entries by their pattern hash.
Args:
entries: List of dicts with ``service``, ``normalized``, and ``message`` keys.
Returns:
Dict mapping ``pattern_id`` → group dict containing ``service``,
``resource_type``, ``normalized``, ``sample_message``, ``count``.
"""
groups: dict[str, dict] = {}
for entry in entries:
service = entry["service"]
normalized = entry["normalized"]
pattern_id = compute_pattern_hash(service, normalized)
if pattern_id not in groups:
groups[pattern_id] = {
"pattern_id": pattern_id,
"service": service,
"resource_type": entry.get("resource_type", "unknown"),
"normalized": normalized,
"sample_message": entry["message"],
"count": 0,
}
groups[pattern_id]["count"] += 1
return groups
def _rolling_average(rolling_counts: list[dict]) -> float:
"""Compute the mean count from a list of rolling_count dicts.
Args:
rolling_counts: List of ``{"count": int, ...}`` dicts.
Returns:
The arithmetic mean as a float, or ``0.0`` for an empty list.
"""
if not rolling_counts:
return 0.0
total = sum(entry.get("count", 0) for entry in rolling_counts)
return total / len(rolling_counts)
def _is_spike(current_count: int, rolling_counts: list[dict]) -> bool:
"""Determine whether ``current_count`` represents an error rate spike.
A spike is detected when:
- ``current_count`` >= ``SPIKE_MIN_COUNT`` (avoids noise from rare errors), AND
- ``current_count`` > ``rolling_average * SPIKE_MULTIPLIER``
Args:
current_count: Error count in the current monitoring window.
rolling_counts: Historical rolling counts from Firestore.
Returns:
``True`` if a spike is detected, ``False`` otherwise.
"""
if not rolling_counts:
return False
if current_count < SPIKE_MIN_COUNT:
return False
avg = _rolling_average(rolling_counts)
if avg == 0.0:
return False
return current_count > avg * SPIKE_MULTIPLIER
# ---------------------------------------------------------------------------
# ErrorMonitor class
# ---------------------------------------------------------------------------
class ErrorMonitor:
"""Orchestrates the full production error monitoring pipeline.
On each run (typically every 15 minutes via Cloud Scheduler), it:
1. Queries Cloud Logging for recent errors across all monitored services.
2. Groups errors into patterns using normalisation + hashing.
3. Upserts patterns to Firestore, tracking new vs. recurrent.
4. Optionally uses an LLM to deduplicate patterns and create incidents.
5. Sends Discord alerts for new patterns, incidents, and spikes.
6. Auto-resolves patterns that have been silent long enough.
"""
def __init__(self) -> None:
self.logging_client = cloud_logging.Client(project=GCP_PROJECT)
self.firestore_adapter = ErrorPatternsAdapter()
self.discord = ErrorMonitorDiscord(webhook_url=self._get_discord_webhook())
def _get_discord_webhook(self) -> str:
"""Retrieve the Discord webhook URL.
Checks ``DISCORD_WEBHOOK_URL`` environment variable first; falls back
to Secret Manager.
Returns:
Discord webhook URL string.
"""
url = os.environ.get("DISCORD_WEBHOOK_URL")
if url:
return url
secret_name = get_discord_webhook_secret_name()
client = secretmanager.SecretManagerServiceClient()
secret_path = f"projects/{GCP_PROJECT}/secrets/{secret_name}/versions/latest"
response = client.access_secret_version(name=secret_path)
return response.payload.data.decode("utf-8").strip()
# ------------------------------------------------------------------
# Main entry point
# ------------------------------------------------------------------
def run(self) -> None:
"""Execute the monitor pipeline (digest or cycle mode)."""
if get_digest_mode():
self._run_daily_digest()
else:
self._run_monitor_cycle()
# ------------------------------------------------------------------
# Monitor cycle
# ------------------------------------------------------------------
def _run_monitor_cycle(self) -> None:
"""Execute one monitor cycle: collect → group → upsert → alert → auto-resolve."""
now = datetime.now(tz=timezone.utc)
now_iso = now.isoformat()
# ── Step 1: Collect log entries ────────────────────────────────────
raw_entries: list[dict] = []
for resource_type, (_, resource_names) in RESOURCE_TYPE_FILTERS.items():
log_filter = _build_log_filter(resource_type, resource_names, LOOKBACK_MINUTES)
logger.info("Querying %s with filter: %s", resource_type, log_filter)
try:
entries = self.logging_client.list_entries(
filter_=log_filter,
max_results=MAX_LOG_ENTRIES,
)
for entry in entries:
message = _extract_message(entry)
if not message:
continue
service = _extract_service_name(entry, resource_type)
ignore_reason = should_ignore(service, message)
if ignore_reason:
logger.debug(
"Ignoring entry from %s (%s): %s",
service,
ignore_reason.pattern_name,
ignore_reason.reason,
)
continue
normalized = normalize_message(message)
if not normalized:
continue
raw_entries.append(
{
"service": service,
"resource_type": _classify_resource_type(resource_type),
"normalized": normalized,
"message": message,
}
)
except Exception as exc: # noqa: BLE001
logger.error("Failed to query %s logs: %s", resource_type, exc)
logger.info("Collected %d log entries after filtering", len(raw_entries))
# ── Step 2: Group by pattern ───────────────────────────────────────
groups = _group_by_pattern(raw_entries)
logger.info("Grouped into %d distinct patterns", len(groups))
if not groups:
logger.info("No new error entries found this cycle; checking auto-resolve.")
self._check_auto_resolve()
return
# ── Step 3: Upsert to Firestore ────────────────────────────────────
new_pattern_ids: list[str] = []
spike_patterns: list[dict] = []
for pattern_id, group in groups.items():
data = PatternData(
pattern_id=pattern_id,
service=group["service"],
resource_type=group["resource_type"],
normalized_message=group["normalized"],
sample_message=group["sample_message"],
count=group["count"],
timestamp=now,
)
result: UpsertResult = self.firestore_adapter.upsert_pattern(data)
if result.is_new:
new_pattern_ids.append(pattern_id)
logger.info("New pattern detected: %s (%s)", pattern_id, group["service"])
# Check for spike on existing patterns
existing = self.firestore_adapter.get_pattern(pattern_id)
if existing and not result.is_new:
rolling = existing.get("rolling_counts") or []
if _is_spike(group["count"], rolling):
spike_patterns.append(
{
"service": group["service"],
"normalized_message": group["normalized"],
"current_count": group["count"],
"rolling_average": _rolling_average(rolling),
}
)
logger.info("Spike detected for pattern %s", pattern_id)
# ── Step 4: LLM dedup ─────────────────────────────────────────────
if new_pattern_ids and get_llm_enabled():
new_patterns_data = [
{
"service": groups[pid]["service"],
"normalized_message": groups[pid]["normalized"],
"count": groups[pid]["count"],
}
for pid in new_pattern_ids
]
existing_patterns = self.firestore_adapter.get_active_patterns()
# Exclude newly added patterns from the canonical list
canonical = [p for p in existing_patterns if p.get("pattern_id") not in new_pattern_ids]
if canonical:
duplicate_groups = find_duplicate_patterns(new_patterns_data, canonical)
for dup_group in duplicate_groups:
# Merge each duplicate new pattern into the canonical
canonical_pattern = canonical[dup_group.canonical_index]
canonical_id = canonical_pattern.get("pattern_id", "")
for dup_idx in dup_group.duplicate_indices:
if dup_idx < len(new_pattern_ids):
dup_id = new_pattern_ids[dup_idx]
logger.info(
"Merging duplicate pattern %s into %s: %s",
dup_id,
canonical_id,
dup_group.reason,
)
self.firestore_adapter.merge_pattern(dup_id, canonical_id, dup_group.reason)
# Remove from new_pattern_ids since it was merged
new_pattern_ids = [pid for pid in new_pattern_ids if pid != dup_id]
# ── Step 5: LLM incident analysis ─────────────────────────────────
incident_pattern_ids: set[str] = set()
if len(new_pattern_ids) >= 2 and get_llm_enabled():
patterns_for_analysis = [
{
"service": groups[pid]["service"],
"normalized_message": groups[pid]["normalized"],
"count": groups[pid]["count"],
}
for pid in new_pattern_ids
if pid in groups
]
analysis = analyze_patterns(patterns_for_analysis)
if analysis and analysis.incidents:
for incident in analysis.incidents:
incident_pids = [
new_pattern_ids[idx]
for idx in incident.pattern_indices
if idx < len(new_pattern_ids)
]
if not incident_pids:
continue
incident_id = self.firestore_adapter.create_incident(
title=incident.title,
root_cause=incident.root_cause or "",
severity=incident.severity,
suggested_fix=incident.suggested_fix or "",
primary_service=incident.primary_service,
pattern_ids=incident_pids,
used_llm=analysis.used_llm,
)
logger.info(
"Created incident %s (%s) with %d patterns",
incident_id,
incident.severity,
len(incident_pids),
)
# Build pattern list for the Discord alert
pattern_dicts = [
{
"service": groups[pid]["service"],
"normalized_message": groups[pid]["normalized"],
"count": groups[pid]["count"],
}
for pid in incident_pids
if pid in groups
]
msg = format_incident_alert(
title=incident.title,
severity=incident.severity,
root_cause=incident.root_cause or "Unknown",
suggested_fix=incident.suggested_fix or "Investigate logs",
primary_service=incident.primary_service,
patterns=pattern_dicts,
)
if self.discord.send_message(msg):
for pid in incident_pids:
try:
self.firestore_adapter.update_pattern_alerted(pid)
except Exception as exc: # noqa: BLE001
logger.warning("Could not update alerted_at for %s: %s", pid, exc)
incident_pattern_ids.update(incident_pids)
# ── Step 6: Individual alerts for new patterns not in incidents ────
for pattern_id in new_pattern_ids:
if pattern_id in incident_pattern_ids:
continue
if pattern_id not in groups:
continue
group = groups[pattern_id]
# Fetch fresh copy to get first_seen timestamp
existing = self.firestore_adapter.get_pattern(pattern_id)
first_seen = existing.get("first_seen", now_iso) if existing else now_iso
msg = format_new_pattern_alert(
service=group["service"],
resource_type=group["resource_type"],
normalized_message=group["normalized"],
sample_message=group["sample_message"],
count=group["count"],
first_seen=first_seen,
)
if self.discord.send_message(msg):
try:
self.firestore_adapter.update_pattern_alerted(pattern_id)
except Exception as exc: # noqa: BLE001
logger.warning("Could not update alerted_at for %s: %s", pattern_id, exc)
# ── Step 7: Spike alerts ───────────────────────────────────────────
for spike in spike_patterns:
msg = format_spike_alert(
service=spike["service"],
normalized_message=spike["normalized_message"],
current_count=spike["current_count"],
rolling_average=spike["rolling_average"],
)
self.discord.send_message(msg)
# ── Step 8: Auto-resolve check ─────────────────────────────────────
self._check_auto_resolve()
# ------------------------------------------------------------------
# Auto-resolve helper
# ------------------------------------------------------------------
def _check_auto_resolve(self) -> None:
"""Check all active patterns for auto-resolution and send a consolidated alert."""
patterns = self.firestore_adapter.get_patterns_for_auto_resolve()
resolved: list[dict] = []
for pattern in patterns:
pattern_id = pattern.get("pattern_id", "")
hours_silent = self.firestore_adapter.check_auto_resolve(pattern)
if hours_silent is not None:
logger.info(
"Auto-resolving pattern %s (silent %.1f hours)", pattern_id, hours_silent
)
self.firestore_adapter.auto_resolve_pattern(pattern_id, round(hours_silent, 1))
resolved.append(
{
"service": pattern.get("service", "unknown"),
"message": pattern.get("normalized_message", ""),
"hours_silent": round(hours_silent, 1),
}
)
if resolved:
msg = format_auto_resolved_alert(resolved)
self.discord.send_message(msg)
# ------------------------------------------------------------------
# Daily digest
# ------------------------------------------------------------------
def _run_daily_digest(self) -> None:
"""Gather 24h stats and send a daily digest to Discord."""
# Optional dedup sweep (best-effort; LLM errors are non-fatal)
if get_llm_enabled():
try:
active = self.firestore_adapter.get_active_patterns()
if len(active) >= 2:
mid = len(active) // 2
duplicates = find_duplicate_patterns(active[:mid], active[mid:])
for dup in duplicates:
for idx in dup.duplicate_indices:
target_half = active[mid:]
source_half = active[:mid]
if idx < len(target_half) and dup.canonical_index < len(source_half):
self.firestore_adapter.merge_pattern(
target_half[idx]["pattern_id"],
source_half[dup.canonical_index]["pattern_id"],
dup.reason,
)
except Exception as exc: # noqa: BLE001
logger.warning("Digest dedup sweep failed (non-fatal): %s", exc)
# Gather stats from active patterns
active_patterns = self.firestore_adapter.get_active_patterns()
per_service_counts: dict[str, int] = {}
new_count = 0
total_errors = 0
for pattern in active_patterns:
service = pattern.get("service", "unknown")
count = pattern.get("total_count", 0)
per_service_counts[service] = per_service_counts.get(service, 0) + count
total_errors += count
if pattern.get("status") == "new":
new_count += 1
# Count recently auto-resolved patterns
resolved_patterns = self.firestore_adapter.get_patterns_for_auto_resolve()
resolved_count = sum(
1
for p in resolved_patterns
if self.firestore_adapter.check_auto_resolve(p) is not None
)
msg = format_daily_digest(
total_errors=total_errors,
new_patterns=new_count,
resolved_patterns=resolved_count,
active_patterns=len(active_patterns),
per_service_counts=per_service_counts,
)
self.discord.send_message(msg)
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
def main() -> None:
"""Configure logging and run the error monitor."""
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
monitor = ErrorMonitor()
monitor.run()
if __name__ == "__main__":
main()
@@ -0,0 +1,137 @@
"""Message normalizer for the production error monitoring service.
Replaces variable parts of error messages (IDs, timestamps, paths, etc.)
with stable placeholders so the same logical error always produces the same
pattern hash, regardless of which specific resource or timestamp was involved.
Normalizer rules are applied in order — more specific patterns first.
"""
import hashlib
import re
from backend.services.error_monitor.config import MAX_NORMALIZED_MESSAGE_LENGTH
# ---------------------------------------------------------------------------
# Compiled regex patterns (applied in order — more specific first)
# ---------------------------------------------------------------------------
_NORMALIZERS: list[tuple[re.Pattern, str]] = [
# 1. GCS paths: gs://bucket/path/to/object → gs://<BUCKET>/<PATH>
# Must come before Firestore and URL normalization.
(
re.compile(r"gs://([^/\s]+)/([^\s]+)"),
r"gs://<BUCKET>/<PATH>",
),
# 1b. GCS bucket root (no object path): gs://bucket/ or gs://bucket
# Uses a lookahead so the slash/end-of-string is not consumed, and uses
# a character class that excludes '<' to avoid re-matching placeholders.
(
re.compile(r"gs://([^/<\s]+)(?=[/\s]|$)"),
r"gs://<BUCKET>",
),
# 2. Firestore document paths (collection/doc/…/doc — at least 2 segments)
# Negative lookbehind for '.' prevents matching inside domain names (URLs).
# Negative lookbehind for '/' prevents matching inside already-replaced paths.
(
re.compile(
r"(?<![./])\b([a-zA-Z_][a-zA-Z0-9_-]*/[a-zA-Z0-9_-]+(?:/[a-zA-Z0-9_-]+){1,})\b"
),
r"<DOC_PATH>",
),
# 3. UUIDs (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
(
re.compile(
r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b"
),
"<ID>",
),
# 4. ISO 8601 timestamps (2024-01-15T10:30:45Z / …+05:30 / ….123Z)
(
re.compile(
r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})"
),
"<TS>",
),
# 5. Epoch timestamps: 10+ digit number optionally followed by fractional seconds
(
re.compile(r"\b\d{10,}(?:\.\d+)?\b"),
"<EPOCH>",
),
# 6. Email addresses
(
re.compile(r"\b[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}\b"),
"<EMAIL>",
),
# 7. IP addresses (IPv4) — must come before large-number replacement
(
re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b"),
"<IP>",
),
# 8. URLs — strip to domain only (https://host/path → https://host)
# Handles http and https; preserves the scheme+domain for context.
(
re.compile(r"https?://([A-Za-z0-9.\-]+(:\d+)?)/[^\s]*"),
r"https://\1",
),
# 9. Job IDs in paths (/jobs/<alphanumeric>)
(
re.compile(r"/jobs/[A-Za-z0-9]+"),
"/jobs/<ID>",
),
# 10. Firebase UIDs (20–28 mixed-case alphanumeric characters)
# Firebase Auth UIDs are typically 28 chars; allow 20-28 for flexibility.
# Must contain both letters and digits (to avoid replacing plain words).
(
re.compile(r"\b(?=[A-Za-z0-9]{20,28}\b)(?=[A-Za-z0-9]*[A-Z])(?=[A-Za-z0-9]*[a-z])(?=[A-Za-z0-9]*\d)[A-Za-z0-9]{20,28}\b"),
"<UID>",
),
# 11. Hex/alphanumeric IDs: 8+ chars containing both letters and digits
# (e.g. git SHAs, Cloud Run revision IDs, job IDs)
# Uses a lookahead to require at least one digit AND one letter.
(
re.compile(r"\b(?=[a-fA-F0-9]*[a-fA-F][a-fA-F0-9]*\d|[a-fA-F0-9]*\d[a-fA-F0-9]*[a-fA-F])[a-fA-F0-9]{8,}\b"),
"<ID>",
),
# 12. Large numbers (4+ digits) — must come after epoch/IP/UUID replacements
(
re.compile(r"\b\d{4,}\b"),
"<NUM>",
),
]
def normalize_message(message: str) -> str:
"""Normalize a raw log message by replacing variable parts with placeholders.
Applies each normalizer rule in order (more specific patterns first) and
truncates the result to MAX_NORMALIZED_MESSAGE_LENGTH characters.
Args:
message: Raw log message string.
Returns:
Normalized message string, at most MAX_NORMALIZED_MESSAGE_LENGTH chars.
"""
if not message:
return ""
result = message
for pattern, replacement in _NORMALIZERS:
result = pattern.sub(replacement, result)
return result[:MAX_NORMALIZED_MESSAGE_LENGTH]
def compute_pattern_hash(service: str, normalized_message: str) -> str:
"""Compute a stable SHA-256 fingerprint for an error pattern.
Args:
service: The originating service name (e.g. "karaoke-backend").
normalized_message: The output of normalize_message().
Returns:
64-character lowercase hex SHA-256 digest.
"""
payload = f"{service}:{normalized_message}"
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
+141
View File
@@ -0,0 +1,141 @@
"""Service for generating personalized referral flyer PDFs."""
import logging
import os
import shutil
import subprocess
import tempfile
logger = logging.getLogger(__name__)
TEMPLATE_DIR = os.path.join(os.path.dirname(__file__), "..", "templates", "printables")
CHROMIUM_PATHS = [
"/usr/bin/chromium",
"/usr/bin/chromium-browser",
"/usr/bin/google-chrome",
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
]
VALID_THEMES = {"light", "dark"}
MAX_QR_DATA_URL_BYTES = 500_000
class FlyerError(Exception):
"""Error during flyer generation."""
class FlyerService:
"""Generates personalized referral flyer PDFs."""
def __init__(self):
self._chromium_path: str | None = None
def _get_chromium(self) -> str:
"""Lazily find Chromium binary. Only needed when generating PDFs."""
if self._chromium_path:
return self._chromium_path
for path in CHROMIUM_PATHS:
if os.path.exists(path):
self._chromium_path = path
return path
for name in ["chromium", "chromium-browser", "google-chrome"]:
found = shutil.which(name)
if found:
self._chromium_path = found
return found
raise FlyerError("Chromium not found. Install chromium to generate flyer PDFs.")
def _validate_qr_data_url(self, qr_data_url: str) -> None:
if not qr_data_url.startswith("data:image/"):
raise FlyerError("Invalid QR data URL: must be a data:image/ URL")
if len(qr_data_url) > MAX_QR_DATA_URL_BYTES:
raise FlyerError(f"QR data URL too large (>{MAX_QR_DATA_URL_BYTES} bytes)")
def _render_template(
self,
theme: str,
referral_code: str,
discount_percent: int,
qr_data_url: str,
) -> str:
if theme not in VALID_THEMES:
raise FlyerError(f"Invalid theme: {theme}. Must be one of: {VALID_THEMES}")
suffix = "-dark" if theme == "dark" else ""
template_path = os.path.join(TEMPLATE_DIR, f"website-referral-flyer{suffix}.html")
with open(template_path) as f:
html = f.read()
html = html.replace("{{REFERRAL_CODE}}", referral_code.upper())
html = html.replace("{{REFERRAL_CODE_LOWER}}", referral_code.lower())
html = html.replace("{{DISCOUNT_PERCENT}}", str(discount_percent))
html = html.replace("{{QR_DATA_URL}}", qr_data_url)
return html
def generate_pdf(
self,
theme: str,
referral_code: str,
discount_percent: int,
qr_data_url: str,
) -> bytes:
"""Generate a personalized flyer PDF. Returns raw PDF bytes."""
self._validate_qr_data_url(qr_data_url)
html = self._render_template(theme, referral_code, discount_percent, qr_data_url)
with tempfile.NamedTemporaryFile(
suffix=".html", delete=False, mode="w", encoding="utf-8"
) as tmp_html:
tmp_html.write(html)
tmp_html_path = tmp_html.name
tmp_pdf_path = tmp_html_path.replace(".html", ".pdf")
try:
cmd = [
self._get_chromium(),
"--headless",
f"--print-to-pdf={tmp_pdf_path}",
"--no-margins",
"--print-background",
"--no-pdf-header-footer",
"--virtual-time-budget=5000",
"--paper-width=8.5",
"--paper-height=11",
"--disable-gpu",
"--no-sandbox",
tmp_html_path,
]
result = subprocess.run(
cmd, capture_output=True, text=True, timeout=30
)
if result.returncode != 0:
logger.error("Chromium PDF generation failed: %s", result.stderr)
raise FlyerError(f"PDF generation failed: {result.stderr[:200]}")
if not os.path.exists(tmp_pdf_path):
raise FlyerError("PDF generation failed: no output file created")
with open(tmp_pdf_path, "rb") as f:
return f.read()
finally:
for path in [tmp_html_path, tmp_pdf_path]:
try:
os.unlink(path)
except OSError:
pass
_flyer_service = None
def get_flyer_service() -> FlyerService:
global _flyer_service
if _flyer_service is None:
_flyer_service = FlyerService()
return _flyer_service
+381 -1
View File
@@ -1,9 +1,11 @@
import asyncio
import glob as glob_module
import hashlib
import json
import logging
import os
import re
import shutil
import subprocess
import sys
import tempfile
@@ -59,12 +61,27 @@ class EncodePreviewRequest(BaseModel):
font_gcs_path: Optional[str] = None # gs://bucket/path/to/custom-font.ttf
class RenderVideoRequest(BaseModel):
job_id: str
original_corrections_gcs_path: str
updated_corrections_gcs_path: Optional[str] = None
audio_gcs_path: str
style_params_gcs_path: Optional[str] = None
style_assets: Optional[dict] = None
output_gcs_prefix: str
artist: str
title: str
subtitle_offset_ms: int = 0
video_resolution: str = "4k"
class JobStatus(BaseModel):
job_id: str
status: str # pending, running, complete, failed
progress: int # 0-100
error: Optional[str] = None
output_files: Optional[list[str]] = None
metadata: Optional[dict] = None
def download_from_gcs(gcs_uri: str, local_path: Path):
@@ -136,6 +153,59 @@ def upload_single_file_to_gcs(local_path: Path, gcs_uri: str):
logger.info(f"Uploaded: {local_path} -> {gcs_uri}")
# Style asset disk cache directory
# Persists across jobs to avoid re-downloading the same theme assets (fonts, backgrounds)
STYLE_CACHE_DIR = Path("/var/cache/karaoke-gen/styles")
def download_with_cache(gcs_uri: str, local_path: Path, cache_dir: Optional[Path] = STYLE_CACHE_DIR):
"""Download a file from GCS, using a local disk cache to skip repeated downloads.
Cache key is SHA-256 of the GCS URI. Cache hits are validated by comparing
the cached file size against the GCS object size (via a lightweight metadata
call). On size mismatch the stale entry is replaced.
When cache_dir is None, downloads directly (no caching).
"""
if cache_dir is None:
download_single_file_from_gcs(gcs_uri, local_path)
return
cache_dir.mkdir(parents=True, exist_ok=True)
cache_key = hashlib.sha256(gcs_uri.encode()).hexdigest()
cached_path = cache_dir / cache_key
if cached_path.exists():
# Validate cached file against GCS object size
try:
parts = gcs_uri.replace("gs://", "").split("/", 1)
bucket_name = parts[0]
blob_name = parts[1] if len(parts) > 1 else ""
blob = storage_client.bucket(bucket_name).blob(blob_name)
blob.reload() # Fetch metadata (lightweight HEAD request)
gcs_size = blob.size
cached_size = cached_path.stat().st_size
if gcs_size is not None and cached_size != gcs_size:
logger.warning(
f"Cache stale for {gcs_uri}: cached={cached_size}B, GCS={gcs_size}B. Re-downloading."
)
cached_path.unlink()
else:
logger.info(f"Cache hit for {gcs_uri} -> {cached_path}")
shutil.copy2(str(cached_path), str(local_path))
return
except Exception as e:
# On transient GCS errors, serve from cache rather than failing the job
logger.warning(f"Cache validation failed for {gcs_uri}: {e}. Serving from cache.")
shutil.copy2(str(cached_path), str(local_path))
return
logger.info(f"Cache miss for {gcs_uri}, downloading...")
download_single_file_from_gcs(gcs_uri, local_path)
# Store in cache
shutil.copy2(str(local_path), str(cached_path))
def run_preview_encoding(job_id: str, work_dir: Path, request: "EncodePreviewRequest"):
# Run FFmpeg encoding for preview video (480x270, fast settings)
jobs[job_id]["status"] = "running"
@@ -239,6 +309,192 @@ def run_preview_encoding(job_id: str, work_dir: Path, request: "EncodePreviewReq
raise
def run_render_video(job_id: str, work_dir: Path, request: "RenderVideoRequest"):
"""Run video rendering using OutputGenerator from the karaoke-gen wheel.
Downloads corrections, audio, and style assets from GCS, runs OutputGenerator
to produce with_vocals.mkv and subtitle files, then uploads results.
Style assets use disk cache to avoid repeated downloads of the same theme.
This mirrors the logic in render_video_worker.py but runs on the GCE VM
instead of Cloud Run, providing more memory and CPU for ffmpeg/libass.
"""
jobs[job_id]["status"] = "running"
jobs[job_id]["progress"] = 5
try:
# Import from installed karaoke-gen wheel
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
from karaoke_gen.style_loader import load_styles_from_gcs
from karaoke_gen.utils import sanitize_filename
# 1. Download original corrections
corrections_path = work_dir / "corrections.json"
download_single_file_from_gcs(request.original_corrections_gcs_path, corrections_path)
jobs[job_id]["progress"] = 15
with open(corrections_path, 'r', encoding='utf-8') as f:
original_data = json.load(f)
base_result = CorrectionResult.from_dict(original_data)
# 2. Apply user corrections if available
if request.updated_corrections_gcs_path:
updated_path = work_dir / "corrections_updated.json"
download_single_file_from_gcs(request.updated_corrections_gcs_path, updated_path)
with open(updated_path, 'r', encoding='utf-8') as f:
updated_data = json.load(f)
if isinstance(updated_data, dict) and "corrections" in updated_data:
correction_result = CorrectionOperations.update_correction_result_with_data(
base_result, updated_data
)
logger.info(f"[job:{job_id}] Applied user corrections")
else:
logger.warning(f"[job:{job_id}] corrections_updated.json exists but has no 'corrections' key, using base result")
correction_result = base_result
else:
correction_result = base_result
jobs[job_id]["progress"] = 25
# 3. Download audio
audio_path = work_dir / "audio.flac"
download_single_file_from_gcs(request.audio_gcs_path, audio_path)
jobs[job_id]["progress"] = 35
# 4. Process countdown intro
countdown_processor = CountdownProcessor(cache_dir=str(work_dir), logger=logger)
correction_result, audio_path_str, padding_added, padding_seconds = countdown_processor.process(
correction_result=correction_result,
audio_filepath=str(audio_path),
)
audio_path = Path(audio_path_str)
jobs[job_id]["progress"] = 40
# 5. Download style assets (with disk cache for repeated themes)
def cached_download(gcs_path, local_path):
download_with_cache(gcs_path, Path(local_path), STYLE_CACHE_DIR)
styles_path, style_data = load_styles_from_gcs(
style_params_gcs_path=request.style_params_gcs_path,
style_assets=request.style_assets,
temp_dir=str(work_dir),
download_func=cached_download,
logger=logger,
)
# Register any downloaded fonts with fontconfig
for asset_key, gcs_path in (request.style_assets or {}).items():
if 'font' in asset_key.lower() and gcs_path.endswith(('.ttf', '.otf', '.woff', '.woff2')):
fonts_dir = Path("/usr/local/share/fonts/custom")
fonts_dir.mkdir(parents=True, exist_ok=True)
font_filename = gcs_path.split("/")[-1]
font_dest = fonts_dir / font_filename
if not font_dest.exists():
ext = os.path.splitext(gcs_path)[1]
style_font = work_dir / "style" / f"{asset_key}{ext}"
if style_font.exists():
shutil.copy2(str(style_font), str(font_dest))
subprocess.run(["fc-cache", "-fv"], capture_output=True)
logger.info(f"Registered font: {font_filename}")
jobs[job_id]["progress"] = 50
# 6. Configure and run OutputGenerator
output_dir = work_dir / "output"
cache_dir = work_dir / "cache"
output_dir.mkdir(exist_ok=True)
cache_dir.mkdir(exist_ok=True)
config = OutputConfig(
output_dir=str(output_dir),
cache_dir=str(cache_dir),
output_styles_json=styles_path,
render_video=True,
generate_cdg=False,
generate_plain_text=True,
generate_lrc=True,
video_resolution=request.video_resolution,
subtitle_offset_ms=request.subtitle_offset_ms,
)
output_generator = OutputGenerator(config, logger)
safe_artist = sanitize_filename(request.artist) if request.artist else "Unknown"
safe_title = sanitize_filename(request.title) if request.title else "Unknown"
output_prefix = f"{safe_artist} - {safe_title}"
logger.info(f"[job:{job_id}] Generating outputs with prefix '{output_prefix}'")
jobs[job_id]["progress"] = 55
outputs = output_generator.generate_outputs(
transcription_corrected=correction_result,
lyrics_results={},
output_prefix=output_prefix,
audio_filepath=str(audio_path),
artist=request.artist,
title=request.title,
)
jobs[job_id]["progress"] = 85
# 7. Upload outputs to GCS
output_prefix_gcs = request.output_gcs_prefix.rstrip("/")
output_files = []
if outputs.video and os.path.exists(outputs.video):
gcs_path = f"{output_prefix_gcs}/videos/with_vocals.mkv"
upload_single_file_to_gcs(Path(outputs.video), gcs_path)
output_files.append(gcs_path)
logger.info(f"[job:{job_id}] Uploaded with_vocals.mkv ({os.path.getsize(outputs.video)} bytes)")
else:
raise RuntimeError("Video generation failed - no output file produced")
if outputs.ass and os.path.exists(outputs.ass):
gcs_path = f"{output_prefix_gcs}/lyrics/karaoke.ass"
upload_single_file_to_gcs(Path(outputs.ass), gcs_path)
output_files.append(gcs_path)
if outputs.lrc and os.path.exists(outputs.lrc):
gcs_path = f"{output_prefix_gcs}/lyrics/karaoke.lrc"
upload_single_file_to_gcs(Path(outputs.lrc), gcs_path)
output_files.append(gcs_path)
if outputs.corrected_txt and os.path.exists(outputs.corrected_txt):
gcs_path = f"{output_prefix_gcs}/lyrics/corrected.txt"
upload_single_file_to_gcs(Path(outputs.corrected_txt), gcs_path)
output_files.append(gcs_path)
jobs[job_id]["progress"] = 95
jobs[job_id]["output_files"] = output_files
jobs[job_id]["metadata"] = {
"countdown_padding_added": padding_added,
"countdown_padding_seconds": padding_seconds if padding_added else 0,
}
logger.info(f"[job:{job_id}] Render video complete. Output files: {output_files}")
except ImportError as e:
error_msg = (
f"OutputGenerator not available: {e}. "
"The karaoke-gen wheel must be installed. "
"Check that ensure_latest_wheel() succeeded."
)
logger.error(error_msg)
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = error_msg
raise RuntimeError(error_msg) from e
except Exception as e:
logger.error(f"[job:{job_id}] Render video failed: {e}")
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = str(e)
raise
def ensure_latest_wheel():
'''Download and install latest karaoke-gen wheel from GCS.
@@ -307,6 +563,43 @@ def find_file(work_dir: Path, *patterns):
return None
def generate_mov_from_png(png_path: Path, mov_path: Path, duration: int = 5) -> Path:
"""Generate a MOV video from a static PNG image using FFmpeg.
This runs on the GCE encoding worker (not Cloud Run) because 4K H.264
encoding requires more memory than the right-sized Cloud Run container
provides (2Gi). See PR #640 / #647.
Args:
png_path: Path to input PNG image
mov_path: Path for output MOV video
duration: Video duration in seconds (default 5)
Returns:
Path to generated MOV file
Raises:
RuntimeError: If FFmpeg fails
"""
command = [
"ffmpeg", "-hide_banner", "-loglevel", "error", "-nostats", "-y",
"-loop", "1", "-framerate", "30", "-i", str(png_path),
"-f", "lavfi", "-i", "anullsrc",
"-c:v", "libx264", "-r", "30", "-t", str(duration),
"-pix_fmt", "yuv420p", "-vf", "scale=3840:2160",
"-c:a", "aac", "-shortest",
str(mov_path),
]
logger.info(f"Generating MOV from PNG: {png_path.name} -> {mov_path.name}")
result = subprocess.run(command, capture_output=True, text=True, timeout=120)
if result.returncode != 0:
raise RuntimeError(f"FFmpeg failed to generate {mov_path.name}: {result.stderr}")
if not mov_path.exists() or mov_path.stat().st_size < 1024:
raise RuntimeError(f"FFmpeg produced invalid output for {mov_path.name}")
logger.info(f"Generated MOV: {mov_path.name} ({mov_path.stat().st_size} bytes)")
return mov_path
def run_encoding(job_id: str, work_dir: Path, config: dict):
'''Run encoding using LocalEncodingService (single source of truth).
@@ -336,10 +629,36 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
logger.info(f"Encoding for: {base_name}")
# Find input files in work_dir
# Title/end screens are in screens/ subdirectory
# Title/end screens: look for MOV first, fall back to generating from PNG.
# Since PR #640 right-sized Cloud Run to 2Gi, the screens_worker only generates
# PNG/JPG images — MOV video generation now happens here on the GCE worker.
title_video = find_file(work_dir, "screens/title.mov", "*Title*.mov", "*title*.mov")
end_video = find_file(work_dir, "screens/end.mov", "*End*.mov", "*end*.mov")
# Get intro/end video durations from style config (default 5s)
intro_duration = config.get("intro_video_duration", 5)
end_duration = config.get("end_video_duration", 5)
# Generate title MOV from PNG if missing or invalid (< 1KB = empty shell)
if not title_video or title_video.stat().st_size < 1024:
title_png = find_file(work_dir, "screens/title.png", "*Title*.png", "*title*.png")
if title_png:
title_mov_path = title_png.parent / "title.mov"
logger.info(f"Title MOV missing/invalid, generating from PNG: {title_png}")
title_video = generate_mov_from_png(title_png, title_mov_path, duration=intro_duration)
elif title_video:
logger.warning(f"Title MOV is only {title_video.stat().st_size} bytes and no PNG found")
# Generate end MOV from PNG if missing or invalid
if not end_video or (end_video and end_video.stat().st_size < 1024):
end_png = find_file(work_dir, "screens/end.png", "*End*.png", "*end*.png")
if end_png:
end_mov_path = end_png.parent / "end.mov"
logger.info(f"End MOV missing/invalid, generating from PNG: {end_png}")
end_video = generate_mov_from_png(end_png, end_mov_path, duration=end_duration)
elif end_video:
logger.warning(f"End MOV is only {end_video.stat().st_size} bytes and no PNG found")
# Karaoke video - search for With Vocals or main karaoke video
# IMPORTANT: Search order matters! Search specific paths first to avoid picking up
# old encoding outputs from finals/ directory when re-encoding after reset
@@ -584,6 +903,36 @@ async def process_preview_job(job_id: str, request: EncodePreviewRequest):
jobs[job_id]["error"] = str(e)
async def process_render_video_job(job_id: str, request: RenderVideoRequest):
# Process a render-video job asynchronously
try:
# Download and install latest wheel at job start (allows hot updates without restart)
ensure_latest_wheel()
with tempfile.TemporaryDirectory() as temp_dir:
work_dir = Path(temp_dir) / "work"
work_dir.mkdir()
# Run render-video in thread pool (CPU-bound)
loop = asyncio.get_event_loop()
await loop.run_in_executor(
executor,
run_render_video,
job_id,
work_dir,
request
)
jobs[job_id]["status"] = "complete"
jobs[job_id]["progress"] = 100
logger.info(f"Render video job {job_id} complete")
except Exception as e:
logger.error(f"Render video job {job_id} failed: {e}")
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = str(e)
@app.post("/encode-preview")
async def submit_preview_encode_job(request: EncodePreviewRequest, background_tasks: BackgroundTasks, _auth: bool = Depends(verify_api_key)):
# Submit a preview encoding job
@@ -615,6 +964,37 @@ async def submit_preview_encode_job(request: EncodePreviewRequest, background_ta
return {"status": "accepted", "job_id": job_id}
@app.post("/render-video")
async def submit_render_video_job(request: RenderVideoRequest, background_tasks: BackgroundTasks, _auth: bool = Depends(verify_api_key)):
# Submit a render-video job
job_id = request.job_id
# If job already exists, return cached result or current status
if job_id in jobs:
existing_job = jobs[job_id]
if existing_job["status"] == "complete":
return {"status": "cached", "job_id": job_id, "output_files": existing_job.get("output_files"), "metadata": existing_job.get("metadata")}
elif existing_job["status"] == "failed":
# Previous attempt failed, allow retry by replacing the job
pass
else:
# Job is still in progress
return {"status": "in_progress", "job_id": job_id}
jobs[job_id] = {
"job_id": job_id,
"status": "pending",
"progress": 0,
"error": None,
"output_files": None,
"metadata": None,
}
background_tasks.add_task(process_render_video_job, job_id, request)
return {"status": "accepted", "job_id": job_id}
@app.post("/encode")
async def submit_encode_job(request: EncodeRequest, background_tasks: BackgroundTasks, _auth: bool = Depends(verify_api_key)):
# Submit an encoding job
+4 -2
View File
@@ -213,8 +213,10 @@ def get_worker_valid_statuses() -> Dict[str, List[JobStatus]]:
"video_worker": [
JobStatus.INSTRUMENTAL_SELECTED,
JobStatus.REVIEW_COMPLETE,
JobStatus.RENDERING_VIDEO,
JobStatus.GENERATING_VIDEO,
# Note: RENDERING_VIDEO and GENERATING_VIDEO are intentionally excluded.
# If the job is already in those states, another worker is actively processing it.
# Including them caused a race condition where Cloud Run Job retries + manual retries
# could launch concurrent workers that corrupt each other's state transitions.
],
"render_video_worker": [
JobStatus.REVIEW_COMPLETE,
+39 -9
View File
@@ -12,8 +12,10 @@ import logging
import os
from typing import Optional, Dict, Any
from backend.i18n import get_locale_prefix
from backend.services.email_service import get_email_service
from backend.services.template_service import get_template_service
from backend.services.user_service import get_user_service
logger = logging.getLogger(__name__)
@@ -51,19 +53,30 @@ class JobNotificationService:
self.frontend_url = os.getenv("FRONTEND_URL", "https://gen.nomadkaraoke.com")
self.backend_url = os.getenv("BACKEND_URL", "https://api.nomadkaraoke.com")
def _build_review_url(self, job_id: str, audio_hash: Optional[str] = None, review_token: Optional[str] = None) -> str:
def _get_user_locale(self, user_email: str) -> str:
"""Look up user's locale preference from Firestore, defaulting to 'en'."""
try:
user_service = get_user_service()
user = user_service.get_user(user_email)
if user and user.locale:
return user.locale
except Exception:
pass # Fall back to English
return "en"
def _build_review_url(self, job_id: str, audio_hash: Optional[str] = None, review_token: Optional[str] = None, locale: str = "en") -> str:
"""Build the lyrics review URL for a job."""
# Use hash-based routing for static hosting compatibility
return f"{self.frontend_url}/app/jobs#/{job_id}/review"
return f"{self.frontend_url}{get_locale_prefix(locale)}/app/jobs#/{job_id}/review"
def _build_instrumental_url(self, job_id: str, instrumental_token: Optional[str] = None) -> str:
def _build_instrumental_url(self, job_id: str, instrumental_token: Optional[str] = None, locale: str = "en") -> str:
"""Build the instrumental selection URL for a job."""
# Use hash-based routing for static hosting compatibility
return f"{self.frontend_url}/app/jobs#/{job_id}/instrumental"
return f"{self.frontend_url}{get_locale_prefix(locale)}/app/jobs#/{job_id}/instrumental"
def _build_audio_edit_url(self, job_id: str) -> str:
def _build_audio_edit_url(self, job_id: str, locale: str = "en") -> str:
"""Build the audio edit URL for a job."""
return f"{self.frontend_url}/app/jobs#/{job_id}/audio-edit"
return f"{self.frontend_url}{get_locale_prefix(locale)}/app/jobs#/{job_id}/audio-edit"
async def send_job_completion_email(
self,
@@ -105,6 +118,9 @@ class JobNotificationService:
return False
try:
# Get user locale for email
user_locale = self._get_user_locale(user_email)
# Render the completion message using template service
message_content = self.template_service.render_job_completion(
name=user_name,
@@ -116,6 +132,7 @@ class JobNotificationService:
feedback_url=FEEDBACK_FORM_URL,
is_private=is_private,
youtube_queued=youtube_queued,
locale=user_locale,
)
# Send the email with CC to admin
@@ -126,6 +143,7 @@ class JobNotificationService:
title=title,
brand_code=brand_code,
cc_admin=True,
locale=user_locale,
)
if success:
@@ -171,10 +189,14 @@ class JobNotificationService:
return False
try:
# Get user locale for email
user_locale = self._get_user_locale(user_email)
message_content = self.template_service.render_youtube_upload_complete(
artist=artist,
title=title,
youtube_url=youtube_url,
locale=user_locale,
)
success = self.email_service.send_youtube_upload_complete(
@@ -183,6 +205,7 @@ class JobNotificationService:
artist=artist,
title=title,
brand_code=brand_code,
locale=user_locale,
)
if success:
@@ -237,31 +260,37 @@ class JobNotificationService:
return False
try:
# Get user locale for email
user_locale = self._get_user_locale(user_email)
# Render the appropriate template
if action_type == "lyrics":
review_url = self._build_review_url(job_id, audio_hash, review_token)
review_url = self._build_review_url(job_id, audio_hash, review_token, locale=user_locale)
message_content = self.template_service.render_action_needed_lyrics(
name=user_name,
artist=artist,
title=title,
review_url=review_url,
locale=user_locale,
)
elif action_type == "instrumental":
instrumental_url = self._build_instrumental_url(job_id, instrumental_token)
instrumental_url = self._build_instrumental_url(job_id, instrumental_token, locale=user_locale)
message_content = self.template_service.render_action_needed_instrumental(
name=user_name,
artist=artist,
title=title,
instrumental_url=instrumental_url,
locale=user_locale,
)
elif action_type == "audio_edit":
audio_edit_url = self._build_audio_edit_url(job_id)
audio_edit_url = self._build_audio_edit_url(job_id, locale=user_locale)
# Reuse the lyrics template but with the audio edit URL and different subject
message_content = self.template_service.render_action_needed_lyrics(
name=user_name,
artist=artist,
title=title,
review_url=audio_edit_url,
locale=user_locale,
)
else:
logger.error(f"Unknown action type: {action_type}")
@@ -274,6 +303,7 @@ class JobNotificationService:
action_type=action_type,
artist=artist,
title=title,
locale=user_locale,
)
if success:
@@ -12,6 +12,7 @@ from pywebpush import webpush, WebPushException
from backend.config import get_settings
from backend.models.user import User, PushSubscription
from backend.i18n import t
logger = logging.getLogger(__name__)
@@ -239,15 +240,16 @@ class PushNotificationService:
artist = job.get("artist", "Unknown Artist")
title = job.get("title", "Unknown Title")
tenant_id = job.get("tenant_id") or None
locale = job.get("locale", "en")
if action_type == "lyrics":
notif_title = "Review Lyrics"
notif_body = f'"{title}" by {artist} needs lyrics review'
notif_title = t(locale, "pushNotifications.reviewLyricsTitle")
notif_body = t(locale, "pushNotifications.reviewLyricsBody", title=title, artist=artist)
url = f"/app/jobs#/{job_id}/review"
tag = f"lyrics-{job_id}"
else: # instrumental
notif_title = "Select Instrumental"
notif_body = f'"{title}" by {artist} needs instrumental selection'
notif_title = t(locale, "pushNotifications.selectInstrumentalTitle")
notif_body = t(locale, "pushNotifications.selectInstrumentalBody", title=title, artist=artist)
url = f"/app/jobs#/{job_id}/instrumental"
tag = f"instrumental-{job_id}"
@@ -278,11 +280,12 @@ class PushNotificationService:
artist = job.get("artist", "Unknown Artist")
title = job.get("title", "Unknown Title")
tenant_id = job.get("tenant_id") or None
locale = job.get("locale", "en")
return await self.send_push(
user_email=user_email,
title="Video Ready!",
body=f'Your karaoke video for "{title}" by {artist} is ready to download',
title=t(locale, "pushNotifications.videoReadyTitle"),
body=t(locale, "pushNotifications.videoReadyBody", title=title, artist=artist),
url=f"/app/?job={job_id}",
tag=f"complete-{job_id}",
tenant_id=tenant_id,
+526
View File
@@ -0,0 +1,526 @@
"""
Referral service for link management, earnings tracking, and payouts.
Handles:
- Referral link creation (generated and vanity codes)
- Link lookup and validation
- Click tracking
- Admin listing
"""
import logging
import re
import secrets
import string
from datetime import datetime, timedelta
from typing import List, Optional, Tuple
from google.cloud import firestore
from backend.models.referral import (
ReferralLink,
ReferralLinkStats,
ReferralEarning,
ReferralPayout,
)
logger = logging.getLogger(__name__)
# ============================================================================
# Constants
# ============================================================================
REFERRAL_LINKS_COLLECTION = "referral_links"
REFERRAL_EARNINGS_COLLECTION = "referral_earnings"
REFERRAL_PAYOUTS_COLLECTION = "referral_payouts"
RESERVED_CODES = frozenset({
"admin", "app", "api", "r", "pricing", "order", "payment",
"login", "auth", "webhook", "webhooks", "internal", "health",
"static", "assets", "public", "private",
})
PAYOUT_THRESHOLD_CENTS = 2000
VANITY_CODE_PATTERN = re.compile(r"^[a-z0-9][a-z0-9\-]{1,28}[a-z0-9]$")
# Characters for generated codes
_CODE_ALPHABET = string.ascii_lowercase + string.digits
# ============================================================================
# Service
# ============================================================================
class ReferralService:
"""Service for referral link management and earnings."""
def __init__(self, db=None, stripe_service=None):
if db is None:
db = firestore.Client()
self.db = db
self.stripe_service = stripe_service
# ========================================================================
# Code Generation & Validation
# ========================================================================
def _generate_code(self) -> str:
"""Generate an 8-character lowercase alphanumeric referral code."""
return "".join(secrets.choice(_CODE_ALPHABET) for _ in range(8))
def _validate_vanity_code(self, code: str) -> Tuple[bool, str]:
"""Validate a vanity code against reserved words and pattern rules.
Returns (is_valid, message).
"""
if code.lower() in RESERVED_CODES:
return False, f"'{code}' is a reserved code"
if not VANITY_CODE_PATTERN.match(code.lower()):
return False, (
"Code must be 3-30 characters, start/end with alphanumeric, "
"and contain only lowercase letters, digits, and hyphens"
)
return True, "Valid"
# ========================================================================
# Link CRUD
# ========================================================================
def get_link_by_code(self, code: str) -> Optional[ReferralLink]:
"""Get a referral link by its code. Returns None if not found or disabled."""
doc = self.db.collection(REFERRAL_LINKS_COLLECTION).document(code).get()
if not doc.exists:
return None
data = doc.to_dict()
if not data.get("enabled", True):
return None
return ReferralLink(**data)
def get_or_create_link(self, owner_email: str) -> ReferralLink:
"""Get existing referral link for owner, or create a new one.
Retries up to 10 times if generated code collides with existing doc.
"""
# Check for existing link
existing = (
self.db.collection(REFERRAL_LINKS_COLLECTION)
.where("owner_email", "==", owner_email)
.limit(1)
.stream()
)
for doc in existing:
return ReferralLink(**doc.to_dict())
# Create new link with retry for code collision
for attempt in range(10):
code = self._generate_code()
doc_ref = self.db.collection(REFERRAL_LINKS_COLLECTION).document(code)
doc_snapshot = doc_ref.get()
if doc_snapshot.exists:
logger.warning("Code collision on attempt %d: %s", attempt + 1, code)
continue
now = datetime.utcnow()
link = ReferralLink(
code=code,
owner_email=owner_email,
created_at=now,
updated_at=now,
)
doc_ref.set(link.model_dump())
return link
raise RuntimeError("Failed to generate unique referral code after 10 attempts")
def create_vanity_link(
self,
code: str,
owner_email: str,
display_name: Optional[str] = None,
custom_message: Optional[str] = None,
discount_percent: int = 10,
kickback_percent: int = 20,
discount_duration_days: int = 30,
earning_duration_days: int = 365,
) -> Tuple[bool, Optional[ReferralLink], str]:
"""Create a vanity referral link.
Returns (success, link_or_none, message).
"""
valid, msg = self._validate_vanity_code(code)
if not valid:
return False, None, msg
normalized = code.lower()
doc_ref = self.db.collection(REFERRAL_LINKS_COLLECTION).document(normalized)
doc_snapshot = doc_ref.get()
if doc_snapshot.exists:
return False, None, f"Code '{normalized}' is already taken"
now = datetime.utcnow()
link = ReferralLink(
code=normalized,
owner_email=owner_email,
display_name=display_name,
custom_message=custom_message,
discount_percent=discount_percent,
kickback_percent=kickback_percent,
discount_duration_days=discount_duration_days,
earning_duration_days=earning_duration_days,
is_vanity=True,
created_at=now,
updated_at=now,
)
doc_ref.set(link.model_dump())
return True, link, "Vanity link created"
def update_link(self, code: str, **updates) -> Tuple[bool, str]:
"""Update fields on an existing referral link.
Returns (success, message).
"""
doc_ref = self.db.collection(REFERRAL_LINKS_COLLECTION).document(code)
doc_snapshot = doc_ref.get()
if not doc_snapshot.exists:
return False, f"Link '{code}' not found"
updates["updated_at"] = datetime.utcnow()
doc_ref.update(updates)
return True, "Link updated"
def increment_clicks(self, code: str) -> None:
"""Increment the click counter for a referral link."""
doc_ref = self.db.collection(REFERRAL_LINKS_COLLECTION).document(code)
doc_ref.update({"stats.clicks": firestore.Increment(1)})
# ========================================================================
# Attribution
# ========================================================================
def attribute_referral(self, referred_email: str, referral_code: str) -> Tuple[bool, str]:
"""Attribute a referral to a user. Called during first login/signup."""
referred_email = referred_email.lower()
referral_code = referral_code.lower()
link = self.get_link_by_code(referral_code)
if not link:
return False, "Invalid or disabled referral code"
if link.owner_email == referred_email:
return False, "Cannot use your own referral code"
# Increment signup count
self.db.collection(REFERRAL_LINKS_COLLECTION).document(referral_code).update({
"stats.signups": firestore.Increment(1),
})
return True, "Referral attributed"
def get_attribution_data(self, referral_code: str) -> Optional[dict]:
"""Get the data to set on user doc for referral attribution."""
link = self.get_link_by_code(referral_code)
if not link:
return None
now = datetime.utcnow()
return {
"referred_by_code": referral_code.lower(),
"referred_at": now,
"referral_discount_expires_at": now + timedelta(days=link.discount_duration_days),
}
def get_or_create_stripe_coupon(self, discount_percent: int) -> Optional[str]:
if not self.stripe_service:
return None
return self.stripe_service.get_or_create_referral_coupon(discount_percent)
def should_apply_discount(self, user_data: dict) -> bool:
if not user_data.get("referred_by_code"):
return False
expires_at = user_data.get("referral_discount_expires_at")
if not expires_at:
return False
if isinstance(expires_at, datetime):
now = datetime.utcnow()
# Firestore returns timezone-aware datetimes; ensure comparison is compatible
if expires_at.tzinfo is not None:
now = now.replace(tzinfo=expires_at.tzinfo)
return expires_at > now
return False
def get_discount_for_checkout(self, user_email: str) -> Optional[dict]:
from backend.services.user_service import get_user_service
user_service = get_user_service()
user = user_service.get_user(user_email)
if not user or not user.referred_by_code:
return None
user_data = {
"referred_by_code": user.referred_by_code,
"referral_discount_expires_at": user.referral_discount_expires_at,
}
if not self.should_apply_discount(user_data):
return None
link = self.get_link_by_code(user.referred_by_code)
if not link:
return None
coupon_id = self.get_or_create_stripe_coupon(link.discount_percent)
if not coupon_id:
return None
return {"coupon_id": coupon_id, "discount_percent": link.discount_percent}
# ========================================================================
# Earnings
# ========================================================================
def record_earning(self, referred_email: str, stripe_session_id: str, purchase_amount_cents: int) -> Optional[dict]:
"""Record a referral earning after a credit purchase."""
referred_email = referred_email.lower()
# Look up the referred user
user_doc = self.db.collection("gen_users").document(referred_email).get()
if not user_doc.exists:
return None
user_data = user_doc.to_dict()
referral_code = user_data.get("referred_by_code")
if not referral_code:
return None
referred_at = user_data.get("referred_at")
if not referred_at:
return None
link = self.get_link_by_code(referral_code)
if not link:
return None
# Check earning window
earning_expires = referred_at + timedelta(days=link.earning_duration_days)
if datetime.utcnow() > earning_expires:
return None
# Calculate earning
earning_amount = int(purchase_amount_cents * link.kickback_percent / 100)
if earning_amount <= 0:
return None
import uuid
earning_id = str(uuid.uuid4())
earning = ReferralEarning(
id=earning_id,
referrer_email=link.owner_email,
referred_email=referred_email,
referral_code=referral_code,
stripe_session_id=stripe_session_id,
purchase_amount_cents=purchase_amount_cents,
earning_amount_cents=earning_amount,
)
self.db.collection(REFERRAL_EARNINGS_COLLECTION).document(earning_id).set(
earning.model_dump(mode="json")
)
self.db.collection(REFERRAL_LINKS_COLLECTION).document(referral_code).update({
"stats.purchases": firestore.Increment(1),
"stats.total_earned_cents": firestore.Increment(earning_amount),
})
logger.info(f"Referral earning recorded: ${earning_amount / 100:.2f} for {link.owner_email}")
return {"earning_id": earning_id, "referrer_email": link.owner_email, "earning_amount_cents": earning_amount}
# ========================================================================
# Stripe Connect & Payouts
# ========================================================================
def create_connect_account(self, email: str) -> Tuple[Optional[str], Optional[str]]:
"""Create Stripe Connect account for a referrer."""
if not self.stripe_service:
return None, None
return self.stripe_service.create_connect_account(email)
def get_connect_account_status(self, account_id: str) -> Optional[dict]:
"""Get Stripe Connect account status."""
if not self.stripe_service:
return None
return self.stripe_service.get_connect_account_status(account_id)
def create_connect_login_link(self, account_id: str) -> Optional[str]:
"""Create login link for Stripe Express dashboard."""
if not self.stripe_service:
return None
return self.stripe_service.create_connect_login_link(account_id)
def create_connect_update_link(self, account_id: str) -> Optional[str]:
"""Create account link for updating Connect info."""
if not self.stripe_service:
return None
return self.stripe_service.create_connect_update_link(account_id)
def get_pending_earnings(self, referrer_email: str) -> List[dict]:
"""Get all pending earnings for a referrer."""
query = (
self.db.collection(REFERRAL_EARNINGS_COLLECTION)
.where("referrer_email", "==", referrer_email.lower())
.where("status", "==", "pending")
)
return [
{**doc.to_dict(), "_ref": doc.reference}
for doc in query.get()
]
def check_and_trigger_payout(self, referrer_email: str, stripe_connect_account_id: str) -> bool:
"""Check if pending earnings meet threshold and trigger payout."""
pending = self.get_pending_earnings(referrer_email)
total_pending = sum(e.get("earning_amount_cents", 0) for e in pending)
if total_pending < PAYOUT_THRESHOLD_CENTS:
return False
if not self.stripe_service:
return False
transfer_id = self.stripe_service.create_transfer(
amount_cents=total_pending,
destination_account_id=stripe_connect_account_id,
)
if not transfer_id:
return False
import uuid
payout_id = str(uuid.uuid4())
earning_ids = [e["id"] for e in pending]
payout = ReferralPayout(
id=payout_id,
referrer_email=referrer_email.lower(),
stripe_transfer_id=transfer_id,
amount_cents=total_pending,
earnings_included=earning_ids,
)
self.db.collection(REFERRAL_PAYOUTS_COLLECTION).document(payout_id).set(
payout.model_dump(mode="json")
)
for earning in pending:
if "_ref" in earning:
earning["_ref"].update({
"status": "paid",
"paid_at": datetime.utcnow(),
"payout_id": payout_id,
})
logger.info(f"Payout triggered: ${total_pending / 100:.2f} to {referrer_email} (transfer: {transfer_id})")
return True
def get_dashboard_data(self, user_email: str) -> dict:
"""Get full referral dashboard data for a user."""
user_email = user_email.lower()
link = self.get_or_create_link(user_email)
# Get recent earnings (last 20)
earnings_query = (
self.db.collection(REFERRAL_EARNINGS_COLLECTION)
.where("referrer_email", "==", user_email)
.order_by("created_at", direction=firestore.Query.DESCENDING)
.limit(20)
)
earnings = [doc.to_dict() for doc in earnings_query.stream()]
# Get recent payouts (last 10)
payouts_query = (
self.db.collection(REFERRAL_PAYOUTS_COLLECTION)
.where("referrer_email", "==", user_email)
.order_by("created_at", direction=firestore.Query.DESCENDING)
.limit(10)
)
payouts = [doc.to_dict() for doc in payouts_query.stream()]
# Compute pending balance from ALL pending earnings (not limited to recent)
pending_earnings = self.get_pending_earnings(user_email)
pending_balance = sum(e.get("earning_amount_cents", 0) for e in pending_earnings)
total_earned = link.stats.total_earned_cents
# total_paid = total_earned - pending (since total_earned tracks all time)
total_paid = total_earned - pending_balance
# Check Connect status and fetch account details
from backend.services.user_service import get_user_service
user = get_user_service().get_user(user_email)
has_connect = bool(user and user.stripe_connect_account_id)
connect_account = None
if has_connect and self.stripe_service:
connect_account = self.stripe_service.get_connect_account_status(
user.stripe_connect_account_id
)
return {
"link": {
"code": link.code,
"display_name": link.display_name,
"custom_message": link.custom_message,
"discount_percent": link.discount_percent,
"kickback_percent": link.kickback_percent,
"discount_duration_days": link.discount_duration_days,
"earning_duration_days": link.earning_duration_days,
"stats": link.stats.model_dump(),
"enabled": link.enabled,
"is_vanity": link.is_vanity,
},
"pending_balance_cents": pending_balance,
"total_earned_cents": total_earned,
"total_paid_cents": total_paid,
"recent_earnings": [
{
"id": e["id"],
"referred_email": e.get("referred_email", ""),
"purchase_amount_cents": e.get("purchase_amount_cents", 0),
"earning_amount_cents": e.get("earning_amount_cents", 0),
"status": e.get("status", "pending"),
"created_at": str(e.get("created_at", "")),
}
for e in earnings
],
"recent_payouts": [
{
"id": p["id"],
"amount_cents": p.get("amount_cents", 0),
"status": p.get("status", "processing"),
"created_at": str(p.get("created_at", "")),
}
for p in payouts
],
"stripe_connect_configured": has_connect,
"stripe_connect_account": connect_account,
}
def list_links(self, limit: int = 50, offset: int = 0) -> list[ReferralLink]:
"""List referral links for admin view."""
query = (
self.db.collection(REFERRAL_LINKS_COLLECTION)
.order_by("created_at", direction=firestore.Query.DESCENDING)
.offset(offset)
.limit(limit)
)
links = []
for doc in query.stream():
try:
links.append(ReferralLink(**doc.to_dict()))
except Exception:
logger.warning("Skipping malformed referral link doc: %s", doc.id)
return links
# ============================================================================
# Singleton accessor
# ============================================================================
_referral_service = None
def get_referral_service() -> ReferralService:
global _referral_service
if _referral_service is None:
from backend.services.stripe_service import get_stripe_service
_referral_service = ReferralService(stripe_service=get_stripe_service())
return _referral_service
+121 -5
View File
@@ -6,6 +6,7 @@ Handles:
- Processing webhook events
- Managing customer records
"""
import json
import logging
import os
from typing import Optional, Dict, Any, Tuple
@@ -22,25 +23,25 @@ logger = logging.getLogger(__name__)
CREDIT_PACKAGES = {
"1_credit": {
"credits": 1,
"price_cents": 500, # $5.00
"price_cents": 1000, # $10.00
"name": "1 Karaoke Credit",
"description": "Create 1 professional karaoke video",
},
"3_credits": {
"credits": 3,
"price_cents": 1200, # $12.00 (20% discount)
"price_cents": 2400, # $24.00 (20% discount)
"name": "3 Karaoke Credits",
"description": "Create 3 professional karaoke videos (Save 20%)",
},
"5_credits": {
"credits": 5,
"price_cents": 1750, # $17.50 (30% discount)
"price_cents": 3500, # $35.00 (30% discount)
"name": "5 Karaoke Credits",
"description": "Create 5 professional karaoke videos (Save 30%)",
},
"10_credits": {
"credits": 10,
"price_cents": 3000, # $30.00 (40% discount)
"price_cents": 6000, # $60.00 (40% discount)
"name": "10 Karaoke Credits",
"description": "Create 10 professional karaoke videos (Save 40%)",
},
@@ -96,6 +97,7 @@ class StripeService:
user_email: str,
success_url: Optional[str] = None,
cancel_url: Optional[str] = None,
coupon_id: Optional[str] = None,
) -> Tuple[bool, Optional[str], str]:
"""
Create a Stripe Checkout session for purchasing credits.
@@ -151,6 +153,11 @@ class StripeService:
'allow_promotion_codes': True,
}
# If a referral coupon is applied, use discounts instead of allow_promotion_codes
if coupon_id:
session_params.pop('allow_promotion_codes', None)
session_params['discounts'] = [{'coupon': coupon_id}]
# Add payment method configuration if set (enables Google Pay, Link, etc.)
if self.payment_method_config:
session_params['payment_method_configuration'] = self.payment_method_config
@@ -284,7 +291,10 @@ class StripeService:
event = stripe.Webhook.construct_event(
payload, signature, self.webhook_secret
)
return True, event, "Webhook verified"
# Convert Stripe Event object to plain dict — Stripe SDK v14+
# returns StripeObject instances that don't support .get()
event_dict = json.loads(str(event))
return True, event_dict, "Webhook verified"
except stripe.error.SignatureVerificationError as e:
logger.error(f"Invalid webhook signature: {e}")
return False, None, "Invalid signature"
@@ -351,6 +361,112 @@ class StripeService:
logger.error(f"Error retrieving session {session_id}: {e}")
return None
def get_or_create_referral_coupon(self, discount_percent: int) -> Optional[str]:
"""Get or create a Stripe coupon for a referral discount percentage."""
if not self.is_configured():
return None
coupon_id = f"referral-{discount_percent}pct"
try:
stripe.Coupon.retrieve(coupon_id)
return coupon_id
except stripe.error.InvalidRequestError:
try:
stripe.Coupon.create(
id=coupon_id,
percent_off=discount_percent,
duration="once",
name=f"Referral {discount_percent}% off",
)
logger.info(f"Created Stripe coupon: {coupon_id}")
return coupon_id
except stripe.error.StripeError as e:
logger.error(f"Failed to create coupon {coupon_id}: {e}")
return None
def create_connect_account(self, email: str) -> Tuple[Optional[str], Optional[str]]:
"""Create a Stripe Connect Express account. Returns (account_id, onboarding_url)."""
if not self.is_configured():
return None, None
try:
account = stripe.Account.create(
type="express",
email=email,
capabilities={"transfers": {"requested": True}},
metadata={"source": "nomad_karaoke_referrals"},
)
account_link = stripe.AccountLink.create(
account=account.id,
refresh_url=f"{self.frontend_url}/app/referrals?connect=refresh",
return_url=f"{self.frontend_url}/app/referrals?connect=complete",
type="account_onboarding",
)
logger.info(f"Created Connect account {account.id} for {email}")
return account.id, account_link.url
except stripe.error.StripeError as e:
logger.error(f"Failed to create Connect account for {email}: {e}")
return None, None
def get_connect_account_status(self, account_id: str) -> Optional[dict]:
"""Retrieve Stripe Connect account status. Returns dict with account details."""
if not self.is_configured():
return None
try:
account = stripe.Account.retrieve(account_id)
return {
"account_id": account.id,
"charges_enabled": account.charges_enabled,
"payouts_enabled": account.payouts_enabled,
"details_submitted": account.details_submitted,
"email": account.email,
}
except stripe.error.StripeError as e:
logger.error(f"Failed to retrieve Connect account {account_id}: {e}")
return None
def create_connect_login_link(self, account_id: str) -> Optional[str]:
"""Create a login link to the Stripe Express dashboard. Returns URL."""
if not self.is_configured():
return None
try:
link = stripe.Account.create_login_link(account_id)
return link.url
except stripe.error.StripeError as e:
logger.error(f"Failed to create login link for {account_id}: {e}")
return None
def create_connect_update_link(self, account_id: str) -> Optional[str]:
"""Create an account link for updating Connect account info. Returns URL."""
if not self.is_configured():
return None
try:
account_link = stripe.AccountLink.create(
account=account_id,
refresh_url=f"{self.frontend_url}/app/referrals?connect=refresh",
return_url=f"{self.frontend_url}/app/referrals?connect=complete",
type="account_onboarding",
)
return account_link.url
except stripe.error.StripeError as e:
logger.error(f"Failed to create update link for {account_id}: {e}")
return None
def create_transfer(self, amount_cents: int, destination_account_id: str, description: str = "Nomad Karaoke referral payout") -> Optional[str]:
"""Create a transfer to a Connect account. Returns transfer ID."""
if not self.is_configured():
return None
try:
transfer = stripe.Transfer.create(
amount=amount_cents,
currency="usd",
destination=destination_account_id,
description=description,
)
logger.info(f"Created transfer {transfer.id}: ${amount_cents / 100:.2f} to {destination_account_id}")
return transfer.id
except stripe.error.StripeError as e:
logger.error(f"Failed to create transfer to {destination_account_id}: {e}")
return None
def create_customer(self, email: str, name: Optional[str] = None) -> Optional[str]:
"""
Create or get a Stripe customer for a user.
+126 -20
View File
@@ -14,6 +14,7 @@ import re
from typing import Optional, Dict, Any
from backend.config import get_settings
from backend.i18n import t
logger = logging.getLogger(__name__)
@@ -154,29 +155,48 @@ class TemplateService:
logger.error(f"Failed to fetch template {blob_path}: {e}")
return None
def get_job_completion_template(self) -> str:
def get_job_completion_template(self, locale: str = "en") -> str:
"""Get the job completion email template."""
# Try locale-specific GCS template first, then default GCS, then localized default
if locale != "en":
template = self._fetch_template_from_gcs(f"{locale}/job-completion.txt")
if template is not None:
return template
template = self._fetch_template_from_gcs("job-completion.txt")
if template is None:
logger.info("Using default job completion template")
if template is not None:
return template
logger.info("Using default job completion template")
if locale == "en":
return DEFAULT_JOB_COMPLETION_TEMPLATE
return template
return self._build_localized_job_completion_template(locale)
def get_action_needed_lyrics_template(self) -> str:
def get_action_needed_lyrics_template(self, locale: str = "en") -> str:
"""Get the lyrics review reminder template."""
if locale != "en":
template = self._fetch_template_from_gcs(f"{locale}/action-needed-lyrics.txt")
if template is not None:
return template
template = self._fetch_template_from_gcs("action-needed-lyrics.txt")
if template is None:
logger.info("Using default lyrics reminder template")
if template is not None:
return template
logger.info("Using default lyrics reminder template")
if locale == "en":
return DEFAULT_ACTION_NEEDED_LYRICS_TEMPLATE
return template
return self._build_localized_action_lyrics_template(locale)
def get_action_needed_instrumental_template(self) -> str:
def get_action_needed_instrumental_template(self, locale: str = "en") -> str:
"""Get the instrumental selection reminder template."""
if locale != "en":
template = self._fetch_template_from_gcs(f"{locale}/action-needed-instrumental.txt")
if template is not None:
return template
template = self._fetch_template_from_gcs("action-needed-instrumental.txt")
if template is None:
logger.info("Using default instrumental reminder template")
if template is not None:
return template
logger.info("Using default instrumental reminder template")
if locale == "en":
return DEFAULT_ACTION_NEEDED_INSTRUMENTAL_TEMPLATE
return template
return self._build_localized_action_instrumental_template(locale)
def render_template(self, template: str, variables: Dict[str, Any]) -> str:
"""
@@ -215,6 +235,74 @@ class TemplateService:
return result.strip()
def _build_localized_job_completion_template(self, locale: str) -> str:
"""Build a localized job completion template from translation keys."""
ns = "emails.templates.jobCompletion"
return f"""{t(locale, f"{ns}.greeting")}
{t(locale, f"{ns}.thanks")}
{t(locale, f"{ns}.youtubeLink")}
{{youtube_url}}
{t(locale, f"{ns}.dropboxIntro")}
{t(locale, f"{ns}.fileList")}
{{dropbox_url}}
{t(locale, f"{ns}.fixOffer")}
{t(locale, f"{ns}.feedbackRequest")}
{{feedback_url}}
{t(locale, f"{ns}.signOff")}
"""
def _build_localized_action_lyrics_template(self, locale: str) -> str:
"""Build a localized action-needed lyrics template."""
ns = "emails.templates.actionLyrics"
return f"""{t(locale, f"{ns}.greeting")}
{t(locale, f"{ns}.ready")}
{t(locale, f"{ns}.instructions")}
{t(locale, f"{ns}.reviewPrompt")}
{{review_url}}
{t(locale, f"{ns}.duration")}
{t(locale, f"{ns}.signOff")}
"""
def _build_localized_action_instrumental_template(self, locale: str) -> str:
"""Build a localized action-needed instrumental template."""
ns = "emails.templates.actionInstrumental"
return f"""{t(locale, f"{ns}.greeting")}
{t(locale, f"{ns}.almostDone")}
{t(locale, f"{ns}.instructions")}
{t(locale, f"{ns}.selectPrompt")}
{{instrumental_url}}
{t(locale, f"{ns}.signOff")}
"""
def _build_localized_youtube_complete_template(self, locale: str) -> str:
"""Build a localized YouTube upload complete template."""
ns = "emails.templates.youtubeComplete"
return f"""{t(locale, f"{ns}.greeting")}
{t(locale, f"{ns}.greatNews")}
{{youtube_url}}
{t(locale, f"{ns}.delayNote")}
{t(locale, f"{ns}.signOff")}
"""
def render_job_completion(
self,
name: Optional[str] = None,
@@ -226,6 +314,7 @@ class TemplateService:
feedback_url: Optional[str] = None,
is_private: bool = False,
youtube_queued: bool = False,
locale: str = "en",
) -> str:
"""
Render the job completion email template.
@@ -244,7 +333,7 @@ class TemplateService:
Returns:
Rendered email content
"""
template = self.get_job_completion_template()
template = self.get_job_completion_template(locale)
# For private tracks, remove the YouTube section entirely
if is_private:
@@ -255,11 +344,18 @@ class TemplateService:
)
elif youtube_queued and not youtube_url:
# Replace YouTube URL with pending message
queued_msg = t(locale, "emails.templates.jobCompletion.youtubeQueued")
youtube_link_text = t(locale, "emails.templates.jobCompletion.youtubeLink")
template = template.replace(
"Here's the link for the karaoke video published to YouTube:\n{youtube_url}",
"Your YouTube upload is queued and will be processed automatically. "
"You'll receive a follow-up email with the link shortly."
f"{youtube_link_text}\n{{youtube_url}}",
queued_msg
)
# Also handle the English default template pattern
if "{youtube_url}" in template:
template = template.replace(
"Here's the link for the karaoke video published to YouTube:\n{youtube_url}",
queued_msg
)
variables = {
"name": name or "there",
@@ -278,6 +374,7 @@ class TemplateService:
artist: Optional[str] = None,
title: Optional[str] = None,
review_url: str = "",
locale: str = "en",
) -> str:
"""
Render the combined review reminder template.
@@ -294,7 +391,7 @@ class TemplateService:
Returns:
Rendered email content
"""
template = self.get_action_needed_lyrics_template()
template = self.get_action_needed_lyrics_template(locale)
variables = {
"name": name or "there",
"artist": artist or "Unknown Artist",
@@ -309,6 +406,7 @@ class TemplateService:
artist: Optional[str] = None,
title: Optional[str] = None,
instrumental_url: str = "",
locale: str = "en",
) -> str:
"""
Render the instrumental selection reminder template.
@@ -326,7 +424,7 @@ class TemplateService:
Returns:
Rendered email content
"""
template = self.get_action_needed_instrumental_template()
template = self.get_action_needed_instrumental_template(locale)
variables = {
"name": name or "there",
"artist": artist or "Unknown Artist",
@@ -341,6 +439,7 @@ class TemplateService:
artist: Optional[str] = None,
title: Optional[str] = None,
youtube_url: Optional[str] = None,
locale: str = "en",
) -> str:
"""
Render the YouTube upload complete follow-up email template.
@@ -356,9 +455,16 @@ class TemplateService:
Returns:
Rendered email content
"""
template = self._fetch_template_from_gcs("youtube-upload-complete.txt")
if locale != "en":
template = self._fetch_template_from_gcs(f"{locale}/youtube-upload-complete.txt")
if template is not None:
pass # Use locale-specific GCS template
else:
template = self._fetch_template_from_gcs("youtube-upload-complete.txt")
else:
template = self._fetch_template_from_gcs("youtube-upload-complete.txt")
if template is None:
template = DEFAULT_YOUTUBE_UPLOAD_COMPLETE_TEMPLATE
template = DEFAULT_YOUTUBE_UPLOAD_COMPLETE_TEMPLATE if locale == "en" else self._build_localized_youtube_complete_template(locale)
variables = {
"name": name or "there",
+70 -37
View File
@@ -13,6 +13,7 @@ import uuid
from datetime import datetime, timedelta, timezone
from typing import Optional, List, Tuple
from google.api_core import exceptions as google_exceptions
from google.cloud import firestore
from google.cloud.firestore_v1 import FieldFilter
from google.cloud.firestore_v1 import Increment
@@ -218,6 +219,7 @@ class UserService:
user_agent: Optional[str] = None,
tenant_id: Optional[str] = None,
device_fingerprint: Optional[str] = None,
referral_code: Optional[str] = None,
) -> MagicLinkToken:
"""
Create a magic link token for email authentication.
@@ -253,6 +255,7 @@ class UserService:
user_agent=user_agent,
tenant_id=tenant_id,
device_fingerprint=device_fingerprint,
referral_code=referral_code,
)
# Save to Firestore
@@ -370,7 +373,11 @@ 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) -> Tuple[bool, str]:
def grant_welcome_credits_if_eligible(
self,
email: str,
precomputed_eval: Optional[dict] = None,
) -> Tuple[bool, str]:
"""
Grant welcome credits on first magic link verification.
@@ -381,6 +388,12 @@ class UserService:
check (survives credit_transactions list trimming). Falls back to
checking for welcome_credit transaction as secondary defense.
Args:
email: User's email address.
precomputed_eval: Optional pre-computed evaluation from magic link doc.
Keys: credit_eval_decision, credit_eval_reasoning, credit_eval_error.
If provided and has a decision, skips the AI call.
Returns:
Tuple of (credits_granted: bool, status: str).
status is one of: "granted", "denied", "already_granted", "not_found", "error"
@@ -400,50 +413,70 @@ class UserService:
if txn.reason == "welcome_credit":
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}"
# Skip AI evaluation for test emails (e.g. E2E test accounts)
# to avoid wasting LLM credits and sending unnecessary denial emails
from backend.utils.test_data import is_test_email
if not is_test_email(email):
# AI evaluation: check for abuse signals before granting
# Use pre-computed result from magic link if available
try:
from backend.services.credit_evaluation_service import (
get_credit_evaluation_service,
CreditEvaluation,
)
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"
precomputed_decision = (precomputed_eval or {}).get("credit_eval_decision")
if precomputed_decision:
logger.info(f"Using pre-computed credit eval for {email}: {precomputed_decision}")
evaluation = CreditEvaluation(
decision=precomputed_decision,
reasoning=(precomputed_eval or {}).get("credit_eval_reasoning", ""),
confidence=1.0,
error=(precomputed_eval or {}).get("credit_eval_error"),
)
else:
eval_service = get_credit_evaluation_service()
evaluation = eval_service.evaluate(email, "welcome")
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}"
)
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, signals=evaluation.signals,
)
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", evaluation.reasoning, signals=evaluation.signals,
email, "welcome", f"Evaluation error: {email}",
)
except Exception:
logger.exception(f"Failed to send review needed email for {email}")
pass
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"
else:
logger.info(f"Skipping credit evaluation for test email {email}")
# Grant welcome credits
welcome_credit = self.NEW_USER_FREE_CREDITS
@@ -967,7 +1000,7 @@ class UserService:
'amount': amount,
'processed_at': datetime.utcnow()
})
except Exception:
except google_exceptions.AlreadyExists:
# Document already exists - this session was already processed
logger.info(f"Stripe session {stripe_session_id} already processed (idempotent skip)")
return False, 0, "Session already processed"
+33 -5
View File
@@ -383,14 +383,13 @@ class WorkerService:
"""
Trigger audio separation worker.
Always uses Cloud Run Jobs to avoid instance termination during long-running
Modal API calls. The BackgroundTasks approach caused Cloud Run to terminate
instances mid-processing when no HTTP requests were active.
Uses Cloud Run Jobs with L4 GPU in us-east4 for direct audio separation.
"""
return await self._trigger_worker_cloud_run_job(
job_id=job_id,
cloud_run_job_name="audio-separation-job",
worker_module="audio_worker",
location="us-east4", # GPU job runs in us-east4 (L4 quota)
)
async def trigger_lyrics_worker(self, job_id: str) -> bool:
@@ -412,14 +411,40 @@ class WorkerService:
"""Trigger screen generation worker."""
return await self.trigger_worker("screens", job_id)
def _warmup_encoding_worker(self, job_id: str) -> None:
"""Fire-and-forget warmup of the encoding worker VM.
Called before dispatching video/render workers so the GCE encoding
VM starts booting while the worker downloads files and prepares.
Failures are logged but never block worker dispatch.
"""
try:
from backend.services.encoding_worker_manager import EncodingWorkerManager
from google.cloud import compute_v1, firestore
db = firestore.Client(project=self.settings.google_cloud_project)
compute_client = compute_v1.InstancesClient()
manager = EncodingWorkerManager(
db=db,
compute_client=compute_client,
project_id=self.settings.google_cloud_project,
)
result = manager.ensure_primary_running()
if result["started"]:
logger.info(f"[job:{job_id}] Encoding worker warmup: started VM {result['vm_name']}")
else:
logger.info(f"[job:{job_id}] Encoding worker warmup: VM {result['vm_name']} already running")
except Exception as e:
logger.warning(f"[job:{job_id}] Encoding worker warmup failed (non-fatal): {e}")
async def trigger_video_worker(self, job_id: str) -> bool:
"""
Trigger video generation worker.
When USE_CLOUD_RUN_JOBS_FOR_VIDEO=true and ENABLE_CLOUD_TASKS=true,
uses Cloud Run Jobs for execution (supports >30 min encoding).
Otherwise, uses Cloud Tasks or direct HTTP.
"""
self._warmup_encoding_worker(job_id)
if self._use_cloud_tasks and self.settings.use_cloud_run_jobs_for_video:
return await self._trigger_cloud_run_job(job_id)
return await self.trigger_worker("video", job_id)
@@ -448,6 +473,7 @@ class WorkerService:
job_id: str,
cloud_run_job_name: str,
worker_module: str,
location: str | None = None,
) -> bool:
"""
Trigger a worker as a Cloud Run Job.
@@ -460,6 +486,7 @@ class WorkerService:
job_id: Job ID to process
cloud_run_job_name: Name of the Cloud Run Job (e.g., "lyrics-transcription-job")
worker_module: Worker module name (e.g., "lyrics_worker")
location: GCP region for the job (defaults to settings.gcp_region)
Returns:
True if job was triggered successfully, False otherwise
@@ -472,7 +499,7 @@ class WorkerService:
logger.error("GOOGLE_CLOUD_PROJECT not set, cannot trigger Cloud Run Job")
return False
location = self.settings.gcp_region
location = location or self.settings.gcp_region
job_name = f"projects/{project}/locations/{location}/jobs/{cloud_run_job_name}"
# Create Cloud Run Jobs client
@@ -510,6 +537,7 @@ class WorkerService:
async def trigger_render_video_worker(self, job_id: str) -> bool:
"""Trigger render video worker (post-review)."""
self._warmup_encoding_worker(job_id)
return await self.trigger_worker("render-video", job_id)
async def schedule_idle_reminder(
@@ -0,0 +1,362 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Nomad Karaoke - Make Your Own Karaoke Videos</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Outfit:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
*, html { margin: 0; padding: 0; box-sizing: border-box; }
@page {
size: 8.5in 11in;
margin: 0;
}
body {
width: 8.5in;
height: 11in;
overflow: hidden;
position: relative;
font-family: 'Outfit', sans-serif;
background: #0c0a1a;
color: #fff;
}
/* Dark atmospheric background */
.bg {
position: absolute;
inset: 0;
background:
radial-gradient(ellipse 80% 50% at 50% 0%, rgba(120, 40, 200, 0.35) 0%, transparent 70%),
radial-gradient(ellipse 60% 40% at 20% 80%, rgba(255, 50, 120, 0.2) 0%, transparent 60%),
radial-gradient(ellipse 50% 30% at 85% 70%, rgba(255, 180, 40, 0.15) 0%, transparent 60%),
linear-gradient(180deg, #0c0a1a 0%, #1a1035 40%, #0c0a1a 100%);
z-index: 0;
}
.content {
position: relative;
z-index: 2;
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
padding: 0.6in 0.65in 0.5in;
}
/* Logo at top */
.logo-container {
margin-bottom: 24px;
}
.logo-svg {
width: 260px;
height: auto;
}
/* Headline */
.headline {
font-family: 'Bebas Neue', sans-serif;
text-align: center;
line-height: 0.92;
margin-bottom: 6px;
}
.headline-main {
font-size: 96px;
letter-spacing: 3px;
background: linear-gradient(180deg, #ffd86b 0%, #ff7acc 50%, #c45aff 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.headline-sub {
font-size: 62px;
letter-spacing: 2px;
color: #fff;
}
/* Subtitle */
.subtitle {
font-size: 20px;
font-weight: 500;
color: rgba(255, 255, 255, 0.7);
text-align: center;
max-width: 5.5in;
line-height: 1.4;
margin-bottom: 28px;
}
/* Steps section */
.steps {
display: flex;
flex-direction: column;
gap: 18px;
width: 100%;
max-width: 6in;
margin-bottom: 28px;
}
.step {
display: flex;
align-items: center;
gap: 18px;
}
.step-number {
width: 52px;
height: 52px;
flex-shrink: 0;
border-radius: 50%;
background: linear-gradient(135deg, #c45aff, #ff7acc);
display: flex;
align-items: center;
justify-content: center;
font-family: 'Bebas Neue', sans-serif;
font-size: 30px;
color: #fff;
letter-spacing: 1px;
}
.step-content {
flex: 1;
}
.step-title {
font-size: 22px;
font-weight: 800;
color: #fff;
letter-spacing: -0.3px;
}
.step-desc {
font-size: 16px;
font-weight: 400;
color: rgba(255, 255, 255, 0.6);
margin-top: 2px;
}
/* Divider */
.divider {
width: 80%;
height: 2px;
background: linear-gradient(90deg, transparent, rgba(255, 122, 204, 0.4), rgba(255, 216, 107, 0.4), transparent);
margin: 4px 0 24px;
}
/* CTA section */
.cta-section {
display: flex;
align-items: center;
justify-content: center;
gap: 40px;
width: 100%;
margin-bottom: 20px;
}
.qr-container {
width: 180px;
height: 180px;
border-radius: 16px;
background: #fff;
border: 3px solid rgba(255, 255, 255, 0.15);
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
box-shadow: 0 4px 20px rgba(0,0,0,0.06);
overflow: hidden;
}
.qr-container img {
width: 100%;
height: 100%;
object-fit: contain;
}
.qr-placeholder {
font-size: 14px;
color: #999;
text-align: center;
padding: 20px;
}
.cta-text {
display: flex;
flex-direction: column;
align-items: flex-start;
}
.cta-label {
font-size: 16px;
font-weight: 600;
color: rgba(255, 255, 255, 0.6);
text-transform: uppercase;
letter-spacing: 2px;
margin-bottom: 6px;
}
.cta-url {
font-family: 'Bebas Neue', sans-serif;
font-size: 38px;
letter-spacing: 2px;
color: #ffd86b;
line-height: 1;
white-space: nowrap;
}
.cta-url .referral-code {
background: linear-gradient(135deg, #ff7acc 0%, #c45aff 40%, #ff5a8a 70%, #ffdf6b 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
letter-spacing: 4px;
}
.cta-note {
font-size: 15px;
color: rgba(255, 255, 255, 0.5);
margin-top: 8px;
font-weight: 500;
}
/* Bottom section */
.bottom {
margin-top: auto;
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
}
.bottom-features {
display: flex;
gap: 24px;
}
.bottom-feature {
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
font-weight: 600;
color: rgba(255, 255, 255, 0.5);
}
.bottom-feature-icon {
font-size: 20px;
}
.bottom-tagline {
font-size: 14px;
font-weight: 500;
color: rgba(255, 255, 255, 0.4);
letter-spacing: 1px;
}
@media print {
body {
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
}
</style>
</head>
<body>
<div class="bg"></div>
<div class="content">
<!-- Logo -->
<div class="logo-container">
<svg class="logo-svg" viewBox="45 60 255 135" xmlns="http://www.w3.org/2000/svg">
<g fill="#ff7acc" transform="translate(48.368003845214844,62.62239074707031)"><g transform="translate(0,0)"><g transform="scale(1.4000000000000004)"><g stroke="#ff7acc" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" paint-order="stroke" fill-opacity="0"><path d="M1.4-33.44L1.4 0C31.48 0 3.96 0 34.04 0L34.04-32.64 17.81-32.64 17.81-20.61 1.4-33.44ZM52.21-33.76C42.6-33.76 34.81-25.97 34.81-16.37 34.81-6.76 42.6 1.03 52.21 1.03 61.81 1.03 69.6-6.76 69.6-16.37 69.6-25.97 61.81-33.76 52.21-33.76ZM70.7 0L103.34 0 103.25-33.9 86.93-21.54 70.61-33.9 70.7 0ZM102.34 0C138.2 0 107.52 0 143.56 0L122.95-34.93 102.34 0ZM158.84 0.05C167.84 0.05 175.16-7.27 175.16-16.27 175.16-25.27 167.84-32.64 158.84-32.64L142.52-32.64C142.52 0.75 142.52-33.34 142.52 0.05L158.84 0.05Z" transform="translate(-1.399999976158142, 34.93000030517578)"></path></g><g transform="translate(0,38.959999084472656)"><g stroke="#ff7acc" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" paint-order="stroke" fill="#ff7acc" fill-opacity="0" transform="scale(1.02719)"><path d="M24.43 0L17.67 0 7.98-11.87 7.98 0 2.63 0 2.63-26.64 7.98-26.64 7.98-14.69 17.67-26.64 24.12-26.64 13.13-13.44 24.43 0ZM45.03 0L43.27-5.08 32.66-5.08 30.91 0 25.3 0 34.88-26.68 41.1-26.68 50.68 0 45.03 0ZM34.11-9.35L41.82-9.35 37.97-20.5 34.11-9.35ZM73.19 0L67.01 0 61.13-10.38 58.61-10.38 58.61 0 53.27 0 53.27-26.64 63.27-26.64Q66.36-26.64 68.53-25.55 70.71-24.47 71.8-22.61 72.89-20.76 72.89-18.47L72.89-18.47Q72.89-15.84 71.36-13.72 69.83-11.6 66.82-10.8L66.82-10.8 73.19 0ZM58.61-22.21L58.61-14.39 63.08-14.39Q65.25-14.39 66.32-15.44 67.39-16.49 67.39-18.36L67.39-18.36Q67.39-20.19 66.32-21.2 65.25-22.21 63.08-22.21L63.08-22.21 58.61-22.21ZM94.82 0L93.07-5.08 82.46-5.08 80.7 0 75.09 0 84.67-26.68 90.89-26.68 100.47 0 94.82 0ZM83.91-9.35L91.62-9.35 87.76-20.5 83.91-9.35ZM115.43 0.27Q111.69 0.27 108.56-1.49 105.43-3.24 103.6-6.35 101.76-9.47 101.76-13.4L101.76-13.4Q101.76-17.29 103.6-20.4 105.43-23.51 108.56-25.27 111.69-27.02 115.43-27.02L115.43-27.02Q119.21-27.02 122.32-25.27 125.43-23.51 127.24-20.4 129.05-17.29 129.05-13.4L129.05-13.4Q129.05-9.47 127.24-6.35 125.43-3.24 122.3-1.49 119.17 0.27 115.43 0.27L115.43 0.27ZM115.43-4.5Q117.83-4.5 119.66-5.59 121.5-6.68 122.53-8.7 123.56-10.73 123.56-13.4L123.56-13.4Q123.56-16.07 122.53-18.07 121.5-20.08 119.66-21.15 117.83-22.21 115.43-22.21L115.43-22.21Q113.02-22.21 111.17-21.15 109.32-20.08 108.29-18.07 107.26-16.07 107.26-13.4L107.26-13.4Q107.26-10.73 108.29-8.7 109.32-6.68 111.17-5.59 113.02-4.5 115.43-4.5L115.43-4.5ZM153.82 0L147.06 0 137.37-11.87 137.37 0 132.02 0 132.02-26.64 137.37-26.64 137.37-14.69 147.06-26.64 153.51-26.64 142.52-13.44 153.82 0ZM171.79-22.33L161.67-22.33 161.67-15.65 170.64-15.65 170.64-11.41 161.67-11.41 161.67-4.35 171.79-4.35 171.79 0 156.33 0 156.33-26.68 171.79-26.68 171.79-22.33Z" transform="translate(-2.630000114440918, 27.020000457763672)"></path></g></g></g></g>
<g fill-rule="" fill="#ffdf6b" transform="translate(5,111.788818359375)"><rect x="0" height="1" y="5.9832000732421875" width="14.278396606445312"></rect><rect height="1" y="5.9832000732421875" width="14.278396606445312" x="218.985595703125"></rect><g transform="translate(17.278396606445312,0)"><g transform="scale(1.2800000000000002)"><path d="M10.21-8.38L12.02-8.38L9.68 0L7.70 0L6.13-5.96L4.49 0L2.52 0.01L0.26-8.38L2.06-8.38L3.54-1.87L5.24-8.38L7.12-8.38L8.72-1.91L10.21-8.38ZM18.38-8.38L20.06-8.38L20.06 0L18.38 0L18.38-3.56L14.80-3.56L14.80 0L13.12 0L13.12-8.38L14.80-8.38L14.80-4.93L18.38-4.93L18.38-8.38ZM26.58-7.02L23.40-7.02L23.40-4.92L26.22-4.92L26.22-3.59L23.40-3.59L23.40-1.37L26.58-1.37L26.58 0L21.72 0L21.72-8.39L26.58-8.39L26.58-7.02ZM34.37 0L32.42 0L30.58-3.26L29.78-3.26L29.78 0L28.10 0L28.10-8.38L31.25-8.38Q32.22-8.38 32.90-8.03Q33.59-7.69 33.93-7.11Q34.27-6.53 34.27-5.81L34.27-5.81Q34.27-4.98 33.79-4.31Q33.31-3.65 32.36-3.40L32.36-3.40L34.37 0ZM29.78-6.98L29.78-4.52L31.19-4.52Q31.87-4.52 32.21-4.85Q32.54-5.18 32.54-5.77L32.54-5.77Q32.54-6.35 32.21-6.67Q31.87-6.98 31.19-6.98L31.19-6.98L29.78-6.98ZM40.66-7.02L37.48-7.02L37.48-4.92L40.30-4.92L40.30-3.59L37.48-3.59L37.48-1.37L40.66-1.37L40.66 0L35.80 0L35.80-8.39L40.66-8.39L40.66-7.02ZM47.92-8.38L49.70-8.38L46.63 0L44.59 0L41.52-8.38L43.32-8.38L45.62-1.72L47.92-8.38ZM55.57-7.02L52.39-7.02L52.39-4.92L55.21-4.92L55.21-3.59L52.39-3.59L52.39-1.37L55.57-1.37L55.57 0L50.71 0L50.71-8.39L55.57-8.39L55.57-7.02ZM63.36 0L61.42 0L59.57-3.26L58.78-3.26L58.78 0L57.10 0L57.10-8.38L60.24-8.38Q61.21-8.38 61.90-8.03Q62.58-7.69 62.92-7.11Q63.26-6.53 63.26-5.81L63.26-5.81Q63.26-4.98 62.78-4.31Q62.30-3.65 61.36-3.40L61.36-3.40L63.36 0ZM58.78-6.98L58.78-4.52L60.18-4.52Q60.86-4.52 61.20-4.85Q61.54-5.18 61.54-5.77L61.54-5.77Q61.54-6.35 61.20-6.67Q60.86-6.98 60.18-6.98L60.18-6.98L58.78-6.98ZM72.43-8.38L74.30-8.38L71.47-2.92L71.47 0L69.79 0L69.79-2.92L66.95-8.38L68.84-8.38L70.64-4.55L72.43-8.38ZM79.16 0.08Q77.99 0.08 77.00-0.47Q76.02-1.02 75.44-2.00Q74.87-2.98 74.87-4.21L74.87-4.21Q74.87-5.44 75.44-6.41Q76.02-7.39 77.00-7.94Q77.99-8.50 79.16-8.50L79.16-8.50Q80.35-8.50 81.33-7.94Q82.31-7.39 82.88-6.41Q83.45-5.44 83.45-4.21L83.45-4.21Q83.45-2.98 82.88-2.00Q82.31-1.02 81.32-0.47Q80.34 0.08 79.16 0.08L79.16 0.08ZM79.16-1.42Q79.92-1.42 80.50-1.76Q81.07-2.10 81.40-2.74Q81.72-3.37 81.72-4.21L81.72-4.21Q81.72-5.05 81.40-5.68Q81.07-6.31 80.50-6.65Q79.92-6.98 79.16-6.98L79.16-6.98Q78.41-6.98 77.83-6.65Q77.24-6.31 76.92-5.68Q76.60-5.05 76.60-4.21L76.60-4.21Q76.60-3.37 76.92-2.74Q77.24-2.10 77.83-1.76Q78.41-1.42 79.16-1.42L79.16-1.42ZM84.67-8.38L86.35-8.38L86.35-3.19Q86.35-2.34 86.80-1.89Q87.24-1.44 88.04-1.44L88.04-1.44Q88.86-1.44 89.30-1.89Q89.75-2.34 89.75-3.19L89.75-3.19L89.75-8.38L91.44-8.38L91.44-3.20Q91.44-2.14 90.98-1.40Q90.52-0.66 89.74-0.29Q88.97 0.08 88.02 0.08L88.02 0.08Q87.08 0.08 86.32-0.29Q85.56-0.66 85.12-1.40Q84.67-2.14 84.67-3.20L84.67-3.20L84.67-8.38ZM101.60 0L101.05-1.60L97.72-1.60L97.16 0L95.40 0L98.41-8.39L100.37-8.39L103.38 0L101.60 0ZM98.17-2.94L100.60-2.94L99.38-6.44L98.17-2.94ZM110.77 0L108.83 0L106.98-3.26L106.19-3.26L106.19 0L104.51 0L104.51-8.38L107.65-8.38Q108.62-8.38 109.31-8.03Q109.99-7.69 110.33-7.11Q110.68-6.53 110.68-5.81L110.68-5.81Q110.68-4.98 110.20-4.31Q109.72-3.65 108.77-3.40L108.77-3.40L110.77 0ZM106.19-6.98L106.19-4.52L107.59-4.52Q108.28-4.52 108.61-4.85Q108.95-5.18 108.95-5.77L108.95-5.77Q108.95-6.35 108.61-6.67Q108.28-6.98 107.59-6.98L107.59-6.98L106.19-6.98ZM117.06-7.02L113.88-7.02L113.88-4.92L116.70-4.92L116.70-3.59L113.88-3.59L113.88-1.37L117.06-1.37L117.06 0L112.20 0L112.20-8.39L117.06-8.39L117.06-7.02ZM118.72-1.76L120.42-1.76L119.02 1.61L117.94 1.61L118.72-1.76ZM127.38 0.08Q126.50 0.08 125.80-0.22Q125.10-0.52 124.69-1.08Q124.28-1.64 124.27-2.41L124.27-2.41L126.07-2.41Q126.11-1.90 126.44-1.60Q126.77-1.30 127.34-1.30L127.34-1.30Q127.93-1.30 128.27-1.58Q128.60-1.86 128.60-2.32L128.60-2.32Q128.60-2.69 128.38-2.93Q128.15-3.17 127.81-3.31Q127.46-3.44 126.86-3.61L126.86-3.61Q126.05-3.85 125.54-4.09Q125.03-4.32 124.66-4.79Q124.30-5.27 124.30-6.06L124.30-6.06Q124.30-6.80 124.67-7.36Q125.04-7.91 125.71-8.20Q126.38-8.50 127.25-8.50L127.25-8.50Q128.54-8.50 129.35-7.87Q130.16-7.24 130.25-6.11L130.25-6.11L128.40-6.11Q128.38-6.54 128.03-6.82Q127.69-7.10 127.13-7.10L127.13-7.10Q126.64-7.10 126.34-6.85Q126.05-6.60 126.05-6.12L126.05-6.12Q126.05-5.78 126.27-5.56Q126.49-5.34 126.82-5.20Q127.15-5.06 127.75-4.88L127.75-4.88Q128.57-4.64 129.08-4.40Q129.60-4.16 129.97-3.68Q130.34-3.20 130.34-2.42L130.34-2.42Q130.34-1.75 130.00-1.18Q129.65-0.60 128.98-0.26Q128.30 0.08 127.38 0.08L127.38 0.08ZM131.80-8.38L133.48-8.38L133.48 0L131.80 0L131.80-8.38ZM142.30-8.39L142.30 0L140.62 0L136.81-5.75L136.81 0L135.13 0L135.13-8.39L136.81-8.39L140.62-2.63L140.62-8.39L142.30-8.39ZM151.72-5.86L149.78-5.86Q149.50-6.38 148.99-6.66Q148.49-6.94 147.82-6.94L147.82-6.94Q147.07-6.94 146.50-6.60Q145.92-6.26 145.60-5.64Q145.27-5.02 145.27-4.20L145.27-4.20Q145.27-3.36 145.60Line truncated
</svg>
</svg>
</div>
<!-- Headline -->
<div class="headline">
<div class="headline-main">MAKE YOUR OWN</div>
<div class="headline-sub">KARAOKE VIDEOS</div>
</div>
<!-- Subtitle -->
<div class="subtitle">
Turn any song into a professional karaoke video with synced lyrics, vocal removal, and automatic YouTube publishing.
</div>
<!-- How it works -->
<div class="steps">
<div class="step">
<div class="step-number">1</div>
<div class="step-content">
<div class="step-title">Pick any song</div>
<div class="step-desc">Search by artist &amp; title or paste a YouTube link</div>
</div>
</div>
<div class="step">
<div class="step-number">2</div>
<div class="step-content">
<div class="step-title">Our system does the work</div>
<div class="step-desc">Vocals removed, lyrics synced, video rendered automatically</div>
</div>
</div>
<div class="step">
<div class="step-number">3</div>
<div class="step-content">
<div class="step-title">Review &amp; correct the lyrics and instrumental</div>
<div class="step-desc">Fine-tune everything before publishing</div>
</div>
</div>
<div class="step">
<div class="step-number">4</div>
<div class="step-content">
<div class="step-title">Download or publish to YouTube</div>
<div class="step-desc">Get your finished karaoke video in minutes</div>
</div>
</div>
</div>
<div class="divider"></div>
<!-- CTA with QR code -->
<div class="cta-section">
<div class="qr-container">
<!-- Replace src with actual QR code image path -->
<img src="{{QR_DATA_URL}}" alt="QR Code - nomadkaraoke.com/r/{{REFERRAL_CODE_LOWER}}">
</div>
<div class="cta-text">
<div class="cta-label">First track free + {{DISCOUNT_PERCENT}}% off with this link</div>
<div class="cta-url">NOMADKARAOKE.COM/R/<span class="referral-code">{{REFERRAL_CODE}}</span></div>
<div class="cta-note">Scan the QR code or visit the link above</div>
</div>
</div>
<!-- Bottom -->
<div class="bottom">
<div class="bottom-features">
<div class="bottom-feature">
<span class="bottom-feature-icon">&#127908;</span>
<span>Any Song</span>
</div>
<div class="bottom-feature">
<span class="bottom-feature-icon">&#9889;</span>
<span>Automatic</span>
</div>
<div class="bottom-feature">
<span class="bottom-feature-icon">&#127916;</span>
<span>Pro Quality</span>
</div>
</div>
<div class="bottom-tagline">Wherever you are, sing!</div>
</div>
</div>
</body>
</html>
@@ -0,0 +1,359 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Nomad Karaoke - Make Your Own Karaoke Videos</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Outfit:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
*, html { margin: 0; padding: 0; box-sizing: border-box; }
@page {
size: 8.5in 11in;
margin: 0;
}
body {
width: 8.5in;
height: 11in;
overflow: hidden;
position: relative;
font-family: 'Outfit', sans-serif;
background: #faf8f5;
color: #1a1a1a;
position: relative;
}
/* Simple gradient background */
.bg {
position: absolute;
inset: 0;
background: linear-gradient(180deg, #faf8f5 0%, #f3eff8 100%);
z-index: 0;
}
.content {
position: relative;
z-index: 2;
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
padding: 0.6in 0.65in 0.5in;
}
/* Logo at top */
.logo-container {
margin-bottom: 24px;
}
.logo-svg {
width: 260px;
height: auto;
}
/* Headline */
.headline {
font-family: 'Bebas Neue', sans-serif;
text-align: center;
line-height: 0.92;
margin-bottom: 6px;
}
.headline-main {
font-size: 96px;
letter-spacing: 3px;
background: linear-gradient(135deg, #c45aff 0%, #ff7acc 50%, #ff5a8a 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.headline-sub {
font-size: 62px;
letter-spacing: 2px;
color: #1a1a1a;
}
/* Subtitle */
.subtitle {
font-size: 20px;
font-weight: 500;
color: #555;
text-align: center;
max-width: 5.5in;
line-height: 1.4;
margin-bottom: 28px;
}
/* Steps section */
.steps {
display: flex;
flex-direction: column;
gap: 18px;
width: 100%;
max-width: 6in;
margin-bottom: 28px;
}
.step {
display: flex;
align-items: center;
gap: 18px;
}
.step-number {
width: 52px;
height: 52px;
flex-shrink: 0;
border-radius: 50%;
background: linear-gradient(135deg, #c45aff, #ff7acc);
display: flex;
align-items: center;
justify-content: center;
font-family: 'Bebas Neue', sans-serif;
font-size: 30px;
color: #fff;
letter-spacing: 1px;
}
.step-content {
flex: 1;
}
.step-title {
font-size: 22px;
font-weight: 800;
color: #1a1a1a;
letter-spacing: -0.3px;
}
.step-desc {
font-size: 16px;
font-weight: 400;
color: #666;
margin-top: 2px;
}
/* Divider */
.divider {
width: 80%;
height: 2px;
background: linear-gradient(90deg, transparent, rgba(196, 90, 255, 0.3), rgba(255, 122, 204, 0.3), transparent);
margin: 4px 0 24px;
}
/* CTA section */
.cta-section {
display: flex;
align-items: center;
justify-content: center;
gap: 40px;
width: 100%;
margin-bottom: 20px;
}
.qr-container {
width: 180px;
height: 180px;
border-radius: 16px;
background: #fff;
border: 3px solid #e8e4e0;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
box-shadow: 0 4px 20px rgba(0,0,0,0.06);
overflow: hidden;
}
.qr-container img {
width: 100%;
height: 100%;
object-fit: contain;
}
.qr-placeholder {
font-size: 14px;
color: #999;
text-align: center;
padding: 20px;
}
.cta-text {
display: flex;
flex-direction: column;
align-items: flex-start;
}
.cta-label {
font-size: 16px;
font-weight: 600;
color: #888;
text-transform: uppercase;
letter-spacing: 2px;
margin-bottom: 6px;
}
.cta-url {
font-family: 'Bebas Neue', sans-serif;
font-size: 38px;
letter-spacing: 2px;
color: #1a1a1a;
line-height: 1;
white-space: nowrap;
}
.cta-url .referral-code {
background: linear-gradient(135deg, #ff7acc 0%, #c45aff 40%, #ff5a8a 70%, #ffdf6b 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
letter-spacing: 4px;
}
.cta-note {
font-size: 15px;
color: #888;
margin-top: 8px;
font-weight: 500;
}
/* Bottom section */
.bottom {
margin-top: auto;
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
}
.bottom-features {
display: flex;
gap: 24px;
}
.bottom-feature {
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
font-weight: 600;
color: #888;
}
.bottom-feature-icon {
font-size: 20px;
}
.bottom-tagline {
font-size: 14px;
font-weight: 500;
color: #aaa;
letter-spacing: 1px;
}
@media print {
body {
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
}
</style>
</head>
<body>
<div class="bg"></div>
<div class="content">
<!-- Logo -->
<div class="logo-container">
<svg class="logo-svg" viewBox="45 60 255 135" xmlns="http://www.w3.org/2000/svg">
<g fill="#ff7acc" transform="translate(48.368003845214844,62.62239074707031)"><g transform="translate(0,0)"><g transform="scale(1.4000000000000004)"><g stroke="#ff7acc" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" paint-order="stroke" fill-opacity="0"><path d="M1.4-33.44L1.4 0C31.48 0 3.96 0 34.04 0L34.04-32.64 17.81-32.64 17.81-20.61 1.4-33.44ZM52.21-33.76C42.6-33.76 34.81-25.97 34.81-16.37 34.81-6.76 42.6 1.03 52.21 1.03 61.81 1.03 69.6-6.76 69.6-16.37 69.6-25.97 61.81-33.76 52.21-33.76ZM70.7 0L103.34 0 103.25-33.9 86.93-21.54 70.61-33.9 70.7 0ZM102.34 0C138.2 0 107.52 0 143.56 0L122.95-34.93 102.34 0ZM158.84 0.05C167.84 0.05 175.16-7.27 175.16-16.27 175.16-25.27 167.84-32.64 158.84-32.64L142.52-32.64C142.52 0.75 142.52-33.34 142.52 0.05L158.84 0.05Z" transform="translate(-1.399999976158142, 34.93000030517578)"></path></g><g transform="translate(0,38.959999084472656)"><g stroke="#ff7acc" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" paint-order="stroke" fill="#ff7acc" fill-opacity="0" transform="scale(1.02719)"><path d="M24.43 0L17.67 0 7.98-11.87 7.98 0 2.63 0 2.63-26.64 7.98-26.64 7.98-14.69 17.67-26.64 24.12-26.64 13.13-13.44 24.43 0ZM45.03 0L43.27-5.08 32.66-5.08 30.91 0 25.3 0 34.88-26.68 41.1-26.68 50.68 0 45.03 0ZM34.11-9.35L41.82-9.35 37.97-20.5 34.11-9.35ZM73.19 0L67.01 0 61.13-10.38 58.61-10.38 58.61 0 53.27 0 53.27-26.64 63.27-26.64Q66.36-26.64 68.53-25.55 70.71-24.47 71.8-22.61 72.89-20.76 72.89-18.47L72.89-18.47Q72.89-15.84 71.36-13.72 69.83-11.6 66.82-10.8L66.82-10.8 73.19 0ZM58.61-22.21L58.61-14.39 63.08-14.39Q65.25-14.39 66.32-15.44 67.39-16.49 67.39-18.36L67.39-18.36Q67.39-20.19 66.32-21.2 65.25-22.21 63.08-22.21L63.08-22.21 58.61-22.21ZM94.82 0L93.07-5.08 82.46-5.08 80.7 0 75.09 0 84.67-26.68 90.89-26.68 100.47 0 94.82 0ZM83.91-9.35L91.62-9.35 87.76-20.5 83.91-9.35ZM115.43 0.27Q111.69 0.27 108.56-1.49 105.43-3.24 103.6-6.35 101.76-9.47 101.76-13.4L101.76-13.4Q101.76-17.29 103.6-20.4 105.43-23.51 108.56-25.27 111.69-27.02 115.43-27.02L115.43-27.02Q119.21-27.02 122.32-25.27 125.43-23.51 127.24-20.4 129.05-17.29 129.05-13.4L129.05-13.4Q129.05-9.47 127.24-6.35 125.43-3.24 122.3-1.49 119.17 0.27 115.43 0.27L115.43 0.27ZM115.43-4.5Q117.83-4.5 119.66-5.59 121.5-6.68 122.53-8.7 123.56-10.73 123.56-13.4L123.56-13.4Q123.56-16.07 122.53-18.07 121.5-20.08 119.66-21.15 117.83-22.21 115.43-22.21L115.43-22.21Q113.02-22.21 111.17-21.15 109.32-20.08 108.29-18.07 107.26-16.07 107.26-13.4L107.26-13.4Q107.26-10.73 108.29-8.7 109.32-6.68 111.17-5.59 113.02-4.5 115.43-4.5L115.43-4.5ZM153.82 0L147.06 0 137.37-11.87 137.37 0 132.02 0 132.02-26.64 137.37-26.64 137.37-14.69 147.06-26.64 153.51-26.64 142.52-13.44 153.82 0ZM171.79-22.33L161.67-22.33 161.67-15.65 170.64-15.65 170.64-11.41 161.67-11.41 161.67-4.35 171.79-4.35 171.79 0 156.33 0 156.33-26.68 171.79-26.68 171.79-22.33Z" transform="translate(-2.630000114440918, 27.020000457763672)"></path></g></g></g></g>
<g fill-rule="" fill="#ffdf6b" transform="translate(5,111.788818359375)"><rect x="0" height="1" y="5.9832000732421875" width="14.278396606445312"></rect><rect height="1" y="5.9832000732421875" width="14.278396606445312" x="218.985595703125"></rect><g transform="translate(17.278396606445312,0)"><g transform="scale(1.2800000000000002)"><path d="M10.21-8.38L12.02-8.38L9.68 0L7.70 0L6.13-5.96L4.49 0L2.52 0.01L0.26-8.38L2.06-8.38L3.54-1.87L5.24-8.38L7.12-8.38L8.72-1.91L10.21-8.38ZM18.38-8.38L20.06-8.38L20.06 0L18.38 0L18.38-3.56L14.80-3.56L14.80 0L13.12 0L13.12-8.38L14.80-8.38L14.80-4.93L18.38-4.93L18.38-8.38ZM26.58-7.02L23.40-7.02L23.40-4.92L26.22-4.92L26.22-3.59L23.40-3.59L23.40-1.37L26.58-1.37L26.58 0L21.72 0L21.72-8.39L26.58-8.39L26.58-7.02ZM34.37 0L32.42 0L30.58-3.26L29.78-3.26L29.78 0L28.10 0L28.10-8.38L31.25-8.38Q32.22-8.38 32.90-8.03Q33.59-7.69 33.93-7.11Q34.27-6.53 34.27-5.81L34.27-5.81Q34.27-4.98 33.79-4.31Q33.31-3.65 32.36-3.40L32.36-3.40L34.37 0ZM29.78-6.98L29.78-4.52L31.19-4.52Q31.87-4.52 32.21-4.85Q32.54-5.18 32.54-5.77L32.54-5.77Q32.54-6.35 32.21-6.67Q31.87-6.98 31.19-6.98L31.19-6.98L29.78-6.98ZM40.66-7.02L37.48-7.02L37.48-4.92L40.30-4.92L40.30-3.59L37.48-3.59L37.48-1.37L40.66-1.37L40.66 0L35.80 0L35.80-8.39L40.66-8.39L40.66-7.02ZM47.92-8.38L49.70-8.38L46.63 0L44.59 0L41.52-8.38L43.32-8.38L45.62-1.72L47.92-8.38ZM55.57-7.02L52.39-7.02L52.39-4.92L55.21-4.92L55.21-3.59L52.39-3.59L52.39-1.37L55.57-1.37L55.57 0L50.71 0L50.71-8.39L55.57-8.39L55.57-7.02ZM63.36 0L61.42 0L59.57-3.26L58.78-3.26L58.78 0L57.10 0L57.10-8.38L60.24-8.38Q61.21-8.38 61.90-8.03Q62.58-7.69 62.92-7.11Q63.26-6.53 63.26-5.81L63.26-5.81Q63.26-4.98 62.78-4.31Q62.30-3.65 61.36-3.40L61.36-3.40L63.36 0ZM58.78-6.98L58.78-4.52L60.18-4.52Q60.86-4.52 61.20-4.85Q61.54-5.18 61.54-5.77L61.54-5.77Q61.54-6.35 61.20-6.67Q60.86-6.98 60.18-6.98L60.18-6.98L58.78-6.98ZM72.43-8.38L74.30-8.38L71.47-2.92L71.47 0L69.79 0L69.79-2.92L66.95-8.38L68.84-8.38L70.64-4.55L72.43-8.38ZM79.16 0.08Q77.99 0.08 77.00-0.47Q76.02-1.02 75.44-2.00Q74.87-2.98 74.87-4.21L74.87-4.21Q74.87-5.44 75.44-6.41Q76.02-7.39 77.00-7.94Q77.99-8.50 79.16-8.50L79.16-8.50Q80.35-8.50 81.33-7.94Q82.31-7.39 82.88-6.41Q83.45-5.44 83.45-4.21L83.45-4.21Q83.45-2.98 82.88-2.00Q82.31-1.02 81.32-0.47Q80.34 0.08 79.16 0.08L79.16 0.08ZM79.16-1.42Q79.92-1.42 80.50-1.76Q81.07-2.10 81.40-2.74Q81.72-3.37 81.72-4.21L81.72-4.21Q81.72-5.05 81.40-5.68Q81.07-6.31 80.50-6.65Q79.92-6.98 79.16-6.98L79.16-6.98Q78.41-6.98 77.83-6.65Q77.24-6.31 76.92-5.68Q76.60-5.05 76.60-4.21L76.60-4.21Q76.60-3.37 76.92-2.74Q77.24-2.10 77.83-1.76Q78.41-1.42 79.16-1.42L79.16-1.42ZM84.67-8.38L86.35-8.38L86.35-3.19Q86.35-2.34 86.80-1.89Q87.24-1.44 88.04-1.44L88.04-1.44Q88.86-1.44 89.30-1.89Q89.75-2.34 89.75-3.19L89.75-3.19L89.75-8.38L91.44-8.38L91.44-3.20Q91.44-2.14 90.98-1.40Q90.52-0.66 89.74-0.29Q88.97 0.08 88.02 0.08L88.02 0.08Q87.08 0.08 86.32-0.29Q85.56-0.66 85.12-1.40Q84.67-2.14 84.67-3.20L84.67-3.20L84.67-8.38ZM101.60 0L101.05-1.60L97.72-1.60L97.16 0L95.40 0L98.41-8.39L100.37-8.39L103.38 0L101.60 0ZM98.17-2.94L100.60-2.94L99.38-6.44L98.17-2.94ZM110.77 0L108.83 0L106.98-3.26L106.19-3.26L106.19 0L104.51 0L104.51-8.38L107.65-8.38Q108.62-8.38 109.31-8.03Q109.99-7.69 110.33-7.11Q110.68-6.53 110.68-5.81L110.68-5.81Q110.68-4.98 110.20-4.31Q109.72-3.65 108.77-3.40L108.77-3.40L110.77 0ZM106.19-6.98L106.19-4.52L107.59-4.52Q108.28-4.52 108.61-4.85Q108.95-5.18 108.95-5.77L108.95-5.77Q108.95-6.35 108.61-6.67Q108.28-6.98 107.59-6.98L107.59-6.98L106.19-6.98ZM117.06-7.02L113.88-7.02L113.88-4.92L116.70-4.92L116.70-3.59L113.88-3.59L113.88-1.37L117.06-1.37L117.06 0L112.20 0L112.20-8.39L117.06-8.39L117.06-7.02ZM118.72-1.76L120.42-1.76L119.02 1.61L117.94 1.61L118.72-1.76ZM127.38 0.08Q126.50 0.08 125.80-0.22Q125.10-0.52 124.69-1.08Q124.28-1.64 124.27-2.41L124.27-2.41L126.07-2.41Q126.11-1.90 126.44-1.60Q126.77-1.30 127.34-1.30L127.34-1.30Q127.93-1.30 128.27-1.58Q128.60-1.86 128.60-2.32L128.60-2.32Q128.60-2.69 128.38-2.93Q128.15-3.17 127.81-3.31Q127.46-3.44 126.86-3.61L126.86-3.61Q126.05-3.85 125.54-4.09Q125.03-4.32 124.66-4.79Q124.30-5.27 124.30-6.06L124.30-6.06Q124.30-6.80 124.67-7.36Q125.04-7.91 125.71-8.20Q126.38-8.50 127.25-8.50L127.25-8.50Q128.54-8.50 129.35-7.87Q130.16-7.24 130.25-6.11L130.25-6.11L128.40-6.11Q128.38-6.54 128.03-6.82Q127.69-7.10 127.13-7.10L127.13-7.10Q126.64-7.10 126.34-6.85Q126.05-6.60 126.05-6.12L126.05-6.12Q126.05-5.78 126.27-5.56Q126.49-5.34 126.82-5.20Q127.15-5.06 127.75-4.88L127.75-4.88Q128.57-4.64 129.08-4.40Q129.60-4.16 129.97-3.68Q130.34-3.20 130.34-2.42L130.34-2.42Q130.34-1.75 130.00-1.18Q129.65-0.60 128.98-0.26Q128.30 0.08 127.38 0.08L127.38 0.08ZM131.80-8.38L133.48-8.38L133.48 0L131.80 0L131.80-8.38ZM142.30-8.39L142.30 0L140.62 0L136.81-5.75L136.81 0L135.13 0L135.13-8.39L136.81-8.39L140.62-2.63L140.62-8.39L142.30-8.39ZM151.72-5.86L149.78-5.86Q149.50-6.38 148.99-6.66Q148.49-6.94 147.82-6.94L147.82-6.94Q147.07-6.94 146.50-6.60Q145.92-6.26 145.60-5.64Q145.27-5.02 145.27-4.20L145.27-4.20Q145.27-3.36 145.60Line truncated
</svg>
</svg>
</div>
<!-- Headline -->
<div class="headline">
<div class="headline-main">MAKE YOUR OWN</div>
<div class="headline-sub">KARAOKE VIDEOS</div>
</div>
<!-- Subtitle -->
<div class="subtitle">
Turn any song into a professional karaoke video with synced lyrics, vocal removal, and automatic YouTube publishing.
</div>
<!-- How it works -->
<div class="steps">
<div class="step">
<div class="step-number">1</div>
<div class="step-content">
<div class="step-title">Pick any song</div>
<div class="step-desc">Search by artist &amp; title or paste a YouTube link</div>
</div>
</div>
<div class="step">
<div class="step-number">2</div>
<div class="step-content">
<div class="step-title">Our system does the work</div>
<div class="step-desc">Vocals removed, lyrics synced, video rendered automatically</div>
</div>
</div>
<div class="step">
<div class="step-number">3</div>
<div class="step-content">
<div class="step-title">Review &amp; correct the lyrics and instrumental</div>
<div class="step-desc">Fine-tune everything before publishing</div>
</div>
</div>
<div class="step">
<div class="step-number">4</div>
<div class="step-content">
<div class="step-title">Download or publish to YouTube</div>
<div class="step-desc">Get your finished karaoke video in minutes</div>
</div>
</div>
</div>
<div class="divider"></div>
<!-- CTA with QR code -->
<div class="cta-section">
<div class="qr-container">
<!-- Replace src with actual QR code image path -->
<img src="{{QR_DATA_URL}}" alt="QR Code - nomadkaraoke.com/r/{{REFERRAL_CODE_LOWER}}">
</div>
<div class="cta-text">
<div class="cta-label">First track free + {{DISCOUNT_PERCENT}}% off with this link</div>
<div class="cta-url">NOMADKARAOKE.COM/R/<span class="referral-code">{{REFERRAL_CODE}}</span></div>
<div class="cta-note">Scan the QR code or visit the link above</div>
</div>
</div>
<!-- Bottom -->
<div class="bottom">
<div class="bottom-features">
<div class="bottom-feature">
<span class="bottom-feature-icon">&#127908;</span>
<span>Any Song</span>
</div>
<div class="bottom-feature">
<span class="bottom-feature-icon">&#9889;</span>
<span>Automatic</span>
</div>
<div class="bottom-feature">
<span class="bottom-feature-icon">&#127916;</span>
<span>Pro Quality</span>
</div>
</div>
<div class="bottom-tagline">Wherever you are, sing!</div>
</div>
</div>
</body>
</html>
+2 -2
View File
@@ -282,7 +282,7 @@ class TestSubmitFeedbackEmailIntegration:
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)
submit_user_feedback(http_request=MagicMock(headers={"accept-language": "en"}), request=request, authorization="Bearer test-token", user_service=mock_user_svc)
)
# Verify email notification was called with matching args
@@ -339,7 +339,7 @@ class TestSubmitFeedbackEmailIntegration:
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)
submit_user_feedback(http_request=MagicMock(headers={"accept-language": "en"}), request=request, authorization="Bearer test-token", user_service=mock_user_svc)
)
# User still gets credits even though email failed
+97
View File
@@ -130,6 +130,36 @@ class TestGrantWelcomeCredits:
assert update_args['credits'] == 1
assert update_args['welcome_credits_granted'] is True
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_uses_precomputed_eval_when_provided(self, mock_fs, mock_settings):
"""grant_welcome_credits_if_eligible uses pre-computed eval and skips AI call."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
user = User(email="new@example.com", credits=0, credit_transactions=[])
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = user.model_dump(mode='json')
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
from backend.services.user_service import UserService
service = UserService()
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval:
granted, status = service.grant_welcome_credits_if_eligible(
"new@example.com",
precomputed_eval={
"credit_eval_decision": "grant",
"credit_eval_reasoning": "Pre-computed: clean user",
},
)
# AI evaluation should NOT have been called
mock_eval.return_value.evaluate.assert_not_called()
assert granted is True
assert status == "granted"
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_skips_if_flag_already_set(self, mock_fs, mock_settings):
@@ -206,6 +236,30 @@ class TestGrantWelcomeCredits:
assert granted is False
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_skips_evaluation_for_test_emails(self, mock_fs, mock_settings):
"""grant_welcome_credits_if_eligible skips AI evaluation for @inbox.testmail.app emails."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
user = User(email="e2e.test@inbox.testmail.app", credits=0, credit_transactions=[])
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = user.model_dump(mode='json')
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
from backend.services.user_service import UserService
service = UserService()
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval:
granted, status = service.grant_welcome_credits_if_eligible("e2e.test@inbox.testmail.app")
# AI evaluation should NOT have been called
mock_eval.return_value.evaluate.assert_not_called()
assert granted is True
assert status == "granted"
# =============================================================================
# Phase 2: Per-IP Signup Rate Limiting
@@ -565,6 +619,49 @@ class TestVerifyGrantsCredits:
from backend.main import app
app.dependency_overrides.clear()
def test_verify_passes_precomputed_eval(self, mock_user_svc):
"""Verify endpoint passes pre-computed eval from magic link doc."""
user = User(email="new@example.com", credits=2, email_verified=True)
client = self._make_verify_client(mock_user_svc, user, credits_eligible=True)
# Add pre-computed eval to the magic link doc
mock_ml_doc = mock_user_svc.db.collection.return_value.document.return_value.get.return_value
mock_ml_doc.to_dict.return_value = {
'email': user.email,
'tenant_id': None,
'credit_eval_decision': 'grant',
'credit_eval_reasoning': 'Clean user',
}
try:
response = client.get("/api/users/auth/verify?token=valid-token")
assert response.status_code == 200
# Verify precomputed_eval was passed through
call_kwargs = mock_user_svc.grant_welcome_credits_if_eligible.call_args
assert call_kwargs[1]['precomputed_eval'] == {
'credit_eval_decision': 'grant',
'credit_eval_reasoning': 'Clean user',
}
finally:
from backend.main import app
app.dependency_overrides.clear()
def test_verify_falls_back_without_precomputed_eval(self, mock_user_svc):
"""Verify endpoint passes None when no pre-computed eval exists."""
user = User(email="new@example.com", credits=2, email_verified=True)
client = self._make_verify_client(mock_user_svc, user, credits_eligible=True)
try:
response = client.get("/api/users/auth/verify?token=valid-token")
assert response.status_code == 200
call_kwargs = mock_user_svc.grant_welcome_credits_if_eligible.call_args
assert call_kwargs[1]['precomputed_eval'] is None
finally:
from backend.main import app
app.dependency_overrides.clear()
def test_verify_returns_zero_credits_for_returning_user(self, mock_user_svc):
"""Returning user gets credits_granted=0."""
user = User(
+150
View File
@@ -0,0 +1,150 @@
"""
Tests for Google OIDC token validation in AuthService.
Cloud Scheduler and Cloud Tasks send OIDC JWTs signed by Google.
The auth service must validate these and grant admin access for
requests from the configured service account.
"""
import pytest
from unittest.mock import patch, MagicMock
from backend.services.auth_service import AuthService, AuthResult, UserType
@pytest.fixture
def auth_service():
"""Create an AuthService instance with mocked Firestore."""
with patch("backend.services.auth_service.FirestoreService"):
service = AuthService()
service._scheduler_service_account = "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com"
return service
# A fake JWT-shaped token (3 dot-separated parts)
FAKE_JWT = "eyJhbGciOiJSUzI1NiJ9.eyJlbWFpbCI6InRlc3RAZXhhbXBsZS5jb20ifQ.signature"
class TestOidcTokenValidation:
"""Tests for _validate_oidc_token."""
def test_non_jwt_returns_none(self, auth_service):
"""Non-JWT tokens (no dots) should return None immediately."""
result = auth_service._validate_oidc_token("simple-token-no-dots")
assert result is None
def test_two_dots_not_three_parts_returns_none(self, auth_service):
"""Tokens with wrong number of dots should return None."""
result = auth_service._validate_oidc_token("only.one.dot-but-not-jwt")
# This has 2 dots = 3 parts, so it will attempt OIDC validation
# but fail signature verification. That's fine — it returns None.
# A token with 1 dot should be skipped entirely.
result_one_dot = auth_service._validate_oidc_token("one.dot")
assert result_one_dot is None
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
def test_valid_oidc_from_allowed_sa(self, mock_verify, auth_service):
"""Valid OIDC token from the configured service account grants admin."""
mock_verify.return_value = {
"email": "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com",
"email_verified": True,
"iss": "https://accounts.google.com",
"aud": "https://api.nomadkaraoke.com/api/internal/process-stale-reviews",
}
result = auth_service._validate_oidc_token(FAKE_JWT)
assert result is not None
assert result.is_valid is True
assert result.is_admin is True
assert result.user_type == UserType.ADMIN
assert result.remaining_uses == -1
assert result.user_email == "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com"
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
def test_oidc_from_wrong_sa_returns_none(self, mock_verify, auth_service):
"""OIDC token from a different service account is rejected."""
mock_verify.return_value = {
"email": "attacker@evil-project.iam.gserviceaccount.com",
"email_verified": True,
"iss": "https://accounts.google.com",
}
result = auth_service._validate_oidc_token(FAKE_JWT)
assert result is None
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
def test_expired_oidc_token_returns_none(self, mock_verify, auth_service):
"""Expired OIDC token raises ValueError and returns None."""
mock_verify.side_effect = ValueError("Token expired")
result = auth_service._validate_oidc_token(FAKE_JWT)
assert result is None
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
def test_invalid_signature_returns_none(self, mock_verify, auth_service):
"""Token with invalid signature raises ValueError and returns None."""
mock_verify.side_effect = ValueError("Could not verify token signature")
result = auth_service._validate_oidc_token(FAKE_JWT)
assert result is None
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
def test_network_error_returns_none(self, mock_verify, auth_service):
"""Network error fetching Google certs returns None gracefully."""
mock_verify.side_effect = Exception("Connection timeout")
result = auth_service._validate_oidc_token(FAKE_JWT)
assert result is None
class TestValidateTokenFullOidc:
"""Tests that OIDC validation is properly integrated into validate_token_full."""
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
def test_oidc_token_grants_admin_via_validate_token_full(self, mock_verify, auth_service):
"""OIDC token flows through validate_token_full and grants admin."""
mock_verify.return_value = {
"email": "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com",
"email_verified": True,
}
# Mock Firestore to not interfere
auth_service.firestore.get_token = MagicMock(return_value=None)
result = auth_service.validate_token_full(FAKE_JWT)
assert result.is_valid is True
assert result.is_admin is True
assert result.user_type == UserType.ADMIN
def test_admin_token_still_works(self, auth_service):
"""Admin tokens from env var still take priority over OIDC."""
auth_service.admin_tokens = ["test-admin-token"]
result = auth_service.validate_token_full("test-admin-token")
assert result.is_valid is True
assert result.is_admin is True
assert result.message == "Admin access granted"
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
def test_failed_oidc_falls_through_to_firestore(self, mock_verify, auth_service):
"""If OIDC validation fails, token is still checked against Firestore."""
mock_verify.side_effect = ValueError("Invalid token")
# Firestore has a valid token
auth_service.firestore.get_token = MagicMock(return_value={
"type": "unlimited",
"active": True,
"max_uses": -1,
"user_email": "user@example.com",
})
result = auth_service.validate_token_full(FAKE_JWT)
assert result.is_valid is True
assert result.user_type == UserType.UNLIMITED
@@ -319,3 +319,59 @@ class TestRenderVideoWorkerUsesCorrectedData:
# Metadata and original_segments preserved
assert original_data['metadata']['preserved'] is True
assert original_data['original_segments'][0]['id'] == 1
class TestCompleteReviewSkipsEmptyCorrections:
"""Test that complete_review doesn't write corrections_updated.json when no corrections.
Bug scenario: Completing review via admin API without corrections payload writes
an empty {} to corrections_updated.json. Downstream render workers then get
KeyError: 'corrections' when processing it.
"""
def test_no_corrections_key_skips_upload(self):
"""When updated_data has only instrumental_selection, no corrections file is written."""
# Simulate what the endpoint does with the corrections_to_save logic
updated_data = {"instrumental_selection": "clean"}
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
# This is the guard we added
should_write = corrections_to_save and "corrections" in corrections_to_save
assert not should_write, "Should not write corrections_updated.json for empty payload"
def test_with_corrections_key_allows_upload(self):
"""When updated_data has corrections, the file should be written."""
updated_data = {
"corrections": [{"id": 1, "type": "edit"}],
"corrected_segments": [{"id": 1, "text": "fixed"}],
"instrumental_selection": "with_backing",
}
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
should_write = corrections_to_save and "corrections" in corrections_to_save
assert should_write, "Should write corrections_updated.json when corrections present"
def test_empty_dict_payload_skips_upload(self):
"""When updated_data is effectively empty after removing instrumental_selection."""
updated_data = {"instrumental_selection": "clean", "some_other_key": "value"}
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
# Has content but no "corrections" key
should_write = corrections_to_save and "corrections" in corrections_to_save
assert not should_write, "Should not write without corrections key"
def test_render_worker_handles_empty_corrections_gracefully(self):
"""Document that render workers skip empty corrections_updated.json.
Both GCE and Cloud Run workers now check for 'corrections' key
before passing to CorrectionOperations.update_correction_result_with_data().
"""
# Simulates what the workers do on download
empty_updated_data = {}
has_valid_corrections = empty_updated_data and "corrections" in empty_updated_data
assert not has_valid_corrections, "Empty dict should not be treated as valid corrections"
# Dict with irrelevant keys
bad_updated_data = {"some_key": "value"}
has_valid_corrections = bad_updated_data and "corrections" in bad_updated_data
assert not has_valid_corrections, "Dict without corrections key should not be valid"
@@ -24,6 +24,15 @@ def complete_job():
user_email="user@example.com",
dropbox_path="/Karaoke/Organized",
edit_count=0,
file_urls={
"screens": {
"title_png": "jobs/test-edit-123/screens/title.png",
"title_jpg": "jobs/test-edit-123/screens/title.jpg",
"end_png": "jobs/test-edit-123/screens/end.png",
"end_jpg": "jobs/test-edit-123/screens/end.jpg",
},
"videos": {"with_vocals": "jobs/test-edit-123/videos/with_vocals.mkv"},
},
state_data={
"youtube_url": "https://youtu.be/abc123",
"brand_code": "NOMAD-1234",
@@ -196,6 +205,48 @@ class TestEditWithMetadataUpdate:
)
mock_worker_service.trigger_screens_worker.assert_called_once_with("test-edit-123")
def test_edit_with_metadata_transitions_to_lyrics_complete(self, client, mock_job_manager, auth_headers):
"""Metadata change transitions to LYRICS_COMPLETE so screens worker can run.
Bug fix: previously transitioned to AWAITING_REVIEW, which made the screens
worker fail (AWAITING_REVIEW → GENERATING_SCREENS is not a valid transition).
"""
client.post(
"/api/jobs/test-edit-123/edit",
headers=auth_headers,
json={"artist": "New Artist"},
)
mock_job_manager.transition_to_state.assert_called_once_with(
"test-edit-123",
JobStatus.LYRICS_COMPLETE,
progress=55,
message="Regenerating screens with updated metadata",
)
def test_edit_with_metadata_clears_file_urls_screens(self, client, mock_job_manager, auth_headers):
"""Metadata change clears stale file_urls.screens entries.
Bug fix: stale screen URLs caused retry to skip screen generation,
resulting in 404 when video worker tried to download deleted screens.
"""
response = client.post(
"/api/jobs/test-edit-123/edit",
headers=auth_headers,
json={"title": "New Title"},
)
assert response.status_code == 200
# The Firestore job_ref.update() is called via the mocked FirestoreService.
# Verify the update_payload included screen URL deletions by checking
# the transition went to LYRICS_COMPLETE (which only happens when
# metadata_updated=True, the same branch that clears screens).
mock_job_manager.transition_to_state.assert_called_once_with(
"test-edit-123",
JobStatus.LYRICS_COMPLETE,
progress=55,
message="Regenerating screens with updated metadata",
)
class TestEditValidation:
"""Tests for validation and error cases."""
+3 -3
View File
@@ -59,8 +59,8 @@ class TestSendReviewReminder:
job_id="abc123",
)
call_args = service.provider.send_email.call_args
assert "gen.nomadkaraoke.com/app/jobs#/abc123/review" in call_args.kwargs["html_content"]
assert "gen.nomadkaraoke.com/app/jobs#/abc123/review" in call_args.kwargs["text_content"]
assert "gen.nomadkaraoke.com/en/app/jobs#/abc123/review" in call_args.kwargs["html_content"]
assert "gen.nomadkaraoke.com/en/app/jobs#/abc123/review" in call_args.kwargs["text_content"]
def test_content_includes_expiry_warning(self):
"""Content should warn about 24h expiry."""
@@ -153,4 +153,4 @@ class TestSendReviewExpired:
credits_balance=2,
)
call_args = service.provider.send_email.call_args
assert "gen.nomadkaraoke.com/app" in call_args.kwargs["html_content"]
assert "gen.nomadkaraoke.com/en/app" in call_args.kwargs["html_content"]
@@ -542,6 +542,41 @@ class TestExternalAPIChecks:
# No HTTP calls should have been made
mock_client.return_value.get.assert_not_called()
# =========================================================================
# Allowlisted domain bypass (Tier 1.5)
# =========================================================================
def test_allowlisted_domain_skips_external_api_checks(self, mock_db):
"""Allowlisted domains should skip external API checks entirely.
Regression test: inbox.testmail.app was getting flagged by DeBounce
even though it was in the allowlist, because external API calls ran
after the static blocklist check but before checking the allowlist.
"""
from backend.services.email_validation_service import EmailValidationService
mock_doc = Mock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"external_domains": ["yopmail.com"],
"manual_domains": ["inbox.testmail.app"], # auto-learned by DeBounce
"allowlisted_domains": ["inbox.testmail.app"], # but also allowlisted
"blocked_emails": [],
"blocked_ips": [],
"verified_clean_domains": {},
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
EmailValidationService._blocklist_cache = None
EmailValidationService._blocklist_cache_time = None
service = EmailValidationService(db=mock_db)
with patch(
"backend.services.email_validation_service._get_http_client"
) as mock_client:
result = service.is_disposable_domain("user@inbox.testmail.app")
assert result is False
# No HTTP calls should have been made — allowlist bypasses external APIs
mock_client.return_value.get.assert_not_called()
# =========================================================================
# DeBounce API
# =========================================================================
+31
View File
@@ -239,6 +239,37 @@ class TestRequestWithRetry:
await encoding_service.submit_encoding_job("j1", "gs://in", "gs://out", {})
class TestWarmupFallback:
"""Tests for _warmup_encoding_worker_fallback() in the retry loop."""
def test_warmup_fallback_called_on_first_connection_failure(self, encoding_service):
"""Warmup fallback is called when the first connection attempt fails."""
mock_manager = MagicMock()
mock_manager.ensure_primary_running.return_value = {
"started": True, "vm_name": "encoding-worker-b", "primary_url": "http://1.2.3.4:8080"
}
encoding_service._worker_manager = mock_manager
encoding_service._warmup_encoding_worker_fallback("test-job")
mock_manager.ensure_primary_running.assert_called_once()
def test_warmup_fallback_noop_without_worker_manager(self, encoding_service):
"""Warmup fallback is a no-op when worker_manager is not set (dev mode)."""
encoding_service._worker_manager = None
# Should not raise
encoding_service._warmup_encoding_worker_fallback("test-job")
def test_warmup_fallback_swallows_exceptions(self, encoding_service):
"""Warmup fallback never raises — failures are logged but non-fatal."""
mock_manager = MagicMock()
mock_manager.ensure_primary_running.side_effect = Exception("Compute API down")
encoding_service._worker_manager = mock_manager
# Should not raise
encoding_service._warmup_encoding_worker_fallback("test-job")
class TestWaitForCompletionPollTolerance:
"""Tests for wait_for_completion() transient failure tolerance."""
+97
View File
@@ -0,0 +1,97 @@
"""Tests for flyer PDF generation service."""
import os
from unittest.mock import patch, MagicMock
import pytest
from backend.services.flyer_service import FlyerService, FlyerError
class TestFlyerService:
"""Tests for FlyerService."""
def setup_method(self):
self.service = FlyerService()
def test_render_template_light_substitutes_placeholders(self):
html = self.service._render_template(
theme="light",
referral_code="MYCODE",
discount_percent=15,
qr_data_url="data:image/png;base64,abc123",
)
assert "MYCODE" in html
assert "{{REFERRAL_CODE}}" not in html
assert "{{QR_DATA_URL}}" not in html
assert "{{DISCOUNT_PERCENT}}" not in html
assert "{{REFERRAL_CODE_LOWER}}" not in html
assert "15% off" in html
assert "data:image/png;base64,abc123" in html
assert "mycode" in html # lowercase version in alt text
def test_render_template_dark_substitutes_placeholders(self):
html = self.service._render_template(
theme="dark",
referral_code="DARKCODE",
discount_percent=20,
qr_data_url="data:image/png;base64,xyz789",
)
assert "DARKCODE" in html
assert "{{REFERRAL_CODE}}" not in html
assert "data:image/png;base64,xyz789" in html
assert "20% off" in html
def test_render_template_invalid_theme_raises(self):
with pytest.raises(FlyerError, match="Invalid theme"):
self.service._render_template(
theme="neon",
referral_code="CODE",
discount_percent=10,
qr_data_url="data:image/png;base64,abc",
)
def test_render_template_uppercases_referral_code(self):
html = self.service._render_template(
theme="light",
referral_code="mycode",
discount_percent=10,
qr_data_url="data:image/png;base64,abc",
)
assert '<span class="referral-code">MYCODE</span>' in html
@patch("backend.services.flyer_service.subprocess.run")
def test_generate_pdf_calls_chromium_with_correct_flags(self, mock_run):
mock_run.return_value = MagicMock(returncode=0)
self.service._chromium_path = "/usr/bin/chromium"
with patch.object(self.service, "_render_template", return_value="<html>test</html>"):
with patch("os.path.exists", return_value=True):
with patch("builtins.open", MagicMock(return_value=MagicMock(read=MagicMock(return_value=b"%PDF")))):
with patch("os.unlink"):
self.service.generate_pdf(
theme="light",
referral_code="TEST",
discount_percent=10,
qr_data_url="data:image/png;base64,abc",
)
call_args = mock_run.call_args[0][0]
assert "--headless" in call_args
assert "--no-margins" in call_args
assert "--print-background" in call_args
assert "--no-pdf-header-footer" in call_args
assert "--virtual-time-budget=5000" in call_args
assert "--paper-width=8.5" in call_args
assert "--paper-height=11" in call_args
def test_validate_qr_data_url_rejects_non_data_url(self):
with pytest.raises(FlyerError, match="Invalid QR"):
self.service._validate_qr_data_url("https://evil.com/qr.png")
def test_validate_qr_data_url_rejects_too_large(self):
huge_url = "data:image/png;base64," + "A" * 600_000
with pytest.raises(FlyerError, match="too large"):
self.service._validate_qr_data_url(huge_url)
def test_validate_qr_data_url_accepts_valid(self):
self.service._validate_qr_data_url("data:image/png;base64,abc123")
+117
View File
@@ -0,0 +1,117 @@
"""Tests for backend.i18n translation utility."""
import pytest
from unittest.mock import MagicMock
from backend.i18n import t, get_locale_from_request, get_locale_prefix, SUPPORTED_LOCALES, DEFAULT_LOCALE, _load_translations
class TestTranslationFunction:
"""Tests for t() function."""
def test_returns_english_string(self):
result = t("en", "jobs.notFound")
assert result == "Job not found"
def test_dotted_key_path(self):
result = t("en", "pushNotifications.reviewLyricsTitle")
assert result == "Review Lyrics"
def test_interpolation(self):
result = t("en", "jobs.notCompleted", status="downloading")
assert result == "Only completed jobs can be edited. Current status: downloading"
def test_multiple_interpolation_vars(self):
result = t("en", "jobs.durationMismatch", upload_duration="120", original_duration="180")
assert "120s" in result
assert "180s" in result
def test_spanish_returns_translated_string(self):
result = t("es", "jobs.notFound")
assert result == "Trabajo no encontrado"
def test_fallback_to_english_for_missing_key_in_other_locale(self):
# Key that exists in en.json but not in es.json should fall back to English
result = t("es", "nonexistent.key.path")
assert result == "nonexistent.key.path" # Falls all the way to key itself
def test_returns_key_for_nonexistent_key(self):
result = t("en", "nonexistent.key.path")
assert result == "nonexistent.key.path"
def test_unsupported_locale_falls_back_to_english(self):
result = t("fr", "jobs.notFound")
assert result == "Job not found"
def test_empty_locale_falls_back_to_english(self):
result = t("", "jobs.notFound")
assert result == "Job not found"
def test_missing_interpolation_var_returns_template(self):
# If kwargs are missing, return template string as-is
result = t("en", "jobs.notCompleted")
assert "{status}" in result
def test_all_supported_locales_load(self):
for locale in SUPPORTED_LOCALES:
translations = _load_translations(locale)
assert isinstance(translations, dict)
assert len(translations) > 0
class TestGetLocaleFromRequest:
"""Tests for get_locale_from_request()."""
def _make_request(self, accept_language: str = "") -> MagicMock:
request = MagicMock()
request.headers = {"accept-language": accept_language}
return request
def test_simple_locale(self):
request = self._make_request("de")
assert get_locale_from_request(request) == "de"
def test_locale_with_region(self):
request = self._make_request("es-MX")
assert get_locale_from_request(request) == "es"
def test_quality_weighted_list(self):
request = self._make_request("fr;q=0.9,de;q=0.8,en;q=0.7")
# fr is not supported, de is next
assert get_locale_from_request(request) == "de"
def test_complex_accept_language(self):
request = self._make_request("en-US,en;q=0.9,de;q=0.8")
assert get_locale_from_request(request) == "en"
def test_unsupported_locale_returns_default(self):
request = self._make_request("ja")
assert get_locale_from_request(request) == DEFAULT_LOCALE
def test_empty_header_returns_default(self):
request = self._make_request("")
assert get_locale_from_request(request) == DEFAULT_LOCALE
def test_missing_header_returns_default(self):
request = MagicMock()
request.headers = {}
assert get_locale_from_request(request) == DEFAULT_LOCALE
class TestGetLocalePrefix:
"""Tests for get_locale_prefix()."""
def test_english(self):
assert get_locale_prefix("en") == "/en"
def test_spanish(self):
assert get_locale_prefix("es") == "/es"
def test_german(self):
assert get_locale_prefix("de") == "/de"
def test_unsupported_returns_english(self):
assert get_locale_prefix("fr") == "/en"
def test_empty_returns_english(self):
assert get_locale_prefix("") == "/en"
+7
View File
@@ -285,6 +285,13 @@ class TestValidateWorkerCanRun:
assert error is not None
assert "video_worker called but job status is pending" in error
def test_video_worker_invalid_with_generating_video_status(self):
"""Test video worker rejects GENERATING_VIDEO to prevent concurrent worker races."""
job = create_test_job(status=JobStatus.GENERATING_VIDEO)
error = validate_worker_can_run("video_worker", job)
assert error is not None
assert "video_worker called but job status is generating_video" in error
def test_render_video_worker_valid_with_review_complete_status(self):
"""Test render video worker is valid with REVIEW_COMPLETE status."""
job = create_test_job(status=JobStatus.REVIEW_COMPLETE)
@@ -22,7 +22,7 @@ class TestURLBuilding:
url = service._build_review_url("job-123")
assert url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/review"
assert url == "https://gen.nomadkaraoke.com/en/app/jobs#/job-123/review"
def test_build_review_url_ignores_legacy_params(self):
"""Test review URL ignores legacy audio_hash and review_token params."""
@@ -33,7 +33,7 @@ class TestURLBuilding:
url = service._build_review_url("job-123", audio_hash="abc123", review_token="token456")
# URL should be the simple consolidated route
assert url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/review"
assert url == "https://gen.nomadkaraoke.com/en/app/jobs#/job-123/review"
# No query params
assert "?" not in url
@@ -45,7 +45,7 @@ class TestURLBuilding:
# Note: job IDs with slashes would be unusual in real usage
url = service._build_review_url("abc-def-123")
assert url == "https://gen.nomadkaraoke.com/app/jobs#/abc-def-123/review"
assert url == "https://gen.nomadkaraoke.com/en/app/jobs#/abc-def-123/review"
def test_build_instrumental_url_basic(self):
"""Test basic instrumental URL building."""
@@ -54,7 +54,7 @@ class TestURLBuilding:
url = service._build_instrumental_url("job-123")
assert url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/instrumental"
assert url == "https://gen.nomadkaraoke.com/en/app/jobs#/job-123/instrumental"
def test_build_instrumental_url_ignores_legacy_params(self):
"""Test instrumental URL ignores legacy instrumental_token param."""
@@ -65,7 +65,7 @@ class TestURLBuilding:
url = service._build_instrumental_url("job-123", instrumental_token="inst-token")
# URL should be the simple consolidated route
assert url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/instrumental"
assert url == "https://gen.nomadkaraoke.com/en/app/jobs#/job-123/instrumental"
# No query params
assert "?" not in url
@@ -312,7 +312,7 @@ class TestActionReminderEmail:
# Verify the review URL was passed to template
call_kwargs = service.template_service.render_action_needed_lyrics.call_args.kwargs
review_url = call_kwargs.get('review_url')
assert review_url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/review"
assert review_url == "https://gen.nomadkaraoke.com/en/app/jobs#/job-123/review"
@pytest.mark.asyncio
async def test_send_instrumental_reminder_includes_url(self):
@@ -334,7 +334,7 @@ class TestActionReminderEmail:
# Verify the instrumental URL was passed to template
call_kwargs = service.template_service.render_action_needed_instrumental.call_args.kwargs
instrumental_url = call_kwargs.get('instrumental_url')
assert instrumental_url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/instrumental"
assert instrumental_url == "https://gen.nomadkaraoke.com/en/app/jobs#/job-123/instrumental"
class TestGetCompletionMessage:
+6 -2
View File
@@ -90,12 +90,16 @@ class TestExceptionHandlers:
credits_required=1,
)
response = await insufficient_credits_exception_handler(request=None, exc=exc)
from unittest.mock import MagicMock
mock_request = MagicMock()
mock_request.headers = {"accept-language": "en"}
response = await insufficient_credits_exception_handler(request=mock_request, exc=exc)
assert response.status_code == 402
import json
body = json.loads(response.body)
assert body["detail"] == "No credits remaining"
assert body["detail"] == "Insufficient credits for this operation"
assert body["credits_available"] == 0
assert body["credits_required"] == 1
assert body["buy_url"] == "/#pricing"
+291
View File
@@ -0,0 +1,291 @@
"""
Unit tests for referral system Pydantic models.
Tests validate:
- ReferralLinkStats defaults
- ReferralLink default and custom values
- ReferralEarning pending status default
- ReferralPayout creation with earnings list
- User model referral fields default to None
- UserPublic referral fields
- API request/response model shapes
"""
import pytest
from datetime import datetime, UTC
from pydantic import ValidationError
from backend.models.referral import (
ReferralLinkStats,
ReferralLink,
ReferralEarning,
ReferralPayout,
CreateReferralLinkRequest,
UpdateReferralLinkRequest,
ReferralLinkResponse,
ReferralEarningResponse,
ReferralPayoutResponse,
ReferralDashboardResponse,
ReferralInterstitialResponse,
)
from backend.models.user import User, UserPublic, UserRole
class TestReferralLinkStats:
"""Test ReferralLinkStats model defaults."""
def test_all_defaults_zero(self):
stats = ReferralLinkStats()
assert stats.clicks == 0
assert stats.signups == 0
assert stats.purchases == 0
assert stats.total_earned_cents == 0
def test_custom_values(self):
stats = ReferralLinkStats(clicks=10, signups=5, purchases=2, total_earned_cents=5000)
assert stats.clicks == 10
assert stats.signups == 5
assert stats.purchases == 2
assert stats.total_earned_cents == 5000
class TestReferralLink:
"""Test ReferralLink model defaults and custom values."""
def test_default_values(self):
link = ReferralLink(
code="abc123",
owner_email="user@example.com",
)
assert link.code == "abc123"
assert link.owner_email == "user@example.com"
assert link.discount_percent == 10
assert link.kickback_percent == 20
assert link.discount_duration_days == 30
assert link.earning_duration_days == 365
assert link.is_vanity is False
assert link.enabled is True
assert link.display_name is None
assert link.custom_message is None
assert link.stripe_coupon_id is None
# Stats should be all zeros
assert link.stats.clicks == 0
assert link.stats.signups == 0
assert link.stats.purchases == 0
assert link.stats.total_earned_cents == 0
def test_vanity_link_with_custom_values(self):
link = ReferralLink(
code="karaoke-king",
owner_email="king@example.com",
display_name="The Karaoke King",
custom_message="Sing with me!",
discount_percent=15,
kickback_percent=25,
discount_duration_days=60,
earning_duration_days=730,
is_vanity=True,
stripe_coupon_id="coupon_abc",
)
assert link.code == "karaoke-king"
assert link.display_name == "The Karaoke King"
assert link.custom_message == "Sing with me!"
assert link.discount_percent == 15
assert link.kickback_percent == 25
assert link.discount_duration_days == 60
assert link.earning_duration_days == 730
assert link.is_vanity is True
assert link.stripe_coupon_id == "coupon_abc"
def test_timestamps_set_automatically(self):
link = ReferralLink(code="test", owner_email="a@b.com")
assert isinstance(link.created_at, datetime)
assert isinstance(link.updated_at, datetime)
class TestReferralEarning:
"""Test ReferralEarning model."""
def test_pending_status_default(self):
earning = ReferralEarning(
id="earn_001",
referrer_email="referrer@example.com",
referred_email="newuser@example.com",
referral_code="abc123",
stripe_session_id="cs_test_123",
purchase_amount_cents=2999,
earning_amount_cents=600,
)
assert earning.status == "pending"
assert earning.paid_at is None
assert earning.payout_id is None
assert isinstance(earning.created_at, datetime)
def test_custom_status(self):
earning = ReferralEarning(
id="earn_002",
referrer_email="referrer@example.com",
referred_email="newuser@example.com",
referral_code="abc123",
stripe_session_id="cs_test_456",
purchase_amount_cents=2999,
earning_amount_cents=600,
status="paid",
)
assert earning.status == "paid"
class TestReferralPayout:
"""Test ReferralPayout model."""
def test_creation_with_earnings_list(self):
payout = ReferralPayout(
id="payout_001",
referrer_email="referrer@example.com",
stripe_transfer_id="tr_test_123",
amount_cents=1200,
earnings_included=["earn_001", "earn_002"],
)
assert payout.id == "payout_001"
assert payout.amount_cents == 1200
assert payout.earnings_included == ["earn_001", "earn_002"]
assert payout.status == "processing"
assert isinstance(payout.created_at, datetime)
def test_empty_earnings_list(self):
payout = ReferralPayout(
id="payout_002",
referrer_email="referrer@example.com",
stripe_transfer_id="tr_test_456",
amount_cents=0,
earnings_included=[],
)
assert payout.earnings_included == []
class TestUserReferralFields:
"""Test that User model has referral fields defaulting to None."""
def test_referral_fields_default_none(self):
user = User(email="test@example.com")
assert user.referral_code is None
assert user.referred_by_code is None
assert user.referred_at is None
assert user.referral_discount_expires_at is None
assert user.stripe_connect_account_id is None
def test_referral_fields_set(self):
now = datetime.now(UTC)
user = User(
email="test@example.com",
referral_code="mycode",
referred_by_code="friendcode",
referred_at=now,
referral_discount_expires_at=now,
stripe_connect_account_id="acct_123",
)
assert user.referral_code == "mycode"
assert user.referred_by_code == "friendcode"
assert user.referred_at == now
assert user.referral_discount_expires_at == now
assert user.stripe_connect_account_id == "acct_123"
class TestUserPublicReferralFields:
"""Test UserPublic has referral fields."""
def test_defaults(self):
pub = UserPublic(email="test@example.com", role=UserRole.USER, credits=0)
assert pub.referral_code is None
assert pub.has_active_referral_discount is False
def test_with_referral(self):
pub = UserPublic(
email="test@example.com",
role=UserRole.USER,
credits=5,
referral_code="mycode",
has_active_referral_discount=True,
)
assert pub.referral_code == "mycode"
assert pub.has_active_referral_discount is True
class TestReferralAPIModels:
"""Test API request/response models exist and have correct shapes."""
def test_create_request(self):
req = CreateReferralLinkRequest(owner_email="user@example.com", display_name="My Link")
assert req.display_name == "My Link"
assert req.owner_email == "user@example.com"
assert req.discount_percent == 10
assert req.kickback_percent == 20
def test_update_request(self):
req = UpdateReferralLinkRequest(enabled=False)
assert req.enabled is False
def test_link_response(self):
resp = ReferralLinkResponse(
code="abc",
owner_email="a@b.com",
discount_percent=10,
kickback_percent=20,
is_vanity=False,
enabled=True,
stats=ReferralLinkStats(),
created_at=datetime.now(UTC),
)
assert resp.code == "abc"
def test_earning_response(self):
resp = ReferralEarningResponse(
id="e1",
referred_email="new@b.com",
referral_code="abc",
purchase_amount_cents=2999,
earning_amount_cents=600,
status="pending",
created_at=datetime.now(UTC),
)
assert resp.status == "pending"
def test_payout_response(self):
resp = ReferralPayoutResponse(
id="p1",
amount_cents=1200,
earnings_count=2,
status="processing",
created_at=datetime.now(UTC),
)
assert resp.amount_cents == 1200
def test_dashboard_response(self):
resp = ReferralDashboardResponse(
referral_link=ReferralLinkResponse(
code="abc",
owner_email="a@b.com",
discount_percent=10,
kickback_percent=20,
is_vanity=False,
enabled=True,
stats=ReferralLinkStats(),
created_at=datetime.now(UTC),
),
recent_earnings=[],
recent_payouts=[],
total_earned_cents=0,
total_paid_cents=0,
pending_balance_cents=0,
stripe_connect_onboarded=False,
)
assert resp.total_earned_cents == 0
def test_interstitial_response(self):
resp = ReferralInterstitialResponse(
referral_code="abc",
referrer_display_name="Friend",
discount_percent=10,
discount_duration_days=30,
)
assert resp.referral_code == "abc"
assert resp.referrer_display_name == "Friend"
+347
View File
@@ -0,0 +1,347 @@
"""
Tests for Referral API routes.
Tests the /api/referrals/* endpoints for referral link management,
interstitial pages, dashboard, and admin operations.
"""
import pytest
from unittest.mock import Mock, patch, MagicMock
from fastapi.testclient import TestClient
from backend.main import app
from backend.api.dependencies import require_auth, require_admin
from backend.services.auth_service import UserType, AuthResult
from backend.models.referral import ReferralLink, ReferralLinkStats
@pytest.fixture(autouse=True)
def _clear_overrides():
"""Clear dependency overrides before and after each test."""
app.dependency_overrides.clear()
yield
app.dependency_overrides.clear()
@pytest.fixture
def client():
"""Create test client."""
return TestClient(app)
@pytest.fixture
def mock_auth_result():
"""Create a mock AuthResult for regular user."""
return AuthResult(
is_valid=True,
user_type=UserType.UNLIMITED,
remaining_uses=-1,
message="Valid",
user_email="test@example.com",
is_admin=False,
)
@pytest.fixture
def mock_admin_auth_result():
"""Create a mock AuthResult for admin user."""
return AuthResult(
is_valid=True,
user_type=UserType.ADMIN,
remaining_uses=-1,
message="Valid",
user_email="admin@nomadkaraoke.com",
is_admin=True,
)
def _make_referral_link(**overrides) -> ReferralLink:
"""Helper to create a ReferralLink with sensible defaults."""
defaults = {
"code": "abc12345",
"owner_email": "referrer@example.com",
"display_name": "Test Referrer",
"custom_message": "Join karaoke!",
"discount_percent": 10,
"kickback_percent": 20,
"discount_duration_days": 30,
"earning_duration_days": 365,
"is_vanity": False,
"enabled": True,
"stats": ReferralLinkStats(clicks=5, signups=2, purchases=1, total_earned_cents=500),
}
defaults.update(overrides)
return ReferralLink(**defaults)
# ============================================================================
# GET /api/referrals/r/{code} - Public interstitial
# ============================================================================
class TestGetInterstitial:
"""Tests for GET /api/referrals/r/{code}."""
@patch("backend.api.routes.referrals.get_referral_service")
def test_valid_code_returns_interstitial(self, mock_get_service, client):
"""Valid code returns 200 with referral data and display_name."""
mock_service = Mock()
link = _make_referral_link()
mock_service.get_link_by_code.return_value = link
mock_get_service.return_value = mock_service
response = client.get("/api/referrals/r/abc12345")
assert response.status_code == 200
data = response.json()
assert data["valid"] is True
assert data["referral_code"] == "abc12345"
assert data["referrer_display_name"] == "Test Referrer"
assert data["discount_percent"] == 10
assert data["discount_duration_days"] == 30
assert data["custom_message"] == "Join karaoke!"
mock_service.increment_clicks.assert_called_once_with("abc12345")
@patch("backend.api.routes.referrals.get_referral_service")
def test_invalid_code_returns_valid_false(self, mock_get_service, client):
"""Invalid code returns 200 with valid=False."""
mock_service = Mock()
mock_service.get_link_by_code.return_value = None
mock_get_service.return_value = mock_service
response = client.get("/api/referrals/r/nonexistent")
assert response.status_code == 200
data = response.json()
assert data["valid"] is False
mock_service.increment_clicks.assert_not_called()
@patch("backend.api.routes.referrals.get_referral_service")
def test_click_increment_failure_does_not_break_response(self, mock_get_service, client):
"""Click tracking failure should not affect the response."""
mock_service = Mock()
link = _make_referral_link()
mock_service.get_link_by_code.return_value = link
mock_service.increment_clicks.side_effect = Exception("Firestore error")
mock_get_service.return_value = mock_service
response = client.get("/api/referrals/r/abc12345")
assert response.status_code == 200
data = response.json()
assert data["valid"] is True
@patch("backend.api.routes.referrals.get_referral_service")
def test_no_track_skips_click_increment(self, mock_get_service, client):
"""no_track=true should return data without incrementing clicks."""
mock_service = Mock()
link = _make_referral_link()
mock_service.get_link_by_code.return_value = link
mock_get_service.return_value = mock_service
response = client.get("/api/referrals/r/abc12345?no_track=true")
assert response.status_code == 200
data = response.json()
assert data["valid"] is True
assert data["referral_code"] == "abc12345"
assert data["referrer_display_name"] == "Test Referrer"
mock_service.increment_clicks.assert_not_called()
# ============================================================================
# GET /api/referrals/me - Dashboard
# ============================================================================
class TestGetDashboard:
"""Tests for GET /api/referrals/me."""
@patch("backend.api.routes.referrals.get_referral_service")
def test_authenticated_user_gets_dashboard(self, mock_get_service, client, mock_auth_result):
"""Authenticated user gets their referral dashboard."""
app.dependency_overrides[require_auth] = lambda: mock_auth_result
mock_service = Mock()
mock_service.get_dashboard_data.return_value = {
"link": {"code": "abc12345", "display_name": "Test"},
"pending_balance_cents": 500,
"total_earned_cents": 1000,
"total_paid_cents": 200,
"recent_earnings": [],
"recent_payouts": [],
"stripe_connect_configured": False,
}
mock_get_service.return_value = mock_service
response = client.get("/api/referrals/me")
assert response.status_code == 200
data = response.json()
assert data["link"]["code"] == "abc12345"
assert data["pending_balance_cents"] == 500
assert data["stripe_connect_configured"] is False
mock_service.get_dashboard_data.assert_called_once_with("test@example.com")
def test_unauthenticated_returns_401(self, client):
"""Unauthenticated request returns 401."""
# No dependency override -- real auth will reject
response = client.get("/api/referrals/me")
assert response.status_code == 401
# ============================================================================
# PUT /api/referrals/me - Update own link
# ============================================================================
class TestUpdateMyLink:
"""Tests for PUT /api/referrals/me."""
@patch("backend.api.routes.referrals.get_referral_service")
def test_update_display_name(self, mock_get_service, client, mock_auth_result):
"""User can update their display name."""
app.dependency_overrides[require_auth] = lambda: mock_auth_result
mock_service = Mock()
link = _make_referral_link(owner_email="test@example.com")
mock_service.get_or_create_link.return_value = link
mock_service.update_link.return_value = (True, "Link updated")
mock_get_service.return_value = mock_service
response = client.put(
"/api/referrals/me",
json={"display_name": "New Name"},
)
assert response.status_code == 200
assert response.json()["ok"] is True
mock_service.update_link.assert_called_once_with(
"abc12345", display_name="New Name"
)
# ============================================================================
# POST /api/referrals/me/connect - Stripe Connect
# ============================================================================
class TestStripeConnect:
"""Tests for POST /api/referrals/me/connect."""
@patch("backend.services.user_service.get_user_service")
@patch("backend.api.routes.referrals.get_referral_service")
def test_start_connect_onboarding(self, mock_get_service, mock_get_user_svc, client, mock_auth_result):
"""User can start Stripe Connect onboarding."""
app.dependency_overrides[require_auth] = lambda: mock_auth_result
mock_service = Mock()
mock_service.create_connect_account.return_value = ("acct_123", "https://connect.stripe.com/onboard")
mock_get_service.return_value = mock_service
# Mock user without existing Connect account
mock_user = Mock()
mock_user.stripe_connect_account_id = None
mock_user_service = Mock()
mock_user_service.get_user.return_value = mock_user
mock_get_user_svc.return_value = mock_user_service
response = client.post("/api/referrals/me/connect")
assert response.status_code == 200
data = response.json()
assert data["account_id"] == "acct_123"
assert "onboarding_url" in data
# ============================================================================
# Admin endpoints
# ============================================================================
class TestAdminVanityLink:
"""Tests for POST /api/referrals/admin/vanity."""
@patch("backend.api.routes.referrals.get_referral_service")
def test_create_vanity_link(self, mock_get_service, client, mock_admin_auth_result):
"""Admin can create a vanity referral link."""
app.dependency_overrides[require_admin] = lambda: mock_admin_auth_result
mock_service = Mock()
link = _make_referral_link(code="karaoke-king", is_vanity=True)
mock_service.create_vanity_link.return_value = (True, link, "Vanity link created")
mock_get_service.return_value = mock_service
response = client.post(
"/api/referrals/admin/vanity",
json={"vanity_code": "karaoke-king", "owner_email": "king@example.com", "display_name": "King of Karaoke"},
)
assert response.status_code == 200
data = response.json()
assert data["ok"] is True
assert data["code"] == "karaoke-king"
@patch("backend.api.routes.referrals.get_referral_service")
def test_vanity_code_required(self, mock_get_service, client, mock_admin_auth_result):
"""Vanity code is required for vanity link creation."""
app.dependency_overrides[require_admin] = lambda: mock_admin_auth_result
response = client.post(
"/api/referrals/admin/vanity",
json={"owner_email": "user@example.com", "display_name": "No Code"},
)
assert response.status_code == 400
class TestAdminListLinks:
"""Tests for GET /api/referrals/admin/links."""
@patch("backend.api.routes.referrals.get_referral_service")
def test_list_links(self, mock_get_service, client, mock_admin_auth_result):
"""Admin can list all referral links."""
app.dependency_overrides[require_admin] = lambda: mock_admin_auth_result
mock_service = Mock()
mock_service.list_links.return_value = [
_make_referral_link(code="link1"),
_make_referral_link(code="link2"),
]
mock_get_service.return_value = mock_service
response = client.get("/api/referrals/admin/links")
assert response.status_code == 200
data = response.json()
assert data["count"] == 2
assert len(data["links"]) == 2
def test_non_admin_returns_403(self, client, mock_auth_result):
"""Non-admin user gets 403."""
app.dependency_overrides[require_auth] = lambda: mock_auth_result
# Don't override require_admin -- it will check is_admin=False and raise 403
response = client.get("/api/referrals/admin/links")
assert response.status_code == 403
class TestAdminUpdateLink:
"""Tests for PUT /api/referrals/admin/links/{code}."""
@patch("backend.api.routes.referrals.get_referral_service")
def test_admin_update_link(self, mock_get_service, client, mock_admin_auth_result):
"""Admin can update any link."""
app.dependency_overrides[require_admin] = lambda: mock_admin_auth_result
mock_service = Mock()
mock_service.update_link.return_value = (True, "Link updated")
mock_get_service.return_value = mock_service
response = client.put(
"/api/referrals/admin/links/abc12345",
json={"enabled": False},
)
assert response.status_code == 200
assert response.json()["ok"] is True
mock_service.update_link.assert_called_once_with("abc12345", enabled=False)
+854
View File
@@ -0,0 +1,854 @@
"""
Unit tests for ReferralService — link management.
Tests cover:
- Code generation (8-char lowercase alphanumeric, uniqueness)
- Vanity code validation (length, chars, reserved words, hyphens)
- get_or_create_link (returns existing, creates new)
- get_link_by_code (found, not found, disabled)
- get_or_create_stripe_coupon (delegates to stripe service)
- should_apply_discount (active, expired, no referral)
"""
import pytest
import sys
import types
from unittest.mock import MagicMock, patch
from datetime import datetime, timedelta
from backend.services.referral_service import (
ReferralService,
RESERVED_CODES,
VANITY_CODE_PATTERN,
REFERRAL_LINKS_COLLECTION,
)
# ============================================================================
# Fixtures
# ============================================================================
@pytest.fixture
def mock_db():
return MagicMock()
@pytest.fixture
def mock_stripe_service():
return MagicMock()
@pytest.fixture
def service(mock_db, mock_stripe_service):
svc = ReferralService.__new__(ReferralService)
svc.db = mock_db
svc.stripe_service = mock_stripe_service
return svc
@pytest.fixture
def mock_user_service():
"""Inject a fake backend.services.user_service module so local imports resolve."""
mock_get_user_svc = MagicMock()
fake_module = types.ModuleType("backend.services.user_service")
fake_module.get_user_service = mock_get_user_svc
with patch.dict(sys.modules, {"backend.services.user_service": fake_module}):
yield mock_get_user_svc
# ============================================================================
# TestGenerateCode
# ============================================================================
class TestGenerateCode:
"""Tests for _generate_code()."""
def test_generates_8_char_lowercase_alphanumeric(self, service):
code = service._generate_code()
assert len(code) == 8
assert code == code.lower()
assert code.isalnum()
def test_generates_unique_codes(self, service):
codes = {service._generate_code() for _ in range(100)}
# With 36^8 possible codes, 100 should all be unique
assert len(codes) == 100
# ============================================================================
# TestValidateVanityCode
# ============================================================================
class TestValidateVanityCode:
"""Tests for _validate_vanity_code()."""
def test_valid_code(self, service):
valid, msg = service._validate_vanity_code("karaoke-king")
assert valid is True
def test_too_short(self, service):
valid, msg = service._validate_vanity_code("ab")
assert valid is False
assert "3-30" in msg or "characters" in msg.lower()
def test_too_long(self, service):
valid, msg = service._validate_vanity_code("a" * 31)
assert valid is False
def test_invalid_chars(self, service):
valid, msg = service._validate_vanity_code("bad_code!")
assert valid is False
def test_reserved_words(self, service):
valid, msg = service._validate_vanity_code("admin")
assert valid is False
assert "reserved" in msg.lower()
valid, msg = service._validate_vanity_code("api")
assert valid is False
assert "reserved" in msg.lower()
def test_allows_hyphens(self, service):
valid, msg = service._validate_vanity_code("my-cool-code")
assert valid is True
# ============================================================================
# TestGetOrCreateLink
# ============================================================================
class TestGetOrCreateLink:
"""Tests for get_or_create_link()."""
def test_returns_existing_link(self, service, mock_db):
# Set up mock: query returns an existing doc
mock_query = MagicMock()
mock_db.collection.return_value.where.return_value.limit.return_value.stream.return_value = [
MagicMock(to_dict=lambda: {
"code": "abc12345",
"owner_email": "user@example.com",
"discount_percent": 10,
"kickback_percent": 20,
"discount_duration_days": 30,
"earning_duration_days": 365,
"is_vanity": False,
"enabled": True,
"created_at": datetime(2026, 1, 1),
"updated_at": datetime(2026, 1, 1),
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
})
]
link = service.get_or_create_link("user@example.com")
assert link.code == "abc12345"
assert link.owner_email == "user@example.com"
# Should NOT have called document().set()
mock_db.collection.return_value.document.return_value.set.assert_not_called()
def test_creates_new_if_none_exists(self, service, mock_db):
# Query returns empty — no existing link
mock_db.collection.return_value.where.return_value.limit.return_value.stream.return_value = []
# doc.get() returns a doc that doesn't exist (no collision)
mock_doc_ref = MagicMock()
mock_doc_snapshot = MagicMock()
mock_doc_snapshot.exists = False
mock_doc_ref.get.return_value = mock_doc_snapshot
mock_db.collection.return_value.document.return_value = mock_doc_ref
link = service.get_or_create_link("new@example.com")
assert link is not None
assert link.owner_email == "new@example.com"
assert len(link.code) == 8
mock_doc_ref.set.assert_called_once()
# ============================================================================
# TestGetLinkByCode
# ============================================================================
class TestGetLinkByCode:
"""Tests for get_link_by_code()."""
def test_returns_link_if_exists(self, service, mock_db):
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"code": "abc12345",
"owner_email": "user@example.com",
"discount_percent": 10,
"kickback_percent": 20,
"discount_duration_days": 30,
"earning_duration_days": 365,
"is_vanity": False,
"enabled": True,
"created_at": datetime(2026, 1, 1),
"updated_at": datetime(2026, 1, 1),
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
link = service.get_link_by_code("abc12345")
assert link is not None
assert link.code == "abc12345"
def test_returns_none_if_not_found(self, service, mock_db):
mock_doc = MagicMock()
mock_doc.exists = False
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
link = service.get_link_by_code("nonexistent")
assert link is None
def test_returns_none_if_disabled(self, service, mock_db):
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"code": "abc12345",
"owner_email": "user@example.com",
"discount_percent": 10,
"kickback_percent": 20,
"discount_duration_days": 30,
"earning_duration_days": 365,
"is_vanity": False,
"enabled": False,
"created_at": datetime(2026, 1, 1),
"updated_at": datetime(2026, 1, 1),
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
link = service.get_link_by_code("abc12345")
assert link is None
# ============================================================================
# TestAttributeReferral
# ============================================================================
def _mock_valid_link_doc(mock_db, owner_email="referrer@example.com"):
"""Helper: set up mock_db so get_link_by_code returns a valid link."""
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"code": "abc12345",
"owner_email": owner_email,
"discount_percent": 10,
"kickback_percent": 20,
"discount_duration_days": 30,
"earning_duration_days": 365,
"is_vanity": False,
"enabled": True,
"created_at": datetime(2026, 1, 1),
"updated_at": datetime(2026, 1, 1),
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
class TestAttributeReferral:
"""Tests for attribute_referral()."""
def test_successful_attribution(self, service, mock_db):
_mock_valid_link_doc(mock_db, owner_email="referrer@example.com")
success, msg = service.attribute_referral("newuser@example.com", "abc12345")
assert success is True
assert "attributed" in msg.lower()
# Should have incremented signups
mock_db.collection.return_value.document.return_value.update.assert_called_once()
def test_self_referral_blocked(self, service, mock_db):
_mock_valid_link_doc(mock_db, owner_email="user@example.com")
success, msg = service.attribute_referral("user@example.com", "abc12345")
assert success is False
assert "own" in msg.lower() or "self" in msg.lower()
def test_invalid_code_rejected(self, service, mock_db):
mock_doc = MagicMock()
mock_doc.exists = False
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
success, msg = service.attribute_referral("newuser@example.com", "nonexistent")
assert success is False
assert "invalid" in msg.lower() or "disabled" in msg.lower()
# ============================================================================
# TestGetOrCreateStripeCoupon
# ============================================================================
class TestGetOrCreateStripeCoupon:
def test_creates_coupon_for_new_percentage(self, service, mock_stripe_service):
mock_stripe_service.get_or_create_referral_coupon.return_value = "referral-10pct"
coupon_id = service.get_or_create_stripe_coupon(10)
assert coupon_id == "referral-10pct"
mock_stripe_service.get_or_create_referral_coupon.assert_called_once_with(10)
# ============================================================================
# TestShouldApplyDiscount
# ============================================================================
class TestShouldApplyDiscount:
def test_active_discount(self, service):
user_data = {
"referred_by_code": "abc12345",
"referral_discount_expires_at": datetime.utcnow() + timedelta(days=15),
}
assert service.should_apply_discount(user_data) is True
def test_expired_discount(self, service):
user_data = {
"referred_by_code": "abc12345",
"referral_discount_expires_at": datetime.utcnow() - timedelta(days=1),
}
assert service.should_apply_discount(user_data) is False
def test_no_referral(self, service):
user_data = {}
assert service.should_apply_discount(user_data) is False
# ============================================================================
# TestRecordEarning
# ============================================================================
class TestRecordEarning:
def test_creates_earning_within_window(self, service, mock_db):
"""Earning is created when purchase is within earning window."""
mock_user_doc = MagicMock()
mock_user_doc.exists = True
mock_user_doc.to_dict.return_value = {
"email": "referred@example.com",
"referred_by_code": "abc12345",
"referred_at": datetime.utcnow() - timedelta(days=30),
}
mock_link_doc = MagicMock()
mock_link_doc.exists = True
mock_link_doc.to_dict.return_value = {
"code": "abc12345",
"owner_email": "referrer@example.com",
"kickback_percent": 20,
"earning_duration_days": 365,
"discount_percent": 10,
"discount_duration_days": 30,
"is_vanity": False,
"enabled": True,
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow(),
}
def collection_side_effect(name):
mock_col = MagicMock()
if name == "gen_users":
mock_col.document.return_value.get.return_value = mock_user_doc
elif name == REFERRAL_LINKS_COLLECTION:
mock_col.document.return_value.get.return_value = mock_link_doc
return mock_col
mock_db.collection.side_effect = collection_side_effect
result = service.record_earning(
referred_email="referred@example.com",
stripe_session_id="cs_test_123",
purchase_amount_cents=1575,
)
assert result is not None
assert result["earning_amount_cents"] == 315 # 20% of 1575
def test_no_earning_outside_window(self, service, mock_db):
"""No earning created when purchase is outside earning window."""
mock_user_doc = MagicMock()
mock_user_doc.exists = True
mock_user_doc.to_dict.return_value = {
"email": "referred@example.com",
"referred_by_code": "abc12345",
"referred_at": datetime.utcnow() - timedelta(days=400),
}
mock_link_doc = MagicMock()
mock_link_doc.exists = True
mock_link_doc.to_dict.return_value = {
"code": "abc12345",
"owner_email": "referrer@example.com",
"kickback_percent": 20,
"earning_duration_days": 365,
"discount_percent": 10,
"discount_duration_days": 30,
"is_vanity": False,
"enabled": True,
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow(),
}
def collection_side_effect(name):
mock_col = MagicMock()
if name == "gen_users":
mock_col.document.return_value.get.return_value = mock_user_doc
elif name == REFERRAL_LINKS_COLLECTION:
mock_col.document.return_value.get.return_value = mock_link_doc
return mock_col
mock_db.collection.side_effect = collection_side_effect
result = service.record_earning(
referred_email="referred@example.com",
stripe_session_id="cs_test_456",
purchase_amount_cents=1575,
)
assert result is None
def test_no_earning_for_non_referred_user(self, service, mock_db):
"""No earning for users without referral attribution."""
mock_user_doc = MagicMock()
mock_user_doc.exists = True
mock_user_doc.to_dict.return_value = {"email": "user@example.com"}
mock_db.collection.return_value.document.return_value.get.return_value = mock_user_doc
result = service.record_earning(
referred_email="user@example.com",
stripe_session_id="cs_test_789",
purchase_amount_cents=1750,
)
assert result is None
# ============================================================================
# TestStripeConnectOnboarding
# ============================================================================
class TestStripeConnectOnboarding:
def test_create_connect_account(self, service, mock_stripe_service):
mock_stripe_service.create_connect_account.return_value = ("acct_123", "https://connect.stripe.com/onboard")
account_id, onboard_url = service.create_connect_account("referrer@example.com")
assert account_id == "acct_123"
assert "stripe.com" in onboard_url
# ============================================================================
# TestTriggerPayout
# ============================================================================
class TestTriggerPayout:
def test_payout_triggered_at_threshold(self, service, mock_db, mock_stripe_service):
"""Payout is triggered when pending earnings >= $20."""
earning_docs = []
for i in range(4):
doc = MagicMock()
doc.to_dict.return_value = {
"id": f"earn-{i}",
"referrer_email": "referrer@example.com",
"referred_email": f"user{i}@example.com",
"referral_code": "abc12345",
"stripe_session_id": f"cs_{i}",
"purchase_amount_cents": 1750,
"earning_amount_cents": 525, # $5.25 each, 4 = $21.00
"status": "pending",
"created_at": datetime.utcnow(),
}
doc.reference = MagicMock()
earning_docs.append(doc)
mock_query = MagicMock()
mock_query.where.return_value = mock_query
mock_query.get.return_value = earning_docs
mock_db.collection.return_value = mock_query
mock_stripe_service.create_transfer.return_value = "tr_123"
result = service.check_and_trigger_payout(
referrer_email="referrer@example.com",
stripe_connect_account_id="acct_123",
)
assert result is True
def test_no_payout_below_threshold(self, service, mock_db, mock_stripe_service):
"""No payout when pending earnings < $20."""
earning_doc = MagicMock()
earning_doc.to_dict.return_value = {
"id": "earn-1",
"referrer_email": "referrer@example.com",
"earning_amount_cents": 315,
"status": "pending",
"created_at": datetime.utcnow(),
}
earning_doc.reference = MagicMock()
mock_query = MagicMock()
mock_query.where.return_value = mock_query
mock_query.get.return_value = [earning_doc]
mock_db.collection.return_value = mock_query
result = service.check_and_trigger_payout(
referrer_email="referrer@example.com",
stripe_connect_account_id="acct_123",
)
assert result is False
# ============================================================================
# TestFullReferralFlow
# ============================================================================
class TestFullReferralFlow:
"""Integration-style test covering the full referral lifecycle."""
def test_full_flow(self, service, mock_db, mock_stripe_service):
"""
1. Referrer gets a link
2. Referred user signs up (attribution)
3. Discount check
4. Earning calculation
"""
# Step 1: Referrer gets a link
mock_query = MagicMock()
mock_query.limit.return_value.get.return_value = []
mock_code_doc = MagicMock()
mock_code_doc.exists = False
mock_db.collection.return_value.where.return_value = mock_query
mock_db.collection.return_value.document.return_value.get.return_value = mock_code_doc
link = service.get_or_create_link("referrer@example.com")
assert link is not None
assert link.owner_email == "referrer@example.com"
# Step 2: Attribution
mock_link_doc = MagicMock()
mock_link_doc.exists = True
mock_link_doc.to_dict.return_value = {
"code": link.code,
"owner_email": "referrer@example.com",
"discount_percent": 10,
"kickback_percent": 20,
"discount_duration_days": 30,
"earning_duration_days": 365,
"is_vanity": False,
"enabled": True,
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow(),
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_link_doc
success, msg = service.attribute_referral("newuser@example.com", link.code)
assert success is True
# Step 3: Discount check
user_data = {
"referred_by_code": link.code,
"referral_discount_expires_at": datetime.utcnow() + timedelta(days=15),
}
assert service.should_apply_discount(user_data) is True
# Step 4: Earning calculation
assert int(1575 * 20 / 100) == 315 # 20% of $15.75 = $3.15
# ============================================================================
# TestGetAttributionData
# ============================================================================
class TestGetAttributionData:
"""Tests for get_attribution_data() — returns dict for user doc update."""
def test_returns_attribution_dict(self, service, mock_db):
"""Attribution data includes correct fields and timedelta calculation."""
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"code": "abc12345",
"owner_email": "referrer@example.com",
"discount_percent": 10,
"kickback_percent": 20,
"discount_duration_days": 30,
"earning_duration_days": 365,
"is_vanity": False,
"enabled": True,
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow(),
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
data = service.get_attribution_data("abc12345")
assert data is not None
assert data["referred_by_code"] == "abc12345"
assert "referred_at" in data
assert "referral_discount_expires_at" in data
# Discount should expire ~30 days from now
delta = data["referral_discount_expires_at"] - data["referred_at"]
assert delta.days == 30
def test_returns_none_for_invalid_code(self, service, mock_db):
mock_doc = MagicMock()
mock_doc.exists = False
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
data = service.get_attribution_data("nonexistent")
assert data is None
def test_custom_discount_duration(self, service, mock_db):
"""Links with custom duration calculate correct expiry."""
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"code": "custom90",
"owner_email": "referrer@example.com",
"discount_percent": 15,
"kickback_percent": 25,
"discount_duration_days": 90, # Custom 90-day duration
"earning_duration_days": 365,
"is_vanity": True,
"enabled": True,
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow(),
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
data = service.get_attribution_data("custom90")
delta = data["referral_discount_expires_at"] - data["referred_at"]
assert delta.days == 90
# ============================================================================
# TestGetDiscountForCheckout
# ============================================================================
class TestGetDiscountForCheckout:
"""Tests for get_discount_for_checkout() — coupon lookup for Stripe checkout."""
def test_returns_discount_for_active_referred_user(self, service, mock_db, mock_stripe_service, mock_user_service):
"""Returns coupon info when user has active referral discount."""
mock_user = MagicMock()
mock_user.referred_by_code = "abc12345"
mock_user.referral_discount_expires_at = datetime.utcnow() + timedelta(days=15)
mock_user_svc = MagicMock()
mock_user_svc.get_user.return_value = mock_user
mock_user_service.return_value = mock_user_svc
# Mock referral link lookup
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"code": "abc12345",
"owner_email": "referrer@example.com",
"discount_percent": 10,
"kickback_percent": 20,
"discount_duration_days": 30,
"earning_duration_days": 365,
"is_vanity": False,
"enabled": True,
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow(),
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
mock_stripe_service.get_or_create_referral_coupon.return_value = "referral-10pct"
result = service.get_discount_for_checkout("referred@example.com")
assert result is not None
assert result["coupon_id"] == "referral-10pct"
assert result["discount_percent"] == 10
def test_returns_none_for_expired_discount(self, service, mock_db, mock_user_service):
"""Returns None when user's discount has expired."""
mock_user = MagicMock()
mock_user.referred_by_code = "abc12345"
mock_user.referral_discount_expires_at = datetime.utcnow() - timedelta(days=1)
mock_user_svc = MagicMock()
mock_user_svc.get_user.return_value = mock_user
mock_user_service.return_value = mock_user_svc
result = service.get_discount_for_checkout("referred@example.com")
assert result is None
def test_returns_none_for_non_referred_user(self, service, mock_db, mock_user_service):
"""Returns None when user has no referral."""
mock_user = MagicMock()
mock_user.referred_by_code = None
mock_user.referral_discount_expires_at = None
mock_user_svc = MagicMock()
mock_user_svc.get_user.return_value = mock_user
mock_user_service.return_value = mock_user_svc
result = service.get_discount_for_checkout("regular@example.com")
assert result is None
# ============================================================================
# TestGetDashboardData
# ============================================================================
class TestGetDashboardData:
"""Tests for get_dashboard_data() — full referral dashboard payload."""
def test_returns_complete_dashboard(self, service, mock_db, mock_user_service):
"""Dashboard data includes link, earnings, payouts, and balances."""
# Mock user service for Connect status check
mock_user = MagicMock()
mock_user.stripe_connect_account_id = None
mock_user_svc = MagicMock()
mock_user_svc.get_user.return_value = mock_user
mock_user_service.return_value = mock_user_svc
# Mock get_or_create_link: query stream returns existing link doc
mock_link_doc = MagicMock()
mock_link_doc.to_dict.return_value = {
"code": "mycode12",
"owner_email": "user@example.com",
"discount_percent": 10,
"kickback_percent": 20,
"discount_duration_days": 30,
"earning_duration_days": 365,
"is_vanity": False,
"enabled": True,
"display_name": None,
"custom_message": None,
"stripe_coupon_id": None,
"stats": {"clicks": 5, "signups": 2, "purchases": 1, "total_earned_cents": 350},
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow(),
}
# Complex mock setup for multiple collection queries
mock_link_query = MagicMock()
mock_link_query.limit.return_value.stream.return_value = [mock_link_doc]
mock_earnings_query = MagicMock()
mock_earnings_query.order_by.return_value.limit.return_value.stream.return_value = []
mock_payouts_query = MagicMock()
mock_payouts_query.order_by.return_value.limit.return_value.stream.return_value = []
def collection_side_effect(name):
mock_col = MagicMock()
if name == "referral_links":
mock_col.where.return_value = mock_link_query
elif name == "referral_earnings":
mock_col.where.return_value = mock_earnings_query
elif name == "referral_payouts":
mock_col.where.return_value = mock_payouts_query
return mock_col
mock_db.collection.side_effect = collection_side_effect
data = service.get_dashboard_data("user@example.com")
assert "link" in data
assert data["link"]["code"] == "mycode12"
assert data["link"]["stats"]["clicks"] == 5
assert data["pending_balance_cents"] == 0
assert data["total_earned_cents"] == 350
assert data["stripe_connect_configured"] is False
assert isinstance(data["recent_earnings"], list)
assert isinstance(data["recent_payouts"], list)
# ============================================================================
# TestEarningCalculationEdgeCases
# ============================================================================
class TestEarningCalculationEdgeCases:
"""Edge cases for record_earning() — rounding and zero amounts."""
def test_earning_rounds_down(self, service, mock_db):
"""Earning calculation truncates fractional cents."""
mock_user_doc = MagicMock()
mock_user_doc.exists = True
mock_user_doc.to_dict.return_value = {
"email": "referred@example.com",
"referred_by_code": "abc12345",
"referred_at": datetime.utcnow() - timedelta(days=10),
}
mock_link_doc = MagicMock()
mock_link_doc.exists = True
mock_link_doc.to_dict.return_value = {
"code": "abc12345",
"owner_email": "referrer@example.com",
"kickback_percent": 20,
"earning_duration_days": 365,
"discount_percent": 10,
"discount_duration_days": 30,
"is_vanity": False,
"enabled": True,
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow(),
}
def collection_side_effect(name):
mock_col = MagicMock()
if name == "gen_users":
mock_col.document.return_value.get.return_value = mock_user_doc
elif name == REFERRAL_LINKS_COLLECTION:
mock_col.document.return_value.get.return_value = mock_link_doc
return mock_col
mock_db.collection.side_effect = collection_side_effect
# 1999 * 20 / 100 = 399.8 -> should truncate to 399
result = service.record_earning(
referred_email="referred@example.com",
stripe_session_id="cs_edge_1",
purchase_amount_cents=1999,
)
assert result is not None
assert result["earning_amount_cents"] == 399
def test_zero_amount_returns_none(self, service, mock_db):
"""Zero purchase amount produces no earning."""
mock_user_doc = MagicMock()
mock_user_doc.exists = True
mock_user_doc.to_dict.return_value = {
"email": "referred@example.com",
"referred_by_code": "abc12345",
"referred_at": datetime.utcnow() - timedelta(days=10),
}
mock_link_doc = MagicMock()
mock_link_doc.exists = True
mock_link_doc.to_dict.return_value = {
"code": "abc12345",
"owner_email": "referrer@example.com",
"kickback_percent": 20,
"earning_duration_days": 365,
"discount_percent": 10,
"discount_duration_days": 30,
"is_vanity": False,
"enabled": True,
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow(),
}
def collection_side_effect(name):
mock_col = MagicMock()
if name == "gen_users":
mock_col.document.return_value.get.return_value = mock_user_doc
elif name == REFERRAL_LINKS_COLLECTION:
mock_col.document.return_value.get.return_value = mock_link_doc
return mock_col
mock_db.collection.side_effect = collection_side_effect
result = service.record_earning(
referred_email="referred@example.com",
stripe_session_id="cs_edge_2",
purchase_amount_cents=0,
)
assert result is None
+132 -7
View File
@@ -224,7 +224,38 @@ class TestRetryEndpoint:
assert has_video and has_instrumental_selection
def test_retry_checkpoint_detection_render_stage(self):
"""Test retry detects render stage checkpoint."""
"""Test retry detects render stage checkpoint when review was completed."""
job = Job(
job_id="test123",
status=JobStatus.FAILED,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test",
title="Song",
file_urls={
'lyrics': {'corrections': 'gs://bucket/path/corrections.json'},
'screens': {'title': 'gs://bucket/path/title.mov'}
},
state_data={
'instrumental_selection': 'clean'
}
)
# This job has corrections, screens, AND completed review - should retry from render
has_corrections = job.file_urls.get('lyrics', {}).get('corrections')
has_screens = job.file_urls.get('screens', {}).get('title')
has_video = job.file_urls.get('videos', {}).get('with_vocals')
has_review = (job.state_data or {}).get('instrumental_selection')
assert has_corrections and has_screens and not has_video and has_review
def test_retry_checkpoint_returns_to_review_when_not_completed(self):
"""Test retry returns to awaiting_review when corrections and screens exist
but user never completed the review (no instrumental_selection).
Regression test: previously, retry would skip to REVIEW_COMPLETE based solely
on corrections.json + title.mov existing, but these are auto-generated artifacts
that exist BEFORE the user reviews anything.
"""
job = Job(
job_id="test123",
status=JobStatus.FAILED,
@@ -236,13 +267,15 @@ class TestRetryEndpoint:
'lyrics': {'corrections': 'gs://bucket/path/corrections.json'},
'screens': {'title': 'gs://bucket/path/title.mov'}
}
# No state_data.instrumental_selection — review was never completed
)
# This job has corrections and screens - should retry from render
# Has corrections and screens but NO review completion
has_corrections = job.file_urls.get('lyrics', {}).get('corrections')
has_screens = job.file_urls.get('screens', {}).get('title')
has_video = job.file_urls.get('videos', {}).get('with_vocals')
assert has_corrections and has_screens and not has_video
has_review = (job.state_data or {}).get('instrumental_selection')
# Should match the "awaiting_review" checkpoint, NOT "render"
assert has_corrections and has_screens and not has_review
def test_retry_checkpoint_detection_from_beginning(self):
"""Test retry detects need to restart from beginning."""
@@ -525,14 +558,14 @@ class TestSummaryEndpoint:
assert list(result['file_urls'].keys()) == ['finals']
def test_hide_completed_statuses(self):
"""Verify _HIDE_COMPLETED_STATUSES only hides successful completions (not failed/cancelled)."""
"""Verify _HIDE_COMPLETED_STATUSES hides terminal statuses (not failed or active)."""
from backend.api.routes.jobs import _HIDE_COMPLETED_STATUSES
assert 'complete' in _HIDE_COMPLETED_STATUSES
assert 'prep_complete' in _HIDE_COMPLETED_STATUSES
# Failed/cancelled should NOT be hidden - users need to see these
assert 'cancelled' in _HIDE_COMPLETED_STATUSES
# Failed should NOT be hidden - users need to see these
assert 'failed' not in _HIDE_COMPLETED_STATUSES
assert 'cancelled' not in _HIDE_COMPLETED_STATUSES
# Active statuses should NOT be in the list
assert 'pending' not in _HIDE_COMPLETED_STATUSES
assert 'downloading' not in _HIDE_COMPLETED_STATUSES
@@ -703,3 +736,95 @@ class TestContentDispositionHeader:
decoded = unquote(utf8_part)
assert decoded == "周杰倫 - 青花瓷.mp4"
class TestSearchFiltering:
"""Tests for the search parameter on list_jobs summary mode."""
def _make_job_dict(self, job_id="job1", artist="Queen", title="Bohemian Rhapsody",
audio_search_artist=None, audio_search_title=None, status="complete"):
return {
"job_id": job_id,
"artist": artist,
"title": title,
"audio_search_artist": audio_search_artist,
"audio_search_title": audio_search_title,
"status": status,
"user_email": "admin@nomadkaraoke.com",
}
def test_search_filters_by_artist(self):
"""Search 'queen' should match job with artist='Queen'."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [
self._make_job_dict(job_id="j1", artist="Queen", title="We Will Rock You"),
self._make_job_dict(job_id="j2", artist="Eagles", title="Hotel California"),
]
result = _search_filter_jobs(jobs, "queen")
assert len(result) == 1
assert result[0]["job_id"] == "j1"
def test_search_filters_by_title(self):
"""Search 'california' should match job with title containing it."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [
self._make_job_dict(job_id="j1", artist="Queen", title="We Will Rock You"),
self._make_job_dict(job_id="j2", artist="Eagles", title="Hotel California"),
]
result = _search_filter_jobs(jobs, "california")
assert len(result) == 1
assert result[0]["job_id"] == "j2"
def test_search_filters_by_job_id(self):
"""Search by partial job_id."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [
self._make_job_dict(job_id="abc-123-def"),
self._make_job_dict(job_id="xyz-789-ghi"),
]
result = _search_filter_jobs(jobs, "abc-123")
assert len(result) == 1
assert result[0]["job_id"] == "abc-123-def"
def test_search_filters_by_audio_search_fields(self):
"""Search should also check audio_search_artist and audio_search_title."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [
self._make_job_dict(job_id="j1", artist="Display Name", title="Display Title",
audio_search_artist="Original Artist", audio_search_title="Original Song"),
]
result = _search_filter_jobs(jobs, "original artist")
assert len(result) == 1
def test_search_is_case_insensitive(self):
"""Search should be case-insensitive."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [self._make_job_dict(artist="QUEEN", title="Bohemian Rhapsody")]
result = _search_filter_jobs(jobs, "queen")
assert len(result) == 1
def test_search_handles_none_fields(self):
"""Search should not crash on None artist/title fields."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [self._make_job_dict(artist=None, title=None)]
result = _search_filter_jobs(jobs, "queen")
assert len(result) == 0
def test_search_empty_string_returns_all(self):
"""Empty search string should return all jobs."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [
self._make_job_dict(job_id="j1"),
self._make_job_dict(job_id="j2"),
]
result = _search_filter_jobs(jobs, "")
assert len(result) == 2
def test_search_returns_all_matches_for_limit_slicing(self):
"""Search returns all matches — caller applies limit separately."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [self._make_job_dict(job_id=f"j{i}", artist="Queen", title=f"Song {i}") for i in range(10)]
result = _search_filter_jobs(jobs, "queen")
assert len(result) == 10 # All 10 match; limit slicing is caller's job
# Verify caller can slice: simulates jobs_dicts[:limit] in route handler
assert len(result[:3]) == 3
+551
View File
@@ -0,0 +1,551 @@
"""
Tests for the search-lyrics operation and API endpoint.
Covers:
- create_lyrics_providers() factory function
- CorrectionOperations.search_lyrics_sources() static method
- CorrectionOperations.add_lyrics_source() force parameter
- POST /{job_id}/search-lyrics API endpoint
"""
import pytest
import os
from unittest.mock import MagicMock, patch, call
from typing import Dict, Any, List
# ---------------------------------------------------------------------------
# Helpers / fixtures
# ---------------------------------------------------------------------------
def _make_lyrics_data(source: str = "TestSource", text: str = "Hello world\nTest line") -> "LyricsData":
"""Create a minimal LyricsData object for testing."""
from karaoke_gen.lyrics_transcriber.types import LyricsData, LyricsSegment, LyricsMetadata, Word
from karaoke_gen.lyrics_transcriber.utils.word_utils import WordUtils
segments = []
for line in text.strip().splitlines():
words = [
Word(id=WordUtils.generate_id(), text=w, start_time=None, end_time=None)
for w in line.split()
]
segments.append(
LyricsSegment(
id=WordUtils.generate_id(),
text=line,
words=words,
start_time=None,
end_time=None,
)
)
return LyricsData(source=source, segments=segments, metadata=LyricsMetadata(source=source, track_name="Test Track", artist_names="Test Artist"))
def _make_correction_result(
reference_lyrics: Dict = None,
metadata: Dict = None,
) -> "CorrectionResult":
"""Create a minimal CorrectionResult for testing."""
from karaoke_gen.lyrics_transcriber.types import (
CorrectionResult, LyricsSegment, Word, LyricsData, LyricsMetadata
)
from karaoke_gen.lyrics_transcriber.utils.word_utils import WordUtils
# A single transcription segment
word = Word(id=WordUtils.generate_id(), text="hello", start_time=0.0, end_time=0.5)
segment = LyricsSegment(id=WordUtils.generate_id(), text="hello", words=[word], start_time=0.0, end_time=0.5)
return CorrectionResult(
original_segments=[segment],
corrected_segments=[segment],
corrections=[],
corrections_made=0,
confidence=1.0,
reference_lyrics=reference_lyrics or {},
anchor_sequences=[],
gap_sequences=[],
resized_segments=None,
metadata=metadata or {"audio_hash": "testhash"},
correction_steps=[],
word_id_map={},
segment_id_map={},
)
# ---------------------------------------------------------------------------
# Tests: create_lyrics_providers factory
# ---------------------------------------------------------------------------
class TestCreateLyricsProviders:
"""Tests for the create_lyrics_providers() module-level factory."""
def test_returns_list(self):
"""Factory always returns a list."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {}, clear=False):
# Remove API keys so only LRCLIB is created
env_override = {
k: "" for k in ["GENIUS_API_KEY", "RAPIDAPI_KEY", "SPOTIFY_COOKIE_SP_DC"]
}
with patch.dict(os.environ, env_override):
providers = create_lyrics_providers(cache_dir="/tmp")
assert isinstance(providers, list)
def test_lrclib_always_included(self):
"""LRCLIBProvider is always included regardless of env vars."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {"GENIUS_API_KEY": "", "RAPIDAPI_KEY": "", "SPOTIFY_COOKIE_SP_DC": ""}):
providers = create_lyrics_providers(cache_dir="/tmp")
provider_names = [p.get_name() for p in providers]
assert "LRCLIB" in provider_names
def test_genius_included_when_genius_key_set(self):
"""GeniusProvider is included when GENIUS_API_KEY is set."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {"GENIUS_API_KEY": "fake-key", "RAPIDAPI_KEY": "", "SPOTIFY_COOKIE_SP_DC": ""}):
providers = create_lyrics_providers(cache_dir="/tmp")
provider_names = [p.get_name() for p in providers]
assert "Genius" in provider_names
def test_genius_included_when_rapidapi_key_set(self):
"""GeniusProvider is included when RAPIDAPI_KEY is set (uses RapidAPI path)."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {"GENIUS_API_KEY": "", "RAPIDAPI_KEY": "fake-rapidapi", "SPOTIFY_COOKIE_SP_DC": ""}):
providers = create_lyrics_providers(cache_dir="/tmp")
provider_names = [p.get_name() for p in providers]
assert "Genius" in provider_names
def test_spotify_included_when_cookie_set(self):
"""SpotifyProvider is included when SPOTIFY_COOKIE_SP_DC is set."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {"GENIUS_API_KEY": "", "RAPIDAPI_KEY": "", "SPOTIFY_COOKIE_SP_DC": "fake-cookie"}):
providers = create_lyrics_providers(cache_dir="/tmp")
provider_names = [p.get_name() for p in providers]
assert "Spotify" in provider_names
def test_musixmatch_included_when_rapidapi_key_set(self):
"""MusixmatchProvider is included when RAPIDAPI_KEY is set."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {"GENIUS_API_KEY": "", "RAPIDAPI_KEY": "fake-rapidapi", "SPOTIFY_COOKIE_SP_DC": ""}):
providers = create_lyrics_providers(cache_dir="/tmp")
provider_names = [p.get_name() for p in providers]
assert "Musixmatch" in provider_names
def test_genius_not_included_without_keys(self):
"""GeniusProvider is excluded when neither key is set."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {"GENIUS_API_KEY": "", "RAPIDAPI_KEY": "", "SPOTIFY_COOKIE_SP_DC": ""}):
providers = create_lyrics_providers(cache_dir="/tmp")
provider_names = [p.get_name() for p in providers]
assert "Genius" not in provider_names
def test_all_providers_when_all_keys_set(self):
"""All four providers are returned when all credentials are set."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {
"GENIUS_API_KEY": "gk",
"RAPIDAPI_KEY": "rk",
"SPOTIFY_COOKIE_SP_DC": "sc",
}):
providers = create_lyrics_providers(cache_dir="/tmp")
provider_names = [p.get_name() for p in providers]
assert "Genius" in provider_names
assert "Spotify" in provider_names
assert "Musixmatch" in provider_names
assert "LRCLIB" in provider_names
assert len(providers) == 4
# ---------------------------------------------------------------------------
# Tests: CorrectionOperations.search_lyrics_sources
# ---------------------------------------------------------------------------
class TestSearchLyricsSources:
"""Tests for CorrectionOperations.search_lyrics_sources()."""
def _mock_provider(self, name: str, lyrics_data=None):
"""Build a mock BaseLyricsProvider that returns lyrics_data."""
mock = MagicMock()
mock.get_name.return_value = name
mock.fetch_lyrics.return_value = lyrics_data
return mock
def test_returns_dict_with_expected_keys(self):
"""Return value always contains all four expected keys."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory:
mock_factory.return_value = [] # No providers — simulates empty env
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
)
assert "updated_result" in result
assert "sources_added" in result
assert "sources_rejected" in result
assert "sources_not_found" in result
def test_no_providers_returns_no_results(self):
"""When no providers are available, returns no results."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory:
mock_factory.return_value = []
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
)
assert result["updated_result"] is None
assert result["sources_added"] == []
def test_provider_not_found_appended_to_not_found(self):
"""Provider returning None is recorded in sources_not_found."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
mock_provider = self._mock_provider("LRCLIB", lyrics_data=None)
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory:
mock_factory.return_value = [mock_provider]
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
)
assert "LRCLIB" in result["sources_not_found"]
assert result["updated_result"] is None
def test_provider_exception_appended_to_not_found(self):
"""Provider raising an exception is recorded in sources_not_found."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
mock_provider = self._mock_provider("Genius")
mock_provider.fetch_lyrics.side_effect = RuntimeError("network error")
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory:
mock_factory.return_value = [mock_provider]
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
)
assert "Genius" in result["sources_not_found"]
def test_existing_source_skipped(self):
"""Provider whose name is already in reference_lyrics is skipped."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
existing_lyrics = {"Genius": _make_lyrics_data("Genius")}
correction_result = _make_correction_result(reference_lyrics=existing_lyrics)
mock_provider = self._mock_provider("Genius", lyrics_data=_make_lyrics_data("Genius"))
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory:
mock_factory.return_value = [mock_provider]
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
)
# fetch_lyrics should NOT have been called
mock_provider.fetch_lyrics.assert_not_called()
assert result["updated_result"] is None # Nothing new to add
def test_lyrics_found_runs_corrector(self):
"""When lyrics are found, LyricsCorrector.run is called."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
lyrics_data = _make_lyrics_data("LRCLIB")
mock_provider = self._mock_provider("LRCLIB", lyrics_data=lyrics_data)
mock_corrector = MagicMock()
mock_corrector.all_handlers = []
mock_corrector.handlers = []
mock_updated = _make_correction_result(metadata={"audio_hash": "testhash"})
mock_corrector.run.return_value = mock_updated
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory, \
patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
mock_factory.return_value = [mock_provider]
MockCorrector.return_value = mock_corrector
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
)
assert mock_corrector.run.called
def test_force_sources_bypass_rejection(self):
"""Sources in force_sources are added even if the corrector rejects them."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
lyrics_data = _make_lyrics_data("Genius")
mock_provider = self._mock_provider("Genius", lyrics_data=lyrics_data)
# Corrector result that puts "Genius" in rejected_sources
mock_corrector = MagicMock()
mock_corrector.all_handlers = []
mock_corrector.handlers = []
mock_updated = _make_correction_result(
reference_lyrics={}, # Corrector filtered it out
metadata={
"audio_hash": "testhash",
"rejected_sources": {
"Genius": {"relevance": 0.0, "matched_words": 0, "total_words": 10,
"track_name": "", "artist_names": ""},
},
}
)
mock_corrector.run.return_value = mock_updated
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory, \
patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
mock_factory.return_value = [mock_provider]
MockCorrector.return_value = mock_corrector
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
force_sources=["Genius"],
)
# The forced source should be in sources_added, not rejected
assert "Genius" in result["sources_added"]
assert "Genius" not in result["sources_rejected"]
# And it should have been re-added to reference_lyrics
assert "Genius" in result["updated_result"].reference_lyrics
def test_audio_hash_preserved(self):
"""The audio_hash from the original correction_result is preserved."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
original_hash = "original-audio-hash-abc"
correction_result = _make_correction_result(metadata={"audio_hash": original_hash})
lyrics_data = _make_lyrics_data("LRCLIB")
mock_provider = self._mock_provider("LRCLIB", lyrics_data=lyrics_data)
mock_corrector = MagicMock()
mock_corrector.all_handlers = []
mock_corrector.handlers = []
mock_updated = _make_correction_result(metadata={}) # metadata without audio_hash
mock_corrector.run.return_value = mock_updated
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory, \
patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
mock_factory.return_value = [mock_provider]
MockCorrector.return_value = mock_corrector
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
)
if result["updated_result"] is not None:
assert result["updated_result"].metadata.get("audio_hash") == original_hash
# ---------------------------------------------------------------------------
# Tests: CorrectionOperations.add_lyrics_source force parameter
# ---------------------------------------------------------------------------
class TestAddLyricsSourceForce:
"""Tests for the force parameter added to add_lyrics_source."""
def test_force_false_does_not_override_rejection(self):
"""With force=False (default), rejected sources remain rejected."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
mock_corrector = MagicMock()
mock_corrector.all_handlers = []
mock_corrector.handlers = []
mock_updated = _make_correction_result(
reference_lyrics={}, # source was filtered out
metadata={
"audio_hash": "testhash",
"rejected_sources": {
"custom": {"relevance": 0.0, "matched_words": 0, "total_words": 5,
"track_name": "", "artist_names": ""},
},
}
)
mock_corrector.run.return_value = mock_updated
with patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
MockCorrector.return_value = mock_corrector
result = CorrectionOperations.add_lyrics_source(
correction_result=correction_result,
source="custom",
lyrics_text="Hello world\nTest line",
cache_dir="/tmp",
force=False,
)
# Source should NOT be in reference_lyrics when force=False
assert "custom" not in result.reference_lyrics
def test_force_true_adds_source_even_if_rejected(self):
"""With force=True, source is added back even if the corrector rejected it."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
mock_corrector = MagicMock()
mock_corrector.all_handlers = []
mock_corrector.handlers = []
mock_updated = _make_correction_result(
reference_lyrics={}, # source was filtered out
metadata={
"audio_hash": "testhash",
"rejected_sources": {
"custom": {"relevance": 0.0, "matched_words": 0, "total_words": 5,
"track_name": "", "artist_names": ""},
},
}
)
mock_corrector.run.return_value = mock_updated
with patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
MockCorrector.return_value = mock_corrector
result = CorrectionOperations.add_lyrics_source(
correction_result=correction_result,
source="custom",
lyrics_text="Hello world\nTest line",
cache_dir="/tmp",
force=True,
)
# Source SHOULD be in reference_lyrics when force=True
assert "custom" in result.reference_lyrics
def test_force_true_no_op_when_source_not_rejected(self):
"""With force=True but source wasn't rejected, nothing extra happens."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
mock_corrector = MagicMock()
mock_corrector.all_handlers = []
mock_corrector.handlers = []
# Source is accepted (not in rejected_sources)
mock_updated = _make_correction_result(
reference_lyrics={"custom": _make_lyrics_data("custom")},
metadata={"audio_hash": "testhash"},
)
mock_corrector.run.return_value = mock_updated
with patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
MockCorrector.return_value = mock_corrector
result = CorrectionOperations.add_lyrics_source(
correction_result=correction_result,
source="custom",
lyrics_text="Hello world\nTest line",
cache_dir="/tmp",
force=True,
)
# Source remains in reference_lyrics normally
assert "custom" in result.reference_lyrics
# ---------------------------------------------------------------------------
# Tests: POST /{job_id}/search-lyrics API endpoint
# ---------------------------------------------------------------------------
class TestSearchLyricsEndpoint:
"""Tests for the POST /{job_id}/search-lyrics API endpoint."""
def test_endpoint_exists(self):
"""Verify the search-lyrics endpoint is registered in the router."""
from backend.api.routes.review import router
paths = [route.path for route in router.routes]
assert any("search-lyrics" in p for p in paths), f"search-lyrics not found in: {paths}"
def test_search_lyrics_requires_artist_and_title(self):
"""Document that the endpoint requires artist and title fields."""
valid_payload = {
"artist": "The Beatles",
"title": "Hey Jude",
}
assert "artist" in valid_payload
assert "title" in valid_payload
assert valid_payload["artist"].strip()
assert valid_payload["title"].strip()
def test_search_lyrics_accepts_force_sources(self):
"""Document that force_sources is an optional list of provider names."""
payload_with_force = {
"artist": "The Beatles",
"title": "Hey Jude",
"force_sources": ["Genius", "LRCLIB"],
}
assert isinstance(payload_with_force["force_sources"], list)
def test_success_response_format(self):
"""Document the expected success response format."""
example_success_response = {
"status": "success",
"data": {}, # CorrectionData dict
"sources_added": ["LRCLIB"],
"sources_rejected": {"Genius": {"relevance": 0.1}},
"sources_not_found": ["Spotify"],
}
assert example_success_response["status"] == "success"
assert "data" in example_success_response
assert "sources_added" in example_success_response
assert "sources_rejected" in example_success_response
assert "sources_not_found" in example_success_response
def test_no_results_response_format(self):
"""Document the expected no_results response format."""
example_no_results_response = {
"status": "no_results",
"message": "No matching lyrics found from any provider",
"sources_rejected": {},
"sources_not_found": ["Genius", "LRCLIB"],
}
assert example_no_results_response["status"] == "no_results"
assert "message" in example_no_results_response
assert "sources_rejected" in example_no_results_response
assert "sources_not_found" in example_no_results_response
def test_search_lyrics_uses_correction_operations(self):
"""Verify CorrectionOperations.search_lyrics_sources exists and is callable."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
assert hasattr(CorrectionOperations, "search_lyrics_sources")
method = getattr(CorrectionOperations, "search_lyrics_sources")
assert callable(method)
def test_add_lyrics_source_has_force_parameter(self):
"""Verify add_lyrics_source now accepts a force parameter."""
import inspect
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
sig = inspect.signature(CorrectionOperations.add_lyrics_source)
assert "force" in sig.parameters
# Default should be False
assert sig.parameters["force"].default is False
+46 -1
View File
@@ -336,9 +336,54 @@ class TestWorkerService:
assert "test123" in str(override_args)
class TestWorkerServiceWarmup:
"""Test encoding worker warmup in trigger methods."""
@pytest.mark.asyncio
async def test_trigger_video_worker_calls_warmup(self):
"""trigger_video_worker calls _warmup_encoding_worker before dispatching."""
with patch('backend.services.worker_service.httpx.AsyncClient') as mock_client_cls:
mock_client = AsyncMock()
mock_client_cls.return_value.__aenter__.return_value = mock_client
mock_response = Mock()
mock_response.status_code = 200
mock_client.post.return_value = mock_response
worker_service = get_worker_service()
with patch.object(worker_service, '_warmup_encoding_worker') as mock_warmup:
await worker_service.trigger_video_worker("test-job")
mock_warmup.assert_called_once_with("test-job")
@pytest.mark.asyncio
async def test_trigger_render_video_worker_calls_warmup(self):
"""trigger_render_video_worker calls _warmup_encoding_worker before dispatching."""
with patch('backend.services.worker_service.httpx.AsyncClient') as mock_client_cls:
mock_client = AsyncMock()
mock_client_cls.return_value.__aenter__.return_value = mock_client
mock_response = Mock()
mock_response.status_code = 200
mock_client.post.return_value = mock_response
worker_service = get_worker_service()
with patch.object(worker_service, '_warmup_encoding_worker') as mock_warmup:
await worker_service.trigger_render_video_worker("test-job")
mock_warmup.assert_called_once_with("test-job")
def test_warmup_swallows_exceptions(self):
"""Warmup failures are logged but never block worker dispatch."""
worker_service = get_worker_service()
with patch('backend.services.encoding_worker_manager.EncodingWorkerManager.ensure_primary_running',
side_effect=Exception("Compute API down")):
# Should not raise
worker_service._warmup_encoding_worker("test-job")
class TestWorkerServiceCloudTasks:
"""Test WorkerService Cloud Tasks integration."""
def test_should_use_cloud_tasks_default_false(self):
"""Test that Cloud Tasks is disabled by default."""
from backend.services.worker_service import WorkerService, reset_worker_service
+12 -12
View File
@@ -120,12 +120,12 @@ class TestProcessStaleReviews:
mock_job_manager.cancel_job.assert_called_once_with(
"job-123", reason="Review not completed within 48 hours"
)
mock_email_service.send_review_expired.assert_called_once_with(
to_email="user@test.com",
artist="Test Artist",
title="Test Song",
credits_balance=2,
)
call_kwargs = mock_email_service.send_review_expired.call_args.kwargs
assert call_kwargs["to_email"] == "user@test.com"
assert call_kwargs["artist"] == "Test Artist"
assert call_kwargs["title"] == "Test Song"
assert call_kwargs["credits_balance"] == 2
assert "locale" in call_kwargs # locale now passed from user profile
async def test_expires_job_over_48h_with_reminder_already_sent(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should expire job >48h even if reminder was already sent (no duplicate reminder)."""
@@ -153,12 +153,12 @@ class TestProcessStaleReviews:
assert result["reminders_sent"] == 1
assert result["jobs_expired"] == 0
mock_email_service.send_review_reminder.assert_called_once_with(
to_email="user@test.com",
artist="Test Artist",
title="Test Song",
job_id="job-123",
)
call_kwargs = mock_email_service.send_review_reminder.call_args.kwargs
assert call_kwargs["to_email"] == "user@test.com"
assert call_kwargs["artist"] == "Test Artist"
assert call_kwargs["title"] == "Test Song"
assert call_kwargs["job_id"] == "job-123"
assert "locale" in call_kwargs
# Should update state_data with expiry_reminder_sent flag
mock_firestore.update_job.assert_called_once()
call_args = mock_firestore.update_job.call_args
@@ -0,0 +1,157 @@
"""Tests for the /api/health/system-status endpoint."""
import pytest
from unittest.mock import patch, MagicMock, AsyncMock
@pytest.fixture
def mock_encoding_status():
return {
"configured": True,
"enabled": True,
"available": True,
"status": "ok",
"active_jobs": 0,
"queue_length": 0,
"wheel_version": "0.155.3",
}
@pytest.fixture
def mock_flacfetch_status():
return {
"configured": True,
"available": True,
"status": "ok",
"version": "0.19.1",
}
@pytest.fixture
def mock_separator_status():
return {
"available": True,
"status": "ok",
"version": "0.4.3",
}
@pytest.fixture
def mock_encoding_worker_config():
"""Mock EncodingWorkerConfig dataclass."""
config = MagicMock()
config.primary_vm = "encoding-worker-b"
config.primary_ip = "34.10.189.118"
config.primary_version = "0.155.3"
config.primary_deployed_at = "2026-03-31T18:10:00Z"
config.secondary_vm = "encoding-worker-a"
config.secondary_ip = "34.57.78.246"
config.secondary_version = "0.155.2"
config.secondary_deployed_at = "2026-03-29T14:00:00Z"
config.last_swap_at = "2026-03-31T18:10:00Z"
config.deploy_in_progress = False
config.deploy_in_progress_since = None
config.last_activity_at = None
return config
class TestSystemStatusPublic:
"""Tests for unauthenticated /api/health/system-status."""
@pytest.mark.asyncio
async def test_returns_all_services(
self, mock_encoding_status, mock_flacfetch_status, mock_separator_status
):
from backend.api.routes.health import system_status
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=mock_encoding_status), \
patch("backend.api.routes.health.check_flacfetch_service_status", new_callable=AsyncMock, return_value=mock_flacfetch_status), \
patch("backend.api.routes.health.check_audio_separator_status", return_value=mock_separator_status), \
patch("backend.api.routes.health.VERSION", "0.155.3"), \
patch("backend.api.routes.health.COMMIT_SHA", "8e2a949a"), \
patch("backend.api.routes.health.PR_NUMBER", "644"), \
patch("backend.api.routes.health.PR_TITLE", "fix: blue-green deploy"), \
patch("backend.api.routes.health.STARTUP_TIME", "2026-03-31T18:10:00Z"):
result = await system_status(auth=None)
assert "services" in result
services = result["services"]
# All 5 services present
assert "frontend" in services
assert "backend" in services
assert "encoder" in services
assert "flacfetch" in services
assert "separator" in services
# Backend has build metadata
backend_svc = services["backend"]
assert backend_svc["version"] == "0.155.3"
assert backend_svc["commit_sha"] == "8e2a949a"
assert backend_svc["pr_number"] == "644"
# Encoder has status
assert services["encoder"]["status"] == "ok"
assert services["encoder"]["version"] == "0.155.3"
# No admin_details without auth
assert "admin_details" not in services["encoder"]
@pytest.mark.asyncio
async def test_offline_service(self, mock_flacfetch_status, mock_separator_status):
from backend.api.routes.health import system_status
offline_encoding = {
"configured": True,
"enabled": True,
"available": False,
"error": "Connection refused",
}
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=offline_encoding), \
patch("backend.api.routes.health.check_flacfetch_service_status", new_callable=AsyncMock, return_value=mock_flacfetch_status), \
patch("backend.api.routes.health.check_audio_separator_status", return_value=mock_separator_status), \
patch("backend.api.routes.health.VERSION", "0.155.3"), \
patch("backend.api.routes.health.COMMIT_SHA", ""), \
patch("backend.api.routes.health.PR_NUMBER", ""), \
patch("backend.api.routes.health.PR_TITLE", ""), \
patch("backend.api.routes.health.STARTUP_TIME", "2026-03-31T18:10:00Z"):
result = await system_status(auth=None)
assert result["services"]["encoder"]["status"] == "offline"
class TestSystemStatusAdmin:
"""Tests for admin-authenticated /api/health/system-status."""
@pytest.mark.asyncio
async def test_admin_gets_bluegreen_details(
self, mock_encoding_status, mock_flacfetch_status, mock_separator_status, mock_encoding_worker_config
):
from backend.api.routes.health import system_status
from backend.services.auth_service import UserType
mock_auth = ("token123", UserType.ADMIN, -1)
mock_manager = MagicMock()
mock_manager.get_config.return_value = mock_encoding_worker_config
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=mock_encoding_status), \
patch("backend.api.routes.health.check_flacfetch_service_status", new_callable=AsyncMock, return_value=mock_flacfetch_status), \
patch("backend.api.routes.health.check_audio_separator_status", return_value=mock_separator_status), \
patch("backend.api.routes.health.VERSION", "0.155.3"), \
patch("backend.api.routes.health.COMMIT_SHA", ""), \
patch("backend.api.routes.health.PR_NUMBER", ""), \
patch("backend.api.routes.health.PR_TITLE", ""), \
patch("backend.api.routes.health.STARTUP_TIME", "2026-03-31T18:10:00Z"), \
patch("backend.api.routes.health._get_encoding_worker_manager", return_value=mock_manager):
result = await system_status(auth=mock_auth)
encoder = result["services"]["encoder"]
assert "admin_details" in encoder
admin = encoder["admin_details"]
assert admin["primary_vm"] == "encoding-worker-b"
assert admin["secondary_vm"] == "encoding-worker-a"
assert admin["last_swap_at"] == "2026-03-31T18:10:00Z"
assert admin["deploy_in_progress"] is False
+4 -4
View File
@@ -56,7 +56,7 @@ class TestSendMagicLinkTenantParams:
assert "Nomad Karaoke" in html_content
assert "Nomad Karaoke" in text_content
# Default URL should be used
assert f"{email_service.frontend_url}/auth/verify" in html_content
assert f"{email_service.frontend_url}/en/auth/verify" in html_content
def test_tenant_url_used_in_magic_link(self, email_service):
"""When tenant_frontend_url is provided, magic link points to tenant domain."""
@@ -70,8 +70,8 @@ class TestSendMagicLinkTenantParams:
html_content = call_args[0][2]
text_content = call_args[0][3]
assert "https://vocalstar.nomadkaraoke.com/auth/verify?token=abc123" in html_content
assert "https://vocalstar.nomadkaraoke.com/auth/verify?token=abc123" in text_content
assert "https://vocalstar.nomadkaraoke.com/en/auth/verify?token=abc123" in html_content
assert "https://vocalstar.nomadkaraoke.com/en/auth/verify?token=abc123" in text_content
# Should NOT contain default URL
assert "gen.nomadkaraoke.com" not in html_content
@@ -124,7 +124,7 @@ class TestSendMagicLinkTenantParams:
html_content = call_args[0][2]
assert subject == "Sign in to Vocal Star"
assert "https://vocalstar.nomadkaraoke.com/auth/verify?token=token123" in html_content
assert "https://vocalstar.nomadkaraoke.com/en/auth/verify?token=token123" in html_content
# Check sender email override was passed through
assert call_args[1]["from_email_override"] == "vocalstar@nomadkaraoke.com"
+109 -1
View File
@@ -621,6 +621,111 @@ class TestPackagingValidation:
assert orchestrator.result.final_karaoke_cdg_zip is None
class TestPackagingTrailingPeriodRegression:
"""Regression test for job 4117228f: title ending with period caused TXT failure.
Root cause: The orchestrator's sanitize_filename() strips trailing periods,
but the CDG generator's internal _sanitize_filename() did not, causing a
filename mismatch between the MP3 inside the CDG ZIP and what TXT expected.
Fix: Pass sanitized artist/title to CDG generator and use returned MP3 path.
"""
@pytest.mark.asyncio
async def test_cdg_packaging_uses_sanitized_artist_title(self):
"""Test that CDG packaging passes sanitized (not raw) artist/title."""
with tempfile.TemporaryDirectory() as temp_dir:
lrc_file = os.path.join(temp_dir, "test.lrc")
audio_file = os.path.join(temp_dir, "test.flac")
with open(lrc_file, "w") as f:
f.write("[00:00.00]Test lyrics")
with open(audio_file, "w") as f:
f.write("dummy audio")
# Title ends with period - this triggered the bug
config = OrchestratorConfig(
job_id="test-job",
artist="KARAOKE",
title="Song Title.", # Trailing period
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path=audio_file,
lrc_file_path=lrc_file,
output_dir=temp_dir,
enable_cdg=True,
cdg_styles={"background_color": "black"},
)
orchestrator = VideoWorkerOrchestrator(config)
with patch.object(orchestrator, "_get_packaging_service") as mock_get:
mock_service = MagicMock()
mock_service.create_cdg_package.return_value = (
f"{temp_dir}/cdg.zip",
f"{temp_dir}/test.mp3",
f"{temp_dir}/test.cdg",
)
mock_get.return_value = mock_service
await orchestrator._run_packaging()
call_kwargs = mock_service.create_cdg_package.call_args[1]
# Artist/title should be sanitized (trailing period stripped)
assert call_kwargs["artist"] == "KARAOKE"
assert call_kwargs["title"] == "Song Title" # No trailing period
@pytest.mark.asyncio
async def test_txt_uses_mp3_path_from_cdg_generation(self):
"""Test that TXT generation uses the actual MP3 path returned by CDG, not a constructed one."""
with tempfile.TemporaryDirectory() as temp_dir:
lrc_file = os.path.join(temp_dir, "test.lrc")
audio_file = os.path.join(temp_dir, "test.flac")
# Create a real MP3 file at the path CDG would return
mp3_from_cdg = os.path.join(temp_dir, "actual_cdg_output.mp3")
with open(lrc_file, "w") as f:
f.write("[00:00.00]Test lyrics")
with open(audio_file, "w") as f:
f.write("dummy audio")
with open(mp3_from_cdg, "w") as f:
f.write("dummy mp3")
config = OrchestratorConfig(
job_id="test-job",
artist="KARAOKE",
title="Song Title.", # Trailing period
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path=audio_file,
lrc_file_path=lrc_file,
output_dir=temp_dir,
enable_cdg=True,
enable_txt=True,
cdg_styles={"background_color": "black"},
)
orchestrator = VideoWorkerOrchestrator(config)
with patch.object(orchestrator, "_get_packaging_service") as mock_get:
mock_service = MagicMock()
# CDG returns a path that differs from constructed path
mock_service.create_cdg_package.return_value = (
f"{temp_dir}/cdg.zip",
mp3_from_cdg, # Actual MP3 path from CDG
f"{temp_dir}/test.cdg",
)
mock_service.create_txt_package.return_value = (
f"{temp_dir}/txt.zip",
f"{temp_dir}/test.txt",
)
mock_get.return_value = mock_service
await orchestrator._run_packaging()
# TXT should have been called with the actual CDG MP3 path
mock_service.create_txt_package.assert_called_once()
txt_call_kwargs = mock_service.create_txt_package.call_args[1]
assert txt_call_kwargs["mp3_file"] == mp3_from_cdg
class TestVideoWorkerOrchestratorEncoding:
"""Test encoding stage."""
@@ -1256,6 +1361,7 @@ class TestCreateOrchestratorConfigFromJob:
job.gdrive_folder_id = None
job.keep_brand_code = None
job.existing_instrumental_gcs_path = None
job.file_urls = {'screens': {'title_png': 'jobs/test-123/screens/title.png', 'end_png': 'jobs/test-123/screens/end.png'}}
config = create_orchestrator_config_from_job(
job=job,
@@ -1269,7 +1375,7 @@ class TestCreateOrchestratorConfigFromJob:
assert config.title == "Test Title"
assert config.enable_cdg is True
assert config.enable_youtube_upload is True
assert config.title_video_path == "/tmp/test/Test Artist - Test Title (Title).mov"
assert config.title_video_path == "/tmp/test/Test Artist - Test Title (Title).png"
assert config.instrumental_audio_path == "/tmp/test/Test Artist - Test Title (Instrumental Clean).flac"
def test_create_config_from_job_with_existing_instrumental(self):
@@ -1290,6 +1396,7 @@ class TestCreateOrchestratorConfigFromJob:
job.gdrive_folder_id = None
job.keep_brand_code = None
job.existing_instrumental_gcs_path = "gs://bucket/instrumental.mp3"
job.file_urls = {'screens': {'title_png': 'screens/title.png', 'end_png': 'screens/end.png'}}
config = create_orchestrator_config_from_job(
job=job,
@@ -1329,6 +1436,7 @@ class TestCreateOrchestratorConfigFromJob:
job.gdrive_folder_id = None
job.keep_brand_code = None
job.existing_instrumental_gcs_path = None
job.file_urls = {'screens': {'title_png': 'screens/title.png', 'end_png': 'screens/end.png'}}
config = create_orchestrator_config_from_job(
job=job,
+66 -51
View File
@@ -179,48 +179,48 @@ class TestLyricsWorker:
return storage
@pytest.mark.asyncio
async def test_upload_lyrics_results_requires_job(self, mock_job_manager, mock_storage, mock_job):
"""Test that upload_lyrics_results correctly fetches job for artist/title.
This test would have caught the UnboundLocalError bug where job was used
before being defined.
async def test_upload_lyrics_results_finds_corrections_by_scan(self, mock_job_manager, mock_storage, mock_job):
"""Test that upload_lyrics_results finds corrections JSON by scanning the directory.
The function scans for files ending in '(Lyrics Corrections).json' rather than
reconstructing filenames from job.artist/title, since those may change mid-processing
(e.g. admin updates artist name while lyrics worker is running).
"""
with patch('backend.workers.lyrics_worker.JobManager', return_value=mock_job_manager), \
patch('backend.workers.lyrics_worker.StorageService', return_value=mock_storage):
from backend.workers.lyrics_worker import upload_lyrics_results
with tempfile.TemporaryDirectory() as temp_dir:
# Create mock lyrics directory and files
lyrics_dir = os.path.join(temp_dir, "lyrics")
os.makedirs(lyrics_dir)
# Create test LRC file
lrc_path = os.path.join(lyrics_dir, "ABBA - Waterloo (Karaoke).lrc")
with open(lrc_path, 'w') as f:
f.write("[00:00.00]Test lyrics\n")
# Create corrections JSON
corrections_path = os.path.join(lyrics_dir, "ABBA - Waterloo (Lyrics Corrections).json")
# Use a different artist than what's in the job to simulate mid-run rename
corrections_path = os.path.join(lyrics_dir, "OldArtist - Waterloo (Lyrics Corrections).json")
with open(corrections_path, 'w') as f:
json.dump({"lines": [], "corrections": []}, f)
transcription_result = {
"lrc_filepath": lrc_path,
"corrections_filepath": corrections_path
}
# This should NOT raise UnboundLocalError
await upload_lyrics_results(
"test123",
temp_dir,
transcription_result,
mock_storage,
"test123",
temp_dir,
transcription_result,
mock_storage,
mock_job_manager
)
# Verify job was fetched
mock_job_manager.get_job.assert_called_with("test123")
# Verify corrections file was found and uploaded as corrections.json
upload_calls = mock_storage.upload_file.call_args_list
corrections_uploads = [c for c in upload_calls if 'corrections.json' in str(c)]
assert len(corrections_uploads) == 1
@pytest.mark.asyncio
async def test_upload_lyrics_results_uploads_lrc_file(self, mock_job_manager, mock_storage, mock_job):
@@ -281,53 +281,68 @@ class TestLyricsWorker:
)
@pytest.mark.asyncio
async def test_upload_lyrics_results_uses_artist_title_from_job(self, mock_job_manager, mock_storage, mock_job):
"""Test that upload_lyrics_results correctly uses job.artist and job.title.
This test specifically validates the bug fix where job was not defined
when accessing job.artist and job.title for reference file lookups.
"""
async def test_upload_lyrics_results_raises_when_no_corrections(self, mock_job_manager, mock_storage, mock_job):
"""Test that upload_lyrics_results raises when no corrections file exists at all."""
from backend.workers.lyrics_worker import upload_lyrics_results
import json
with tempfile.TemporaryDirectory() as temp_dir:
lyrics_dir = os.path.join(temp_dir, "lyrics")
os.makedirs(lyrics_dir)
# Create LRC file
lrc_path = os.path.join(lyrics_dir, "test.lrc")
with open(lrc_path, 'w') as f:
f.write("[00:00.00]Test\n")
# Create required corrections.json file
corrections_path = os.path.join(lyrics_dir, "corrections.json")
# No corrections file at all
transcription_result = {"lrc_filepath": lrc_path}
with pytest.raises(Exception, match="No corrections JSON found"):
await upload_lyrics_results(
"test123", temp_dir, transcription_result,
mock_storage, mock_job_manager
)
@pytest.mark.asyncio
async def test_upload_lyrics_results_finds_reference_and_uncorrected_by_scan(self, mock_job_manager, mock_storage, mock_job):
"""Test that upload_lyrics_results finds reference and uncorrected files by scanning.
Files are found by suffix pattern, not by reconstructing from job.artist/title,
so mid-processing artist name changes don't break the upload.
"""
from backend.workers.lyrics_worker import upload_lyrics_results
import json
with tempfile.TemporaryDirectory() as temp_dir:
lyrics_dir = os.path.join(temp_dir, "lyrics")
os.makedirs(lyrics_dir)
lrc_path = os.path.join(lyrics_dir, "test.lrc")
with open(lrc_path, 'w') as f:
f.write("[00:00.00]Test\n")
corrections_path = os.path.join(lyrics_dir, "SomeArtist - SomeTitle (Lyrics Corrections).json")
with open(corrections_path, 'w') as f:
json.dump({"corrected_segments": []}, f)
# Create a reference lyrics file using the job's artist/title
ref_path = os.path.join(lyrics_dir, f"{mock_job.artist} - {mock_job.title} (Lyrics Genius).txt")
# Reference and uncorrected files with arbitrary artist name
ref_path = os.path.join(lyrics_dir, "SomeArtist - SomeTitle (Lyrics Genius).txt")
with open(ref_path, 'w') as f:
f.write("Reference lyrics content\n")
# Create uncorrected transcription file using job's artist/title
uncorrected_path = os.path.join(lyrics_dir, f"{mock_job.artist} - {mock_job.title} (Lyrics Uncorrected).txt")
uncorrected_path = os.path.join(lyrics_dir, "SomeArtist - SomeTitle (Lyrics Uncorrected).txt")
with open(uncorrected_path, 'w') as f:
f.write("Uncorrected transcription\n")
transcription_result = {"lrc_filepath": lrc_path}
# This should NOT raise UnboundLocalError for 'job'
await upload_lyrics_results(
"test123", temp_dir, transcription_result,
mock_storage, mock_job_manager
)
# Verify job was fetched to get artist/title
mock_job_manager.get_job.assert_called_with("test123")
# Verify files were uploaded (the reference and uncorrected files exist)
# Verify files were uploaded: LRC + corrections + genius ref + uncorrected = 4
upload_calls = mock_storage.upload_file.call_args_list
assert len(upload_calls) >= 2 # LRC + at least one reference or uncorrected
assert len(upload_calls) == 4
@pytest.mark.asyncio
async def test_process_lyrics_transcription_marks_failed_on_error(self, mock_job_manager, mock_storage):
+338
View File
@@ -0,0 +1,338 @@
{
"auth": {
"unknownService": "خدمة غير معروفة: {service}",
"invalidCredentials": "تحتاج الخدمات التالية إلى إعادة تفويض: {services}",
"validCredentials": "جميع بيانات الاعتماد المطلوبة صالحة",
"youtubeAuthInstructions": "قم بزيارة {verification_url} وأدخل الرمز: {user_code}",
"youtubeAuthStartFailed": "فشل بدء مصادقة جهاز YouTube: {error}",
"gdriveLinkInstructions": "قم بزيارة {verification_url} وأدخل الرمز: {user_code}",
"gdriveAuthStartFailed": "فشل بدء مصادقة جهاز Google Drive: {error}",
"discordAlertNotConfigured": "لم يتم إعداد الويب هوك (webhook) لتنبيهات Discord"
},
"jobs": {
"created": "تم إنشاء المهمة بنجاح. بدأت المعالجة.",
"authError": "خطأ في المصادقة: لا تتوفر هوية مستخدم",
"noDefaultTheme": "لم يتم إعداد سمة افتراضية. يرجى الاتصال بالدعم أو تحديد theme_id.",
"notFound": "المهمة غير موجودة",
"noPermissionAccess": "ليس لديك إذن للوصول إلى هذه المهمة",
"noPermissionEdit": "ليس لديك إذن لتعديل هذه المهمة",
"noPermissionDelete": "ليس لديك إذن لحذف هذه المهمة",
"noPermissionModify": "ليس لديك إذن لتعديل هذه المهمة",
"notCompleted": "يمكن تعديل المهام المكتملة فقط. الحالة الحالية: {status}",
"alreadyBeingEdited": "هذه المهمة قيد التعديل بالفعل (تم حذف المخرجات مسبقًا)",
"cleanupFailed": "فشل التنظيف لـ {services}. لم يتم تعديل المهمة. يرجى المحاولة مرة أخرى أو الاتصال بالدعم.",
"reopened": "تمت إعادة فتح المقطع الصوتي للتعديل. تمت إزالة المخرجات السابقة.",
"invalidDatetimeFormat": "تنسيق {field} غير صالح: {value}",
"listError": "خطأ في عرض المهام: {error}",
"deleteError": "خطأ في حذف المهمة {job_id}: {error}",
"deletionPreview": "أضف &confirm=true لتنفيذ الحذف",
"deletionRequiresFilters": "مطلوب عامل تصفية واحد على الأقل (environment، client_id، status، created_before)",
"bulkDeleteError": "خطأ في الحذف الجماعي للمهام: {error}",
"reviewNotReady": "المهمة ليست جاهزة للمراجعة (الحالة الحالية: {status})",
"correctionsUnavailable": "بيانات التصحيحات غير متوفرة",
"audioUnavailable": "الصوت غير متوفر للمراجعة",
"reviewCannotStart": "لا يمكن بدء المراجعة",
"jobNotInReviewState": "المهمة ليست في حالة المراجعة (الحالة الحالية: {status})",
"correctionsProcessing": "تم حفظ التصحيحات. قم باستدعاء /complete-review عند الانتهاء.",
"editLogSaveFailed": "خطأ في حفظ سجل التعديل للمهمة {job_id}: {error}",
"stemsMissing": "تفتقد المهمة إلى المسارات المطلوبة (instrumental_clean و/أو backing_vocals)",
"customInstrumentalFailed": "خطأ في إنشاء مسار موسيقي مخصص للمهمة {job_id}: {error}",
"audioProcessingFailed": "فشلت معالجة الملف الصوتي: {error}",
"durationMismatch": "عدم تطابق في المدة: الملف المرفوع مدته {upload_duration} ثانية ولكن الصوت الأصلي مدته {original_duration} ثانية. يجب أن يكون المسار الموسيقي بالضبط {original_duration} ثانية (±0.5 ثانية).",
"reviewNotInState": "المهمة ليست في حالة المراجعة (الحالة الحالية: {status})",
"noLyricsDetected": "لا يمكن إكمال المراجعة: لم يتم اكتشاف كلمات في الصوت. يمكن أن يحدث هذا عندما لا يحتوي الصوت المدخل على غناء (مثل مسار كاريوكي أو موسيقى فقط). يمكنك الرجوع ولصق الكلمات يدويًا باستخدام 'استبدال الكل'، أو إلغاء هذه المهمة والمحاولة مرة أخرى باستخدام ملف صوتي يحتوي على غناء.",
"reviewCompleteStartRendering": "اكتملت المراجعة. بدأ تصيير الفيديو.",
"reviewCompleteError": "خطأ في إكمال المراجعة للمهمة {job_id}: {error}",
"instrumentalSelectionRequired": "مطلوب instrumental_selection. يجب أن يكون 'clean' أو 'with_backing'.",
"invalidInstrumentalSelection": "instrumental_selection غير صالح. يجب أن يكون واحدًا من: {valid_selections}",
"instrumentalSelected": "تم تحديد المسار الموسيقي. بدأ إنشاء الفيديو.",
"instrumentalSelectionError": "خطأ في تحديد المسار الموسيقي للمهمة {job_id}: {error}",
"downloadUrlsError": "خطأ في الحصول على روابط التنزيل: {error}"
},
"review": {
"jobNotFound": "المهمة غير موجودة",
"reviewNotReady": "المهمة ليست جاهزة للمراجعة (الحالة الحالية: {status})",
"correctionsNotFound": "لم يتم العثور على بيانات التصحيحات. قد لا تكون معالجة الكلمات مكتملة.",
"correctionsLoadFailed": "خطأ في تحميل التصحيحات: {error}",
"audioNotFound": "لم يتم العثور على الملف الصوتي",
"audioServeError": "خطأ في تقديم الصوت: {error}",
"instrumentalSelectionRequired": "مطلوب instrumental_selection. يجب أن يكون 'clean' أو 'with_backing'.",
"invalidInstrumentalSelection": "instrumental_selection غير صالح. يجب أن يكون واحدًا من: {valid_selections}",
"reviewCompletedError": "خطأ في إكمال المراجعة: {error}",
"handlersUpdateNotImplemented": "لم يتم تنفيذ تحديثات المعالج بعد",
"lyricsAddError": "فشلت إضافة الكلمات: {error}",
"lyricsAddInvalidRequest": "طلب إضافة كلمات غير صالح: {error}",
"lyricsSearchError": "فشل البحث عن الكلمات: {error}",
"lyricsSearchInvalidRequest": "طلب بحث عن كلمات غير صالح: {error}",
"lyricsSearchNoResults": "لم يتم العثور على كلمات مطابقة من أي مزود",
"previewVideoGenerationError": "فشل إنشاء فيديو المعاينة: {error}",
"previewVideoNotFound": "لم يتم العثور على فيديو المعاينة",
"previewVideoStreamError": "خطأ في بث فيديو المعاينة: {error}",
"annotationSaveError": "خطأ في حفظ التعليقات التوضيحية: {error}",
"waveformGenerationError": "خطأ في إنشاء بيانات الشكل الموجي: {error}",
"waveformNoAudio": "لا يوجد صوت متاح للشكل الموجي",
"sessionSaveError": "بيانات التصحيح مطلوبة"
},
"audioSearch": {
"notEnabled": "البحث الصوتي غير مفعل لهذا المستأجر",
"disabled": "البحث الصوتي غير متوفر",
"downloadError": "فشل التنزيل للمهمة {job_id}: {error}",
"jobNotFound": "لم يتم العثور على المهمة {job_id}",
"noSearchResults": "لا تتوفر نتائج بحث",
"invalidSelectionIndex": "فهرس تحديد غير صالح {selection_index}. النطاق الصالح: 0-{max}",
"selectionError": "خطأ أثناء تحديد الصوت للمهمة {job_id}: {error}",
"youtubeDownloadError": "فشل تنزيل YouTube: {error}",
"torrentDownloadError": "لا يمكن التنزيل من {source} بدون خدمة flacfetch عن بُعد. قم بإعداد FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "لا يتوفر source_id أو remote_search_id لتنزيل {source}",
"remoteDownloadCompleteNoPath": "اكتمل التنزيل عن بُعد ولكن لم يتم إرجاع مسار الملف",
"spotifyDownloadError": "لا يمكن التنزيل من Spotify بدون خدمة flacfetch عن بُعد. قم بإعداد FLACFETCH_API_URL.",
"genericDownloadError": "نوع مصدر غير معروف: {source}، جاري محاولة التنزيل العام",
"jobNotFoundDuringDownload": "لم يتم العثور على المهمة {job_id} أثناء التنزيل في الخلفية",
"selectAudioError": "خطأ في تحديد الصوت للمهمة {job_id}: {error}",
"searchAudioError": "خطأ في البحث عن الصوت: {error}",
"searchCreatedSuccessfully": "تم إنشاء المهمة. جاري البحث عن الصوت...",
"autoDownloadStarted": "تم تحديد أفضل نتيجة تلقائيًا. جاري بدء التنزيل..."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
"magicLinkSent": "إذا كان هذا البريد الإلكتروني مسجلاً، فستتلقى رابط تسجيل الدخول قريبًا.",
"emailServiceNotConfigured": "خدمة البريد الإلكتروني غير متوفرة. يرجى الاتصال بالدعم.",
"emailDomainNotAllowed": "نطاق البريد الإلكتروني غير مسموح به لهذا المستأجر",
"invalidToken": "رمز غير صالح",
"verifyError": "فشل التحقق: {message}",
"magicLinkSuccess": "تم تسجيل الدخول بنجاح",
"logoutSuccess": "تم تسجيل الخروج بنجاح",
"userNotFound": "المستخدم غير موجود",
"creditPackagesError": "خطأ في تحميل باقات الأرصدة: {error}",
"stripeSendError": "خطأ في إرسال رابط الدفع الخاص بـ Stripe: {error}",
"stripeWebhookProcessingError": "خطأ في معالجة الويب هوك (webhook) الخاص بـ Stripe: {error}",
"feedbackSaveError": "خطأ في حفظ الملاحظات: {error}",
"feedbackNotEligible": "المستخدم غير مؤهل لتقديم الملاحظات"
},
"fileUpload": {
"invalidTheme": "السمة غير موجودة: {theme_id}. استخدم GET /api/themes لعرض السمات المتاحة.",
"uploadSuccess": "تم رفع الملف بنجاح. بدأت المعالجة.",
"uploadError": "خطأ في رفع الملف: {error}",
"urlDownloadError": "خطأ في التنزيل من الرابط: {error}",
"invalidContentType": "نوع محتوى غير صالح: {content_type}",
"fileSizeError": "الملف كبير جدًا: {size}. الحد الأقصى: {max_size}",
"invalidFileType": "نوع ملف غير صالح: {file_type}",
"multipleAudioFilesNotAllowed": "يمكن رفع ملف صوتي واحد فقط",
"noAudioFileProvided": "لم يتم توفير ملف صوتي",
"urlCreationSuccess": "تم إنشاء المهمة. تم إنشاء روابط الرفع.",
"urlCreationError": "خطأ في إنشاء المهمة باستخدام روابط الرفع: {error}",
"uploadsCompleteSuccess": "اكتمل الرفع. بدأت المعالجة.",
"uploadsCompleteError": "خطأ في إكمال عمليات الرفع: {error}",
"noUploadedFiles": "لم يتم تحديد ملفات مرفوعة",
"styleUploadUrlsSuccess": "تم إنشاء روابط رفع النمط.",
"styleUploadsCompleteSuccess": "تم تحديث ملفات النمط. تمت إعادة تشغيل المعالجة.",
"styleUploadsCompleteError": "خطأ في إكمال عمليات رفع النمط: {error}"
},
"catalog": {
"rateLimitExceeded": "تم تجاوز حد الطلبات. الحد الأقصى {max_requests} طلبات كتالوج في الدقيقة.",
"catalogSearchError": "خطأ في البحث في الكتالوج: {error}",
"communityCheckError": "خطأ في التحقق من إصدارات المجتمع: {error}"
},
"themes": {
"themesLoadError": "فشل تحميل السمات",
"themeNotFound": "السمة غير موجودة: {theme_id}",
"themeLoadError": "فشل تحميل السمة",
"previewNotAvailable": "لا تتوفر معاينة للسمة: {theme_id}",
"previewLoadError": "فشل تحميل معاينة السمة",
"youtubeDescriptionNotFound": "السمة غير موجودة: {theme_id}",
"youtubeDescriptionLoadError": "فشل تحميل وصف YouTube"
},
"tenant": {
"assetNotFound": "الأصل غير موجود"
},
"push": {
"disabled": "الإشعارات الفورية غير مفعلة",
"userEmailNotAvailable": "البريد الإلكتروني للمستخدم غير متوفر",
"missingEncryptionKeys": "المفاتيح المطلوبة مفقودة (p256dh، auth)",
"subscriptionSaveFailed": "فشل حفظ الاشتراك",
"subscriptionRegistered": "تم تسجيل اشتراك الإشعارات الفورية بنجاح",
"subscriptionNotFound": "تمت إزالة الاشتراك (أو لم يتم العثور عليه)",
"subscriptionRemoved": "تمت إزالة اشتراك الإشعارات الفورية بنجاح",
"testNotificationSent": "تم إرسال إشعار اختباري إلى {sent_count} جهاز/أجهزة"
},
"pushNotifications": {
"reviewLyricsTitle": "مراجعة الكلمات",
"reviewLyricsBody": "\"{title}\" للفنان {artist} تحتاج إلى مراجعة الكلمات",
"selectInstrumentalTitle": "تحديد المسار الموسيقي",
"selectInstrumentalBody": "\"{title}\" للفنان {artist} تحتاج إلى تحديد المسار الموسيقي",
"videoReadyTitle": "الفيديو جاهز!",
"videoReadyBody": "فيديو الكاريوكي الخاص بك لأغنية \"{title}\" للفنان {artist} جاهز للتنزيل"
},
"admin": {
"invalidDomainFormat": "تنسيق النطاق غير صالح",
"domainAddedToBl": "تمت إضافة النطاق '{domain}' إلى قائمة حظر النطاقات المؤقتة",
"domainNotFoundInBl": "لم يتم العثور على النطاق في قائمة الحظر",
"domainRemovedFromBl": "تمت إزالة النطاق '{domain}' من قائمة حظر النطاقات المؤقتة",
"domainAddedToAllowlist": "تمت إضافة النطاق '{domain}' إلى قائمة السماح",
"domainNotFoundInAllowlist": "لم يتم العثور على النطاق في قائمة السماح",
"domainRemovedFromAllowlist": "تمت إزالة النطاق '{domain}' من قائمة السماح",
"syncComplete": "تمت مزامنة {external_count} نطاقات خارجية (تمت إضافة {added}، وتمت إزالة {removed})",
"invalidEmailFormat": "تنسيق البريد الإلكتروني غير صالح",
"emailAddedToBl": "تمت إضافة البريد الإلكتروني '{email}' إلى قائمة رسائل البريد الإلكتروني المحظورة",
"emailNotFoundInBl": "لم يتم العثور على البريد الإلكتروني في قائمة الحظر",
"emailRemovedFromBl": "تمت إزالة البريد الإلكتروني '{email}' من قائمة رسائل البريد الإلكتروني المحظورة",
"invalidIPAddress": "عنوان IP غير صالح",
"ipAddedToBl": "تمت إضافة IP '{ip_address}' إلى قائمة عناوين IP المحظورة",
"ipNotFoundInBl": "لم يتم العثور على IP في قائمة الحظر",
"ipRemovedFromBl": "تمت إزالة IP '{ip_address}' من قائمة عناوين IP المحظورة",
"youtubeUploadNotFound": "الرفع غير موجود أو ليس في حالة قابلة لإعادة المحاولة للمهمة {job_id}",
"youtubeUploadQueuedForRetry": "تم وضع رفع YouTube للمهمة {job_id} في قائمة الانتظار لإعادة المحاولة",
"youtubeQueueProcessingStarted": "بدأت معالجة قائمة انتظار YouTube في الخلفية"
},
"rateLimits": {
"configNotFound": "لم يتم العثور على إعداد حد الطلبات: {config_id}",
"configUpdateError": "خطأ في تحديث إعداد حد الطلبات: {error}"
},
"errors": {
"insufficientCredits": "أرصدة غير كافية لهذه العملية",
"insufficientCreditsBuyUrl": "/#pricing"
},
"emails": {
"magicLink": {
"subject": "تسجيل الدخول إلى {brand_name}",
"greeting": "مرحباً،",
"signInPrompt": "انقر على الزر أدناه لتسجيل الدخول إلى {brand_name}:",
"signInButton": "تسجيل الدخول",
"expiryWarning": "تنتهي صلاحية هذا الرابط خلال 15 دقيقة ويمكن استخدامه مرة واحدة فقط.",
"fallbackLink": "إذا لم يعمل الزر، انسخ هذا الرابط والصقه في متصفحك:",
"ignoreNote": "إذا لم تطلب هذا البريد الإلكتروني، يمكنك تجاهله بأمان."
},
"welcome": {
"subject": "مرحباً بك في Nomad Karaoke!",
"welcomeGreeting": "مرحباً بك في Nomad Karaoke!",
"turnAnySong": "حوّل أي أغنية إلى فيديو كاريوكي احترافي في دقائق.",
"freeCreditsLabel": "أرصدة مجانية",
"freeCreditsNote": "كل رصيد ينشئ فيديو كاريوكي احترافي واحد",
"howItWorks": "إليك كيف يعمل الأمر:",
"step1Title": "1. ابحث عن أغنية",
"step1Desc": "أدخل اسم الفنان وعنوان الأغنية، وسنجد لك صوتاً عالي الجودة.",
"step2Title": "2. نظامنا يقوم بسحره",
"step2Desc": "نقوم بفصل الغناء، ونسخ الكلمات، ومزامنة كل شيء بشكل مثالي.",
"step3Title": "3. المراجعة والتخصيص",
"step3Desc": "قم بضبط الكلمات إذا لزم الأمر، واختر المسار الموسيقي الخاص بك.",
"step4Title": "4. احصل على الفيديو الخاص بك",
"step4Desc": "قم بتنزيل فيديو الكاريوكي بدقة 4K أو ارفعه مباشرة إلى YouTube.",
"feedbackBonus": "أكمل مقطعي فيديو واكسب رصيدين مجانيين إضافيين من خلال مشاركة ملاحظاتك!",
"getStartedButton": "ابدأ الآن"
},
"creditsAdded": {
"subject": "تمت إضافة {credits} أرصدة إلى حساب Nomad Karaoke الخاص بك",
"greatNews": "أخبار رائعة!",
"creditsAddedMessage": "تمت إضافة {credits} أرصدة إلى حسابك.",
"yourBalance": "رصيدك:",
"credits": "أرصدة",
"eachCreditLets": "يتيح لك كل رصيد إنشاء فيديو كاريوكي احترافي واحد مع:",
"featureVocalSeparation": "فصل الغناء/الموسيقى المدعوم بالذكاء الاصطناعي",
"featureLyrics": "كلمات متزامنة مع توقيت على مستوى الكلمة",
"feature4k": "إخراج فيديو بدقة 4K",
"featureYoutube": "الرفع على YouTube",
"createButton": "أنشئ كاريوكي الآن"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (فيديو الكاريوكي الخاص بك جاهز!)",
"subject": "{artist} - {title} (فيديو الكاريوكي الخاص بك جاهز!)",
"subjectFallback": "فيديو الكاريوكي الخاص بك جاهز!"
},
"youtubeUpload": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (الرفع على YouTube جاهز!)",
"subject": "{artist} - {title} (الرفع على YouTube جاهز!)",
"subjectFallback": "الرفع على YouTube جاهز!"
},
"actionReminder": {
"lyricsSubject": "إجراء مطلوب: مراجعة الكلمات لأغنية {artist} - {title}",
"lyricsSubjectFallback": "إجراء مطلوب: مراجعة الكلمات",
"instrumentalSubject": "إجراء مطلوب: تحديد المسار الموسيقي لأغنية {artist} - {title}",
"instrumentalSubjectFallback": "إجراء مطلوب: تحديد المسار الموسيقي",
"audioEditSubject": "إجراء مطلوب لأغنية {artist} - {title}",
"audioEditSubjectFallback": "إجراء مطلوب",
"alertHeading": "فيديو الكاريوكي الخاص بك يحتاج إلى تدخل منك!"
},
"reviewReminder": {
"subject": "تذكير: فيديو الكاريوكي الخاص بك في انتظار المراجعة — {artist} - {title}",
"subjectFallback": "تذكير: فيديو الكاريوكي الخاص بك في انتظار المراجعة",
"alertHeading": "فيديو الكاريوكي الخاص بك في انتظارك!",
"reminderIntro": "مجرد تذكير ودي بأن فيديو الكاريوكي الخاص بك{song_name} جاهز للمراجعة.",
"reviewButton": "راجع الفيديو الخاص بك",
"reviewInstructions": "أثناء المراجعة، يمكنك التحقق من صحة الكلمات واختيار المسار الموسيقي المفضل لديك. يستغرق الأمر عادة بضع دقائق فقط!",
"helpOffer": "إذا واجهت أي مشكلة في عملية المراجعة، فقط قم بالرد على هذا البريد الإلكتروني وسأكون سعيداً بمساعدتك.",
"expiryWarning": "يرجى ملاحظة: إذا لم تكتمل المراجعة خلال الـ 24 ساعة القادمة، فستنتهي صلاحية المهمة تلقائياً وسيتم استرداد رصيدك."
},
"reviewExpired": {
"subject": "انتهت صلاحية فيديو الكاريوكي الخاص بك — {artist} - {title}",
"subjectFallback": "انتهت صلاحية فيديو الكاريوكي الخاص بك",
"cancelNotice": "تم إلغاء فيديو الكاريوكي الخاص بك{song_name} تلقائياً لأنه لم يتم إكمال المراجعة خلال 48 ساعة.",
"refundNotice": "لا تقلق — تم استرداد رصيدك! رصيدك الحالي هو {credits_balance} {credits_word}.",
"creditSingular": "رصيد",
"creditPlural": "أرصدة",
"createNewPrompt": "يمكنك إنشاء فيديو كاريوكي جديد في أي وقت باستخدام أرصدتك:",
"createButton": "إنشاء فيديو جديد",
"helpOffer": "إذا واجهت أي مشكلة في عملية المراجعة أو احتجت إلى مساعدة، فقط قم بالرد على هذا البريد الإلكتروني — يسعدني أن أساعدك!"
},
"creditDenied": {
"subject": "بخصوص أرصدة Nomad Karaoke المجانية الخاصة بك",
"greeting": "مرحباً،",
"thankYou": "شكراً لتسجيلك في Nomad Karaoke!",
"deniedMessage": "للأسف، لم نتمكن من منحك {credit_type} المجانية هذه المرة. اكتشف نظامنا أنماطاً تشير إلى أن هذا قد لا يكون حسابك الأول معنا، وكل مهمة إنشاء كاريوكي تكلفنا أموالاً حقيقية في الحوسبة السحابية ورسوم واجهة برمجة التطبيقات.",
"mistakeNote": "نحن نتفهم تماماً إذا كان هذا خطأ! إذا كنت مستخدماً جديداً حقيقياً، يرجى الرد على هذا البريد الإلكتروني وإخبار أندرو (المؤسس). لقد قام ببناء هذه الخدمة ويسعده منحك بعض الأرصدة المجانية لتجربتها — كل ما يطلبه هو أن تقدم ملاحظات صادقة حول التجربة في المقابل.",
"buyPrompt": "إذا كنت ترغب في البدء على الفور، يمكنك أيضاً شراء أرصدة:",
"buyButton": "شراء أرصدة",
"costNote": "نحن نحافظ على انخفاض التكاليف حتى نتمكن من تقديم الخدمة بأسعار معقولة، مما يعني أننا بحاجة إلى توخي الحذر بشأن إساءة استخدام الأرصدة المجانية. شكراً لتفهمك!",
"welcomeCredits": "أرصدة الترحيب",
"feedbackCredits": "أرصدة مكافأة الملاحظات"
},
"madeForYouConfirmation": {
"subject": "تم تأكيد الطلب: {artist} - {title} | Nomad Karaoke",
"thankYou": "شكراً لطلبك!",
"orderDetails": "تفاصيل الطلب",
"orderId": "رقم الطلب:",
"artist": "الفنان:",
"title": "العنوان:",
"yourNotes": "ملاحظاتك:",
"deliveryTime": "سيقوم فريقنا بإنشاء فيديو الكاريوكي المخصص لك خلال {hours} ساعة.",
"deliveryNotice": "ستتلقى رسالة بريد إلكتروني تحتوي على روابط التنزيل بمجرد أن يصبح الفيديو جاهزاً.",
"noAction": "لا يلزم اتخاذ أي إجراء — استرخِ وسنتولى نحن كل شيء!"
},
"shared": {
"footerHelp": "إذا كان هناك أي شيء غير مثالي، فقط قم بالرد على هذا البريد الإلكتروني وسأقوم بإصلاحه!"
},
"templates": {
"jobCompletion": {
"greeting": "مرحباً {name}،",
"thanks": "شكراً لطلبك!",
"youtubeLink": "إليك رابط فيديو الكاريوكي المنشور على YouTube:",
"dropboxIntro": "إليك مجلد Dropbox الذي يحتوي على جميع الملفات النهائية والملفات المصدرية، بما في ذلك:",
"fileList": "- \"(Final Karaoke Lossless).mkv\": فيديو كاريوكي مدمج بدقة 4K H264 مع صوت FLAC بدون فقدان الجودة\n- \"(Final Karaoke).mp4\": فيديو كاريوكي مدمج مع شاشة العنوان/النهاية بدقة 4K H264/AAC\n- \"(Final Karaoke 720p).mp4\": فيديو كاريوكي مدمج بدقة 720p H264/AAC (ملف أصغر للأنظمة القديمة)\n- \"(With Vocals).mp4\": فيديو للغناء معه بدقة 4K H264/AAC مع الغناء الأصلي\n- \"(Karaoke).mov\": إخراج فيديو كاريوكي من MidiCo (بدون شاشة العنوان/النهاية)\n- \"(Title).mov\"/\"(End).mov\": مقاطع فيديو لبطاقة العنوان وشاشة النهاية\n- \"(Final Karaoke CDG).zip\": تنسيق CDG+MP3 لأنظمة الكاريوكي القديمة/التجارية\n- \"(Final Karaoke TXT).zip\": تنسيق TXT+MP3 لـ Power Karaoke\n- stems/*.flac: مسارات صوتية وغنائية منفصلة متنوعة بتنسيق بدون فقدان الجودة\n- lyrics/*.txt: كلمات الأغنية من مصادر مختلفة بتنسيق نص عادي",
"fixOffer": "أخبرني إذا كان هناك أي شيء غير مثالي وسأقوم بتعديله / إصلاحه بكل سرور، أو إذا كنت بحاجة إليه بأي تنسيق آخر، فربما يمكنني تحويله لك!",
"feedbackRequest": "إذا كان لديك دقيقة، سأقدر حقاً ملاحظاتك (يستغرق الأمر دقيقتين):",
"signOff": "شكراً مرة أخرى وأتمنى لك يوماً سعيداً!\n- أندرو",
"youtubeQueued": "تم وضع الرفع الخاص بك على YouTube في قائمة الانتظار وستتم معالجته تلقائياً. ستتلقى رسالة بريد إلكتروني للمتابعة تحتوي على الرابط قريباً."
},
"actionLyrics": {
"greeting": "مرحباً {name}،",
"ready": "فيديو الكاريوكي الخاص بك لأغنية \"{artist} - {title}\" جاهز للمراجعة!",
"instructions": "قام نظامنا بنسخ الكلمات ومزامنتها، ولكنها قد تحتاج إلى بعض التصحيحات. ستتمكن أيضاً من تحديد المسار الموسيقي المفضل لديك (مع أو بدون غناء خلفي).",
"reviewPrompt": "يرجى مراجعة كلماتك وتحديد مسار موسيقي:",
"duration": "يستغرق هذا عادة بضع دقائق فقط.",
"signOff": "شكراً!\n- أندرو"
},
"actionInstrumental": {
"greeting": "مرحباً {name}،",
"almostDone": "فيديو الكاريوكي الخاص بك لأغنية \"{artist} - {title}\" على وشك الانتهاء!",
"instructions": "لقد قمنا بفصل الصوت إلى إصدارات مختلفة. يرجى تحديد المسار الموسيقي الذي ترغب في استخدامه للفيديو النهائي.",
"selectPrompt": "حدد المسار الموسيقي الخاص بك هنا:",
"signOff": "شكراً!\n- أندرو"
},
"youtubeComplete": {
"greeting": "مرحباً {name}،",
"greatNews": "أخبار رائعة! تم رفع فيديو الكاريوكي الخاص بك لأغنية \"{artist} - {title}\" على YouTube:",
"delayNote": "تأخر هذا الرفع لفترة وجيزة بينما قامت أنظمتنا بمعالجة عمليات الرفع الأخرى، ولكن كل شيء جاهز الآن.",
"signOff": "شكراً!\n- أندرو"
}
}
}
}
+338
View File
@@ -0,0 +1,338 @@
{
"auth": {
"unknownService": "Servei desconegut: {service}",
"invalidCredentials": "Els serveis següents s'han de tornar a autoritzar: {services}",
"validCredentials": "Totes les credencials sol·licitades són vàlides",
"youtubeAuthInstructions": "Visita {verification_url} i introdueix el codi: {user_code}",
"youtubeAuthStartFailed": "No s'ha pogut iniciar l'autenticació del dispositiu de YouTube: {error}",
"gdriveLinkInstructions": "Visita {verification_url} i introdueix el codi: {user_code}",
"gdriveAuthStartFailed": "No s'ha pogut iniciar l'autenticació del dispositiu de Google Drive: {error}",
"discordAlertNotConfigured": "El webhook d'alerta de Discord no està configurat"
},
"jobs": {
"created": "Tasca creada correctament. S'ha iniciat el processament.",
"authError": "Error d'autenticació: no hi ha cap identitat d'usuari disponible",
"noDefaultTheme": "No hi ha cap tema predeterminat configurat. Contacta amb suport o especifica un theme_id.",
"notFound": "Tasca no trobada",
"noPermissionAccess": "No tens permís per accedir a aquesta tasca",
"noPermissionEdit": "No tens permís per editar aquesta tasca",
"noPermissionDelete": "No tens permís per eliminar aquesta tasca",
"noPermissionModify": "No tens permís per modificar aquesta tasca",
"notCompleted": "Només es poden editar les tasques completades. Estat actual: {status}",
"alreadyBeingEdited": "Aquesta tasca ja s'està editant (els resultats ja s'han eliminat)",
"cleanupFailed": "La neteja ha fallat per a {services}. La tasca no s'ha modificat. Torna-ho a provar o contacta amb suport.",
"reopened": "Pista reoberta per a l'edició. S'han eliminat els resultats anteriors.",
"invalidDatetimeFormat": "Format de {field} no vàlid: {value}",
"listError": "Error en llistar les tasques: {error}",
"deleteError": "Error en eliminar la tasca {job_id}: {error}",
"deletionPreview": "Afegeix &confirm=true per executar l'eliminació",
"deletionRequiresFilters": "Es requereix almenys un filtre (environment, client_id, status, created_before)",
"bulkDeleteError": "Error en eliminar tasques de manera massiva: {error}",
"reviewNotReady": "La tasca no està llesta per a la revisió (estat actual: {status})",
"correctionsUnavailable": "Les dades de correcció no estan disponibles",
"audioUnavailable": "L'àudio no està disponible per a la revisió",
"reviewCannotStart": "No es pot iniciar la revisió",
"jobNotInReviewState": "La tasca no està en estat de revisió (estat actual: {status})",
"correctionsProcessing": "Correccions desades. Crida /complete-review quan hagis acabat.",
"editLogSaveFailed": "Error en desar el registre d'edició per a la tasca {job_id}: {error}",
"stemsMissing": "Falten pistes requerides a la tasca (instrumental_clean i/o backing_vocals)",
"customInstrumentalFailed": "Error en crear la pista instrumental personalitzada per a la tasca {job_id}: {error}",
"audioProcessingFailed": "No s'ha pogut processar el fitxer d'àudio: {error}",
"durationMismatch": "Discrepància de durada: el fitxer pujat dura {upload_duration}s però l'àudio original dura {original_duration}s. La pista instrumental ha de durar exactament {original_duration}s (±0.5s).",
"reviewNotInState": "La tasca no està en estat de revisió (estat actual: {status})",
"noLyricsDetected": "No es pot completar la revisió: no s'han detectat lletres a l'àudio. Això pot passar quan l'àudio d'entrada no té veus (p. ex., una pista de karaoke o instrumental). Pots tornar enrere i enganxar les lletres manualment utilitzant 'Substitueix-ho tot', o cancel·lar aquesta tasca i tornar-ho a provar amb un fitxer d'àudio que contingui veus.",
"reviewCompleteStartRendering": "Revisió completada. S'ha iniciat la renderització del vídeo.",
"reviewCompleteError": "Error en completar la revisió per a la tasca {job_id}: {error}",
"instrumentalSelectionRequired": "Es requereix instrumental_selection. Ha de ser 'clean' o 'with_backing'.",
"invalidInstrumentalSelection": "instrumental_selection no vàlid. Ha de ser un de: {valid_selections}",
"instrumentalSelected": "Pista instrumental seleccionada. S'ha iniciat la generació del vídeo.",
"instrumentalSelectionError": "Error en seleccionar la pista instrumental per a la tasca {job_id}: {error}",
"downloadUrlsError": "Error en obtenir els URL de descàrrega: {error}"
},
"review": {
"jobNotFound": "Tasca no trobada",
"reviewNotReady": "La tasca no està llesta per a la revisió (estat actual: {status})",
"correctionsNotFound": "No s'han trobat les dades de correcció. És possible que el processament de les lletres no estigui complet.",
"correctionsLoadFailed": "Error en carregar les correccions: {error}",
"audioNotFound": "Fitxer d'àudio no trobat",
"audioServeError": "Error en servir l'àudio: {error}",
"instrumentalSelectionRequired": "Es requereix instrumental_selection. Ha de ser 'clean' o 'with_backing'.",
"invalidInstrumentalSelection": "instrumental_selection no vàlid. Ha de ser un de: {valid_selections}",
"reviewCompletedError": "Error en completar la revisió: {error}",
"handlersUpdateNotImplemented": "Les actualitzacions de controladors encara no estan implementades",
"lyricsAddError": "No s'han pogut afegir les lletres: {error}",
"lyricsAddInvalidRequest": "Sol·licitud per afegir lletres no vàlida: {error}",
"lyricsSearchError": "No s'han pogut cercar les lletres: {error}",
"lyricsSearchInvalidRequest": "Sol·licitud de cerca de lletres no vàlida: {error}",
"lyricsSearchNoResults": "No s'han trobat lletres coincidents en cap proveïdor",
"previewVideoGenerationError": "No s'ha pogut generar el vídeo de previsualització: {error}",
"previewVideoNotFound": "Vídeo de previsualització no trobat",
"previewVideoStreamError": "Error en transmetre el vídeo de previsualització: {error}",
"annotationSaveError": "Error en desar les anotacions: {error}",
"waveformGenerationError": "Error en generar les dades de la forma d'ona: {error}",
"waveformNoAudio": "No hi ha àudio disponible per a la forma d'ona",
"sessionSaveError": "Es requereixen dades de correcció"
},
"audioSearch": {
"notEnabled": "La cerca d'àudio no està activada per a aquest tenant",
"disabled": "La cerca d'àudio no està disponible",
"downloadError": "La descàrrega ha fallat per a la tasca {job_id}: {error}",
"jobNotFound": "Tasca {job_id} no trobada",
"noSearchResults": "No hi ha resultats de cerca disponibles",
"invalidSelectionIndex": "Índex de selecció no vàlid {selection_index}. Rang vàlid: 0-{max}",
"selectionError": "Error durant la selecció d'àudio per a la tasca {job_id}: {error}",
"youtubeDownloadError": "La descàrrega de YouTube ha fallat: {error}",
"torrentDownloadError": "No es pot descarregar des de {source} sense el servei remot flacfetch. Configura FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "No hi ha cap source_id o remote_search_id disponible per a la descàrrega de {source}",
"remoteDownloadCompleteNoPath": "Descàrrega remota completada però no s'ha retornat cap camí de fitxer",
"spotifyDownloadError": "No es pot descarregar des de Spotify sense el servei remot flacfetch. Configura FLACFETCH_API_URL.",
"genericDownloadError": "Tipus d'origen desconegut: {source}, intentant una descàrrega genèrica",
"jobNotFoundDuringDownload": "Tasca {job_id} no trobada durant la descàrrega en segon pla",
"selectAudioError": "Error en seleccionar l'àudio per a la tasca {job_id}: {error}",
"searchAudioError": "Error en cercar l'àudio: {error}",
"searchCreatedSuccessfully": "Tasca creada. Cercant àudio...",
"autoDownloadStarted": "Millor resultat seleccionat automàticament. Iniciant la descàrrega..."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
"magicLinkSent": "Si aquest correu electrònic està registrat, rebràs un enllaç d'inici de sessió en breu.",
"emailServiceNotConfigured": "El servei de correu electrònic no està disponible. Contacta amb suport.",
"emailDomainNotAllowed": "Domini de correu electrònic no permès per a aquest tenant",
"invalidToken": "Token no vàlid",
"verifyError": "La verificació ha fallat: {message}",
"magicLinkSuccess": "Sessió iniciada correctament",
"logoutSuccess": "Sessió tancada correctament",
"userNotFound": "Usuari no trobat",
"creditPackagesError": "Error en carregar els paquets de crèdits: {error}",
"stripeSendError": "Error en enviar l'enllaç de pagament de Stripe: {error}",
"stripeWebhookProcessingError": "Error en processar el webhook de Stripe: {error}",
"feedbackSaveError": "Error en desar els comentaris: {error}",
"feedbackNotEligible": "L'usuari no és elegible per deixar comentaris"
},
"fileUpload": {
"invalidTheme": "Tema no trobat: {theme_id}. Utilitza GET /api/themes per llistar els temes disponibles.",
"uploadSuccess": "Fitxer pujat correctament. S'ha iniciat el processament.",
"uploadError": "Error en pujar el fitxer: {error}",
"urlDownloadError": "Error en descarregar des de l'URL: {error}",
"invalidContentType": "Tipus de contingut no vàlid: {content_type}",
"fileSizeError": "El fitxer és massa gran: {size}. Màxim: {max_size}",
"invalidFileType": "Tipus de fitxer no vàlid: {file_type}",
"multipleAudioFilesNotAllowed": "Només es pot pujar un fitxer d'àudio",
"noAudioFileProvided": "No s'ha proporcionat cap fitxer d'àudio",
"urlCreationSuccess": "Tasca creada. S'han generat els URL de pujada.",
"urlCreationError": "Error en crear la tasca amb URL de pujada: {error}",
"uploadsCompleteSuccess": "Pujades completades. S'ha iniciat el processament.",
"uploadsCompleteError": "Error en completar les pujades: {error}",
"noUploadedFiles": "No s'han especificat fitxers pujats",
"styleUploadUrlsSuccess": "S'han generat els URL de pujada d'estil.",
"styleUploadsCompleteSuccess": "Fitxers d'estil actualitzats. S'ha reiniciat el processament.",
"styleUploadsCompleteError": "Error en completar les pujades d'estil: {error}"
},
"catalog": {
"rateLimitExceeded": "S'ha superat el límit de velocitat. Màxim {max_requests} sol·licituds de catàleg per minut.",
"catalogSearchError": "Error en cercar al catàleg: {error}",
"communityCheckError": "Error en comprovar les versions de la comunitat: {error}"
},
"themes": {
"themesLoadError": "No s'han pogut carregar els temes",
"themeNotFound": "Tema no trobat: {theme_id}",
"themeLoadError": "No s'ha pogut carregar el tema",
"previewNotAvailable": "No hi ha cap previsualització disponible per al tema: {theme_id}",
"previewLoadError": "No s'ha pogut carregar la previsualització del tema",
"youtubeDescriptionNotFound": "Tema no trobat: {theme_id}",
"youtubeDescriptionLoadError": "No s'ha pogut carregar la descripció de YouTube"
},
"tenant": {
"assetNotFound": "Actiu no trobat"
},
"push": {
"disabled": "Les notificacions push no estan activades",
"userEmailNotAvailable": "El correu electrònic de l'usuari no està disponible",
"missingEncryptionKeys": "Falten claus requerides (p256dh, auth)",
"subscriptionSaveFailed": "No s'ha pogut desar la subscripció",
"subscriptionRegistered": "Subscripció push registrada correctament",
"subscriptionNotFound": "Subscripció eliminada (o no s'ha trobat)",
"subscriptionRemoved": "Subscripció push eliminada correctament",
"testNotificationSent": "Notificació de prova enviada a {sent_count} dispositiu(s)"
},
"pushNotifications": {
"reviewLyricsTitle": "Revisa les lletres",
"reviewLyricsBody": "\"{title}\" de {artist} necessita una revisió de les lletres",
"selectInstrumentalTitle": "Selecciona la pista instrumental",
"selectInstrumentalBody": "\"{title}\" de {artist} necessita la selecció de la pista instrumental",
"videoReadyTitle": "Vídeo llest!",
"videoReadyBody": "El teu vídeo de karaoke per a \"{title}\" de {artist} està llest per descarregar"
},
"admin": {
"invalidDomainFormat": "Format de domini no vàlid",
"domainAddedToBl": "Domini '{domain}' afegit a la llista de bloqueig de dominis d'un sol ús",
"domainNotFoundInBl": "Domini no trobat a la llista de bloqueig",
"domainRemovedFromBl": "Domini '{domain}' eliminat de la llista de bloqueig de dominis d'un sol ús",
"domainAddedToAllowlist": "Domini '{domain}' afegit a la llista de permesos",
"domainNotFoundInAllowlist": "Domini no trobat a la llista de permesos",
"domainRemovedFromAllowlist": "Domini '{domain}' eliminat de la llista de permesos",
"syncComplete": "S'han sincronitzat {external_count} dominis externs ({added} afegits, {removed} eliminats)",
"invalidEmailFormat": "Format de correu electrònic no vàlid",
"emailAddedToBl": "Correu electrònic '{email}' afegit a la llista de correus bloquejats",
"emailNotFoundInBl": "Correu electrònic no trobat a la llista de bloqueig",
"emailRemovedFromBl": "Correu electrònic '{email}' eliminat de la llista de correus bloquejats",
"invalidIPAddress": "Adreça IP no vàlida",
"ipAddedToBl": "IP '{ip_address}' afegida a la llista d'IPs bloquejades",
"ipNotFoundInBl": "IP no trobada a la llista de bloqueig",
"ipRemovedFromBl": "IP '{ip_address}' eliminada de la llista d'IPs bloquejades",
"youtubeUploadNotFound": "Pujada no trobada o no en estat de reintent per a la tasca {job_id}",
"youtubeUploadQueuedForRetry": "Pujada a YouTube per a la tasca {job_id} posada en cua per reintentar",
"youtubeQueueProcessingStarted": "El processament de la cua de YouTube ha començat en segon pla"
},
"rateLimits": {
"configNotFound": "Configuració de límit de velocitat no trobada: {config_id}",
"configUpdateError": "Error en actualitzar la configuració del límit de velocitat: {error}"
},
"errors": {
"insufficientCredits": "Crèdits insuficients per a aquesta operació",
"insufficientCreditsBuyUrl": "/#pricing"
},
"emails": {
"magicLink": {
"subject": "Inicia sessió a {brand_name}",
"greeting": "Hola,",
"signInPrompt": "Fes clic al botó de sota per iniciar sessió a {brand_name}:",
"signInButton": "Inicia sessió",
"expiryWarning": "Aquest enllaç caduca en 15 minuts i només es pot utilitzar una vegada.",
"fallbackLink": "Si el botó no funciona, copia i enganxa aquest enllaç al teu navegador:",
"ignoreNote": "Si no has sol·licitat aquest correu, pots ignorar-lo amb seguretat."
},
"welcome": {
"subject": "Et donem la benvinguda a Nomad Karaoke!",
"welcomeGreeting": "Et donem la benvinguda a Nomad Karaoke!",
"turnAnySong": "Converteix qualsevol cançó en un vídeo de karaoke professional en minuts.",
"freeCreditsLabel": "Crèdits gratuïts",
"freeCreditsNote": "Cada crèdit crea un vídeo de karaoke professional",
"howItWorks": "Així és com funciona:",
"step1Title": "1. Cerca una cançó",
"step1Desc": "Introdueix l'artista i el títol, i trobarem àudio d'alta qualitat.",
"step2Title": "2. El nostre sistema fa la seva màgia",
"step2Desc": "Separem les veus, transcrivim les lletres i ho sincronitzem tot perfectament.",
"step3Title": "3. Revisa i personalitza",
"step3Desc": "Ajusta les lletres si cal, tria la teva pista instrumental.",
"step4Title": "4. Obtén el teu vídeo",
"step4Desc": "Descarrega el teu vídeo de karaoke en 4K o puja'l directament a YouTube.",
"feedbackBonus": "Completa 2 vídeos i guanya 2 crèdits gratuïts més compartint la teva opinió!",
"getStartedButton": "Comença"
},
"creditsAdded": {
"subject": "{credits} crèdits afegits al teu compte de Nomad Karaoke",
"greatNews": "Bones notícies!",
"creditsAddedMessage": "S'han afegit {credits} crèdits al teu compte.",
"yourBalance": "El teu saldo:",
"credits": "crèdits",
"eachCreditLets": "Cada crèdit et permet crear un vídeo de karaoke professional amb:",
"featureVocalSeparation": "Separació de veu/instrumental impulsada per IA",
"featureLyrics": "Lletres sincronitzades amb temporització a nivell de paraula",
"feature4k": "Sortida de vídeo en 4K",
"featureYoutube": "Pujada a YouTube",
"createButton": "Crea un karaoke ara"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (El teu vídeo de karaoke està llest!)",
"subject": "{artist} - {title} (El teu vídeo de karaoke està llest!)",
"subjectFallback": "El teu vídeo de karaoke està llest!"
},
"youtubeUpload": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (Pujada a YouTube llesta!)",
"subject": "{artist} - {title} (Pujada a YouTube llesta!)",
"subjectFallback": "La teva pujada a YouTube està llesta!"
},
"actionReminder": {
"lyricsSubject": "Acció necessària: Revisa les lletres de {artist} - {title}",
"lyricsSubjectFallback": "Acció necessària: Revisa les lletres",
"instrumentalSubject": "Acció necessària: Selecciona la pista instrumental per a {artist} - {title}",
"instrumentalSubjectFallback": "Acció necessària: Selecciona la pista instrumental",
"audioEditSubject": "Acció necessària per a {artist} - {title}",
"audioEditSubjectFallback": "Acció necessària",
"alertHeading": "El teu vídeo de karaoke necessita la teva atenció!"
},
"reviewReminder": {
"subject": "Recordatori: El teu vídeo de karaoke està esperant revisió — {artist} - {title}",
"subjectFallback": "Recordatori: El teu vídeo de karaoke està esperant revisió",
"alertHeading": "El teu vídeo de karaoke t'està esperant!",
"reminderIntro": "Et recordem que el teu vídeo de karaoke{song_name} està llest per a la revisió.",
"reviewButton": "Revisa el teu vídeo",
"reviewInstructions": "Durant la revisió, pots comprovar que les lletres són correctes i triar la teva pista instrumental preferida. Normalment només triga uns minuts!",
"helpOffer": "Si tens cap problema amb el procés de revisió, només has de respondre a aquest correu i estaré encantat d'ajudar-te.",
"expiryWarning": "Tingues en compte: si la revisió no es completa en les properes 24 hores, la tasca caducarà automàticament i se't reemborsarà el crèdit."
},
"reviewExpired": {
"subject": "El teu vídeo de karaoke ha caducat — {artist} - {title}",
"subjectFallback": "El teu vídeo de karaoke ha caducat",
"cancelNotice": "El teu vídeo de karaoke{song_name} s'ha cancel·lat automàticament perquè la revisió no s'ha completat en 48 hores.",
"refundNotice": "No et preocupis — se t'ha reemborsat el crèdit! El teu saldo actual és de {credits_balance} {credits_word}.",
"creditSingular": "crèdit",
"creditPlural": "crèdits",
"createNewPrompt": "Pots crear un nou vídeo de karaoke en qualsevol moment utilitzant els teus crèdits:",
"createButton": "Crea un nou vídeo",
"helpOffer": "Si has tingut algun problema amb el procés de revisió o necessites ajuda, només has de respondre a aquest correu — m'encantaria ajudar-te!"
},
"creditDenied": {
"subject": "Sobre els teus crèdits gratuïts de Nomad Karaoke",
"greeting": "Hola,",
"thankYou": "Gràcies per registrar-te a Nomad Karaoke!",
"deniedMessage": "Malauradament, aquesta vegada no hem pogut concedir-te els teus {credit_type} gratuïts. El nostre sistema ha detectat patrons que suggereixen que aquest pot no ser el teu primer compte amb nosaltres, i cada tasca de generació de karaoke ens costa diners reals en computació al núvol i tarifes d'API.",
"mistakeNote": "Entenem perfectament si això és un error! Si ets un usuari nou genuí, si us plau, respon a aquest correu i fes-ho saber a l'Andrew (el fundador). Ell ha creat aquest servei i estarà encantat de concedir-te alguns crèdits gratuïts per provar-ho — només et demana que a canvi donis la teva opinió sincera sobre l'experiència.",
"buyPrompt": "Si vols començar de seguida, també pots comprar crèdits:",
"buyButton": "Compra crèdits",
"costNote": "Mantenim els costos baixos per poder oferir el servei de manera assequible, la qual cosa significa que hem de tenir cura amb l'abús de crèdits gratuïts. Gràcies per la comprensió!",
"welcomeCredits": "crèdits de benvinguda",
"feedbackCredits": "crèdits de bonificació per comentaris"
},
"madeForYouConfirmation": {
"subject": "Comanda confirmada: {artist} - {title} | Nomad Karaoke",
"thankYou": "Gràcies per la teva comanda!",
"orderDetails": "Detalls de la comanda",
"orderId": "ID de la comanda:",
"artist": "Artista:",
"title": "Títol:",
"yourNotes": "Les teves notes:",
"deliveryTime": "El nostre equip crearà el teu vídeo de karaoke personalitzat en un termini de {hours} hores.",
"deliveryNotice": "Rebràs un correu electrònic amb els enllaços de descàrrega tan aviat com el teu vídeo estigui llest.",
"noAction": "No cal fer res — posa't còmode i nosaltres ens encarreguem de tot!"
},
"shared": {
"footerHelp": "Si alguna cosa no és perfecta, només has de respondre a aquest correu i ho arreglaré!"
},
"templates": {
"jobCompletion": {
"greeting": "Hola {name},",
"thanks": "Gràcies per la teva comanda!",
"youtubeLink": "Aquí tens l'enllaç del vídeo de karaoke publicat a YouTube:",
"dropboxIntro": "Aquí tens la carpeta de Dropbox amb tots els fitxers acabats i els fitxers d'origen, incloent-hi:",
"fileList": "- \"(Final Karaoke Lossless).mkv\": vídeo de karaoke combinat en 4K H264 amb àudio FLAC sense pèrdua\n- \"(Final Karaoke).mp4\": vídeo de karaoke combinat amb pantalla de títol/final en 4K H264/AAC\n- \"(Final Karaoke 720p).mp4\": vídeo de karaoke combinat en 720p H264/AAC (fitxer més petit per a sistemes antics)\n- \"(With Vocals).mp4\": vídeo per cantar a sobre en 4K H264/AAC amb les veus originals\n- \"(Karaoke).mov\": sortida de vídeo de karaoke des de MidiCo (sense pantalla de títol/final)\n- \"(Title).mov\"/\"(End).mov\": vídeos de la targeta de títol i la pantalla final\n- \"(Final Karaoke CDG).zip\": format CDG+MP3 per a sistemes de karaoke antics/comercials\n- \"(Final Karaoke TXT).zip\": format TXT+MP3 per a Power Karaoke\n- stems/*.flac: diverses pistes d'àudio instrumental i vocal separades en format sense pèrdua\n- lyrics/*.txt: lletres de la cançó de diverses fonts en format de text pla",
"fixOffer": "Fes-me saber si alguna cosa no és perfecta i estaré encantat d'ajustar-ho / arreglar-ho, o si ho necessites en qualsevol altre format, probablement t'ho puc convertir!",
"feedbackRequest": "Si tens un moment, agrairia molt la teva opinió (triga 2 minuts):",
"signOff": "Gràcies de nou i que tinguis un bon dia!\n-Andrew",
"youtubeQueued": "La teva pujada a YouTube està en cua i es processarà automàticament. Rebràs un correu electrònic de seguiment amb l'enllaç en breu."
},
"actionLyrics": {
"greeting": "Hola {name},",
"ready": "El teu vídeo de karaoke per a \"{artist} - {title}\" està llest per a la revisió!",
"instructions": "El nostre sistema ha transcrit i sincronitzat les lletres, però potser necessiten algunes correccions. També podràs seleccionar la teva pista instrumental preferida (amb o sense veus de fons).",
"reviewPrompt": "Si us plau, revisa les teves lletres i selecciona una pista instrumental:",
"duration": "Això normalment només triga uns minuts.",
"signOff": "Gràcies!\n-Andrew"
},
"actionInstrumental": {
"greeting": "Hola {name},",
"almostDone": "El teu vídeo de karaoke per a \"{artist} - {title}\" està gairebé acabat!",
"instructions": "Hem separat l'àudio en diferents versions. Si us plau, selecciona quina pista instrumental t'agradaria utilitzar per al vídeo final.",
"selectPrompt": "Selecciona la teva pista instrumental aquí:",
"signOff": "Gràcies!\n-Andrew"
},
"youtubeComplete": {
"greeting": "Hola {name},",
"greatNews": "Bones notícies! El teu vídeo de karaoke per a \"{artist} - {title}\" s'ha pujat a YouTube:",
"delayNote": "Aquesta pujada s'ha endarrerit breument mentre els nostres sistemes processaven altres pujades, però ara ja està tot llest.",
"signOff": "Gràcies!\n-Andrew"
}
}
}
}
+338
View File
@@ -0,0 +1,338 @@
{
"auth": {
"unknownService": "Neznámá služba: {service}",
"invalidCredentials": "Následující služby vyžadují opětovnou autorizaci: {services}",
"validCredentials": "Všechny požadované přihlašovací údaje jsou platné",
"youtubeAuthInstructions": "Navštiv {verification_url} a zadej kód: {user_code}",
"youtubeAuthStartFailed": "Nepodařilo se spustit autorizaci zařízení YouTube: {error}",
"gdriveLinkInstructions": "Navštiv {verification_url} a zadej kód: {user_code}",
"gdriveAuthStartFailed": "Nepodařilo se spustit autorizaci zařízení Google Drive: {error}",
"discordAlertNotConfigured": "Webhook pro upozornění na Discordu není nakonfigurován"
},
"jobs": {
"created": "Úloha byla úspěšně vytvořena. Zpracování začalo.",
"authError": "Chyba ověření: není k dispozici žádná identita uživatele",
"noDefaultTheme": "Není nakonfigurován žádný výchozí motiv. Kontaktuj prosím podporu nebo zadej theme_id.",
"notFound": "Úloha nebyla nalezena",
"noPermissionAccess": "Nemáš oprávnění přistupovat k této úloze",
"noPermissionEdit": "Nemáš oprávnění upravovat tuto úlohu",
"noPermissionDelete": "Nemáš oprávnění smazat tuto úlohu",
"noPermissionModify": "Nemáš oprávnění měnit tuto úlohu",
"notCompleted": "Upravovat lze pouze dokončené úlohy. Aktuální stav: {status}",
"alreadyBeingEdited": "Tato úloha se již upravuje (výstupy byly již smazány)",
"cleanupFailed": "Vyčištění selhalo pro {services}. Úloha nebyla změněna. Zkus to prosím znovu nebo kontaktuj podporu.",
"reopened": "Stopa byla znovu otevřena pro úpravy. Předchozí výstupy byly odstraněny.",
"invalidDatetimeFormat": "Neplatný formát {field}: {value}",
"listError": "Chyba při načítání seznamu úloh: {error}",
"deleteError": "Chyba při mazání úlohy {job_id}: {error}",
"deletionPreview": "Přidej &confirm=true pro provedení smazání",
"deletionRequiresFilters": "Je vyžadován alespoň jeden filtr (environment, client_id, status, created_before)",
"bulkDeleteError": "Chyba při hromadném mazání úloh: {error}",
"reviewNotReady": "Úloha není připravena ke kontrole (aktuální stav: {status})",
"correctionsUnavailable": "Data oprav nejsou k dispozici",
"audioUnavailable": "Zvuk není k dispozici pro kontrolu",
"reviewCannotStart": "Nelze zahájit kontrolu",
"jobNotInReviewState": "Úloha není ve stavu kontroly (aktuální stav: {status})",
"correctionsProcessing": "Opravy uloženy. Až skončíš, zavolej /complete-review.",
"editLogSaveFailed": "Chyba při ukládání protokolu úprav pro úlohu {job_id}: {error}",
"stemsMissing": "Úloze chybí požadované stopy (instrumental_clean a/nebo backing_vocals)",
"customInstrumentalFailed": "Chyba při vytváření vlastního instrumentálu pro úlohu {job_id}: {error}",
"audioProcessingFailed": "Nepodařilo se zpracovat zvukový soubor: {error}",
"durationMismatch": "Neshoda v délce: nahraný soubor má {upload_duration}s, ale původní zvuk má {original_duration}s. Instrumentál musí mít přesně {original_duration}s (±0.5s).",
"reviewNotInState": "Úloha není ve stavu kontroly (aktuální stav: {status})",
"noLyricsDetected": "Nelze dokončit kontrolu: ve zvuku nebyly detekovány žádné texty. To se může stát, když vstupní zvuk neobsahuje vokály (např. karaoke stopa nebo instrumentál). Můžeš se vrátit a vložit text ručně pomocí 'Nahradit vše', nebo tuto úlohu zrušit a zkusit to znovu se zvukovým souborem, který obsahuje vokály.",
"reviewCompleteStartRendering": "Kontrola dokončena. Začalo vykreslování videa.",
"reviewCompleteError": "Chyba při dokončování kontroly pro úlohu {job_id}: {error}",
"instrumentalSelectionRequired": "Je vyžadováno instrumental_selection. Musí být 'clean' nebo 'with_backing'.",
"invalidInstrumentalSelection": "Neplatné instrumental_selection. Musí být jedno z: {valid_selections}",
"instrumentalSelected": "Instrumentál vybrán. Začalo generování videa.",
"instrumentalSelectionError": "Chyba při výběru instrumentálu pro úlohu {job_id}: {error}",
"downloadUrlsError": "Chyba při získávání adres URL ke stažení: {error}"
},
"review": {
"jobNotFound": "Úloha nebyla nalezena",
"reviewNotReady": "Úloha není připravena ke kontrole (aktuální stav: {status})",
"correctionsNotFound": "Data oprav nebyla nalezena. Zpracování textu možná není dokončeno.",
"correctionsLoadFailed": "Chyba při načítání oprav: {error}",
"audioNotFound": "Zvukový soubor nebyl nalezen",
"audioServeError": "Chyba při poskytování zvuku: {error}",
"instrumentalSelectionRequired": "Je vyžadováno instrumental_selection. Musí být 'clean' nebo 'with_backing'.",
"invalidInstrumentalSelection": "Neplatné instrumental_selection. Musí být jedno z: {valid_selections}",
"reviewCompletedError": "Chyba při dokončování kontroly: {error}",
"handlersUpdateNotImplemented": "Aktualizace handlerů ještě nejsou implementovány",
"lyricsAddError": "Nepodařilo se přidat text: {error}",
"lyricsAddInvalidRequest": "Neplatný požadavek na přidání textu: {error}",
"lyricsSearchError": "Nepodařilo se vyhledat text: {error}",
"lyricsSearchInvalidRequest": "Neplatný požadavek na vyhledávání textu: {error}",
"lyricsSearchNoResults": "Nenalezeny žádné odpovídající texty od žádného poskytovatele",
"previewVideoGenerationError": "Nepodařilo se vygenerovat náhledové video: {error}",
"previewVideoNotFound": "Náhledové video nebylo nalezeno",
"previewVideoStreamError": "Chyba při streamování náhledového videa: {error}",
"annotationSaveError": "Chyba při ukládání anotací: {error}",
"waveformGenerationError": "Chyba při generování dat křivky: {error}",
"waveformNoAudio": "Pro křivku není k dispozici žádný zvuk",
"sessionSaveError": "Jsou vyžadována data oprav"
},
"audioSearch": {
"notEnabled": "Vyhledávání zvuku není pro tohoto tenanta povoleno",
"disabled": "Vyhledávání zvuku není k dispozici",
"downloadError": "Stahování selhalo pro úlohu {job_id}: {error}",
"jobNotFound": "Úloha {job_id} nebyla nalezena",
"noSearchResults": "Nejsou k dispozici žádné výsledky vyhledávání",
"invalidSelectionIndex": "Neplatný index výběru {selection_index}. Platný rozsah: 0-{max}",
"selectionError": "Chyba při výběru zvuku pro úlohu {job_id}: {error}",
"youtubeDownloadError": "Stahování z YouTube selhalo: {error}",
"torrentDownloadError": "Nelze stahovat z {source} bez vzdálené služby flacfetch. Nakonfiguruj FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Pro stahování z {source} není k dispozici žádné source_id nebo remote_search_id",
"remoteDownloadCompleteNoPath": "Vzdálené stahování bylo dokončeno, ale nebyla vrácena žádná cesta k souboru",
"spotifyDownloadError": "Nelze stahovat ze Spotify bez vzdálené služby flacfetch. Nakonfiguruj FLACFETCH_API_URL.",
"genericDownloadError": "Neznámý typ zdroje: {source}, pokus o obecné stažení",
"jobNotFoundDuringDownload": "Úloha {job_id} nebyla nalezena během stahování na pozadí",
"selectAudioError": "Chyba při výběru zvuku pro úlohu {job_id}: {error}",
"searchAudioError": "Chyba při vyhledávání zvuku: {error}",
"searchCreatedSuccessfully": "Úloha vytvořena. Vyhledávám zvuk...",
"autoDownloadStarted": "Nejlepší výsledek byl vybrán automaticky. Začíná stahování..."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
"magicLinkSent": "Pokud je tento e-mail zaregistrován, brzy obdržíš odkaz pro přihlášení.",
"emailServiceNotConfigured": "E-mailová služba není k dispozici. Kontaktuj prosím podporu.",
"emailDomainNotAllowed": "E-mailová doména není pro tohoto tenanta povolena",
"invalidToken": "Neplatný token",
"verifyError": "Ověření selhalo: {message}",
"magicLinkSuccess": "Úspěšně přihlášeno",
"logoutSuccess": "Úspěšně odhlášeno",
"userNotFound": "Uživatel nebyl nalezen",
"creditPackagesError": "Chyba při načítání balíčků kreditů: {error}",
"stripeSendError": "Chyba při odesílání odkazu na pokladnu Stripe: {error}",
"stripeWebhookProcessingError": "Chyba při zpracování webhooku Stripe: {error}",
"feedbackSaveError": "Chyba při ukládání zpětné vazby: {error}",
"feedbackNotEligible": "Uživatel nemá nárok na zpětnou vazbu"
},
"fileUpload": {
"invalidTheme": "Motiv nebyl nalezen: {theme_id}. Použij GET /api/themes pro vypsání dostupných motivů.",
"uploadSuccess": "Soubor byl úspěšně nahrán. Zpracování začalo.",
"uploadError": "Chyba při nahrávání souboru: {error}",
"urlDownloadError": "Chyba při stahování z URL: {error}",
"invalidContentType": "Neplatný typ obsahu: {content_type}",
"fileSizeError": "Soubor je příliš velký: {size}. Maximum: {max_size}",
"invalidFileType": "Neplatný typ souboru: {file_type}",
"multipleAudioFilesNotAllowed": "Lze nahrát pouze jeden zvukový soubor",
"noAudioFileProvided": "Nebyl poskytnut žádný zvukový soubor",
"urlCreationSuccess": "Úloha vytvořena. Byly vygenerovány adresy URL pro nahrání.",
"urlCreationError": "Chyba při vytváření úlohy s adresami URL pro nahrání: {error}",
"uploadsCompleteSuccess": "Nahrávání dokončeno. Zpracování začalo.",
"uploadsCompleteError": "Chyba při dokončování nahrávání: {error}",
"noUploadedFiles": "Nebyly zadány žádné nahrané soubory",
"styleUploadUrlsSuccess": "Byly vygenerovány adresy URL pro nahrání stylu.",
"styleUploadsCompleteSuccess": "Soubory stylu byly aktualizovány. Zpracování bylo restartováno.",
"styleUploadsCompleteError": "Chyba při dokončování nahrávání stylu: {error}"
},
"catalog": {
"rateLimitExceeded": "Překročen limit požadavků. Maximum je {max_requests} požadavků na katalog za minutu.",
"catalogSearchError": "Chyba při vyhledávání v katalogu: {error}",
"communityCheckError": "Chyba při kontrole komunitních verzí: {error}"
},
"themes": {
"themesLoadError": "Nepodařilo se načíst motivy",
"themeNotFound": "Motiv nebyl nalezen: {theme_id}",
"themeLoadError": "Nepodařilo se načíst motiv",
"previewNotAvailable": "Pro motiv není k dispozici žádný náhled: {theme_id}",
"previewLoadError": "Nepodařilo se načíst náhled motivu",
"youtubeDescriptionNotFound": "Motiv nebyl nalezen: {theme_id}",
"youtubeDescriptionLoadError": "Nepodařilo se načíst popis pro YouTube"
},
"tenant": {
"assetNotFound": "Prostředek nebyl nalezen"
},
"push": {
"disabled": "Push oznámení nejsou povolena",
"userEmailNotAvailable": "E-mail uživatele není k dispozici",
"missingEncryptionKeys": "Chybí požadované klíče (p256dh, auth)",
"subscriptionSaveFailed": "Nepodařilo se uložit odběr",
"subscriptionRegistered": "Odběr push oznámení byl úspěšně zaregistrován",
"subscriptionNotFound": "Odběr byl odstraněn (nebo nebyl nalezen)",
"subscriptionRemoved": "Odběr push oznámení byl úspěšně odstraněn",
"testNotificationSent": "Testovací oznámení odesláno na {sent_count} zařízení"
},
"pushNotifications": {
"reviewLyricsTitle": "Zkontroluj text",
"reviewLyricsBody": "\"{title}\" od {artist} vyžaduje kontrolu textu",
"selectInstrumentalTitle": "Vyber instrumentál",
"selectInstrumentalBody": "\"{title}\" od {artist} vyžaduje výběr instrumentálu",
"videoReadyTitle": "Video je připraveno!",
"videoReadyBody": "Tvoje karaoke video pro \"{title}\" od {artist} je připraveno ke stažení"
},
"admin": {
"invalidDomainFormat": "Neplatný formát domény",
"domainAddedToBl": "Doména '{domain}' přidána na blocklist jednorázových domén",
"domainNotFoundInBl": "Doména nebyla nalezena na blocklistu",
"domainRemovedFromBl": "Doména '{domain}' odstraněna z blocklistu jednorázových domén",
"domainAddedToAllowlist": "Doména '{domain}' přidána na allowlist",
"domainNotFoundInAllowlist": "Doména nebyla nalezena na allowlistu",
"domainRemovedFromAllowlist": "Doména '{domain}' odstraněna z allowlistu",
"syncComplete": "Synchronizováno {external_count} externích domén ({added} přidáno, {removed} odstraněno)",
"invalidEmailFormat": "Neplatný formát e-mailu",
"emailAddedToBl": "E-mail '{email}' přidán na seznam blokovaných e-mailů",
"emailNotFoundInBl": "E-mail nebyl nalezen na blocklistu",
"emailRemovedFromBl": "E-mail '{email}' odstraněn ze seznamu blokovaných e-mailů",
"invalidIPAddress": "Neplatná IP adresa",
"ipAddedToBl": "IP '{ip_address}' přidána na seznam blokovaných IP",
"ipNotFoundInBl": "IP nebyla nalezena na blocklistu",
"ipRemovedFromBl": "IP '{ip_address}' odstraněna ze seznamu blokovaných IP",
"youtubeUploadNotFound": "Nahrávání nebylo nalezeno nebo není ve stavu pro opakování pro úlohu {job_id}",
"youtubeUploadQueuedForRetry": "Nahrávání na YouTube pro úlohu {job_id} zařazeno do fronty pro opakování",
"youtubeQueueProcessingStarted": "Zpracování fronty YouTube začalo na pozadí"
},
"rateLimits": {
"configNotFound": "Konfigurace limitu požadavků nebyla nalezena: {config_id}",
"configUpdateError": "Chyba při aktualizaci konfigurace limitu požadavků: {error}"
},
"errors": {
"insufficientCredits": "Nedostatek kreditů pro tuto operaci",
"insufficientCreditsBuyUrl": "/#pricing"
},
"emails": {
"magicLink": {
"subject": "Přihlášení do {brand_name}",
"greeting": "Ahoj,",
"signInPrompt": "Klikni na tlačítko níže pro přihlášení do {brand_name}:",
"signInButton": "Přihlásit se",
"expiryWarning": "Tento odkaz vyprší za 15 minut a lze jej použít pouze jednou.",
"fallbackLink": "Pokud tlačítko nefunguje, zkopíruj a vlož tento odkaz do prohlížeče:",
"ignoreNote": "Pokud jsi o tento e-mail nepožádal(a), můžeš ho bezpečně ignorovat."
},
"welcome": {
"subject": "Vítej v Nomad Karaoke!",
"welcomeGreeting": "Vítej v Nomad Karaoke!",
"turnAnySong": "Proměň jakoukoli písničku na profesionální karaoke video během několika minut.",
"freeCreditsLabel": "Kredity zdarma",
"freeCreditsNote": "Za jeden kredit vytvoříš jedno profesionální karaoke video",
"howItWorks": "Takhle to funguje:",
"step1Title": "1. Vyhledej písničku",
"step1Desc": "Zadej interpreta a název a my najdeme vysoce kvalitní zvuk.",
"step2Title": "2. Náš systém udělá svá kouzla",
"step2Desc": "Oddělíme vokály, přepíšeme text a vše perfektně zesynchronizujeme.",
"step3Title": "3. Zkontroluj a uprav",
"step3Desc": "V případě potřeby dolaď text a vyber si svůj instrumentál.",
"step4Title": "4. Získej své video",
"step4Desc": "Stáhni si své 4K karaoke video nebo ho nahraj přímo na YouTube.",
"feedbackBonus": "Dokonči 2 videa, poděl se o zpětnou vazbu a získej další 2 kredity zdarma!",
"getStartedButton": "Začít"
},
"creditsAdded": {
"subject": "{credits} kreditů přidáno na tvůj účet Nomad Karaoke",
"greatNews": "Skvělá zpráva!",
"creditsAddedMessage": "{credits} kreditů bylo přidáno na tvůj účet.",
"yourBalance": "Tvůj zůstatek:",
"credits": "kreditů",
"eachCreditLets": "Každý kredit ti umožní vytvořit jedno profesionální karaoke video s:",
"featureVocalSeparation": "Oddělením vokálů/instrumentálu pomocí AI",
"featureLyrics": "Synchronizovaným textem s časováním na úrovni slov",
"feature4k": "Výstupem videa ve 4K",
"featureYoutube": "Nahráním na YouTube",
"createButton": "Vytvořit karaoke hned"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (Tvoje karaoke video je připraveno!)",
"subject": "{artist} - {title} (Tvoje karaoke video je připraveno!)",
"subjectFallback": "Tvoje karaoke video je připraveno!"
},
"youtubeUpload": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (Nahrání na YouTube je připraveno!)",
"subject": "{artist} - {title} (Nahrání na YouTube je připraveno!)",
"subjectFallback": "Tvoje nahrání na YouTube je připraveno!"
},
"actionReminder": {
"lyricsSubject": "Je vyžadována akce: Zkontroluj text pro {artist} - {title}",
"lyricsSubjectFallback": "Je vyžadována akce: Zkontroluj text",
"instrumentalSubject": "Je vyžadována akce: Vyber instrumentál pro {artist} - {title}",
"instrumentalSubjectFallback": "Je vyžadována akce: Vyber instrumentál",
"audioEditSubject": "Je vyžadována akce pro {artist} - {title}",
"audioEditSubjectFallback": "Je vyžadována akce",
"alertHeading": "Tvoje karaoke video potřebuje tvůj zásah!"
},
"reviewReminder": {
"subject": "Připomenutí: Tvoje karaoke video čeká na kontrolu — {artist} - {title}",
"subjectFallback": "Připomenutí: Tvoje karaoke video čeká na kontrolu",
"alertHeading": "Tvoje karaoke video na tebe čeká!",
"reminderIntro": "Jen přátelské připomenutí, že tvoje karaoke video{song_name} je připraveno ke kontrole.",
"reviewButton": "Zkontrolovat video",
"reviewInstructions": "Během kontroly můžeš ověřit, že je text správný, a vybrat si preferovanou instrumentální stopu. Většinou to zabere jen pár minut!",
"helpOffer": "Pokud máš s procesem kontroly nějaké potíže, stačí odpovědět na tento e-mail a rád ti pomůžu.",
"expiryWarning": "Upozornění: pokud kontrola nebude dokončena během následujících 24 hodin, úloha automaticky vyprší a tvůj kredit bude vrácen."
},
"reviewExpired": {
"subject": "Tvoje karaoke video vypršelo — {artist} - {title}",
"subjectFallback": "Tvoje karaoke video vypršelo",
"cancelNotice": "Tvoje karaoke video{song_name} bylo automaticky zrušeno, protože kontrola nebyla dokončena do 48 hodin.",
"refundNotice": "Neboj — tvůj kredit byl vrácen! Tvůj aktuální zůstatek je {credits_balance} {credits_word}.",
"creditSingular": "kredit",
"creditPlural": "kreditů",
"createNewPrompt": "Kdykoli můžeš vytvořit nové karaoke video pomocí svých kreditů:",
"createButton": "Vytvořit nové video",
"helpOffer": "Pokud jsi měl(a) s procesem kontroly nějaké potíže nebo potřebuješ pomoct, stačí odpovědět na tento e-mail — rád pomůžu!"
},
"creditDenied": {
"subject": "Ohledně tvých kreditů zdarma na Nomad Karaoke",
"greeting": "Ahoj,",
"thankYou": "Díky za registraci do Nomad Karaoke!",
"deniedMessage": "Bohužel jsme ti tentokrát nemohli přidělit tvé {credit_type} zdarma. Náš systém detekoval vzorce, které naznačují, že toto možná není tvůj první účet u nás, a každé generování karaoke nás stojí skutečné peníze za cloudové výpočty a poplatky za API.",
"mistakeNote": "Naprosto chápeme, pokud je to chyba! Pokud jsi skutečně nový uživatel, stačí odpovědět na tento e-mail a dát vědět Andrewovi (zakladateli). Tuto službu vytvořil a rád ti přidělí nějaké kredity zdarma na vyzkoušení — jen žádá, abys mu na oplátku poskytl(a) upřímnou zpětnou vazbu na tvou zkušenost.",
"buyPrompt": "Pokud chceš začít hned, můžeš si také kredity zakoupit:",
"buyButton": "Koupit kredity",
"costNote": "Udržujeme náklady nízko, abychom mohli službu nabízet cenově dostupně, což znamená, že musíme být opatrní ohledně zneužívání kreditů zdarma. Díky za pochopení!",
"welcomeCredits": "uvítací kredity",
"feedbackCredits": "bonusové kredity za zpětnou vazbu"
},
"madeForYouConfirmation": {
"subject": "Objednávka potvrzena: {artist} - {title} | Nomad Karaoke",
"thankYou": "Děkujeme za tvou objednávku!",
"orderDetails": "Detaily objednávky",
"orderId": "ID objednávky:",
"artist": "Interpret:",
"title": "Název:",
"yourNotes": "Tvoje poznámky:",
"deliveryTime": "Náš tým vytvoří tvé vlastní karaoke video do {hours} hodin.",
"deliveryNotice": "Jakmile bude tvé video připraveno, obdržíš e-mail s odkazy ke stažení.",
"noAction": "Není potřeba žádná akce — pohodlně se usaď a my se o vše postaráme!"
},
"shared": {
"footerHelp": "Pokud něco není perfektní, stačí odpovědět na tento e-mail a já to opravím!"
},
"templates": {
"jobCompletion": {
"greeting": "Ahoj {name},",
"thanks": "Díky za tvou objednávku!",
"youtubeLink": "Tady je odkaz na karaoke video zveřejněné na YouTube:",
"dropboxIntro": "Tady je složka na Dropboxu s hotovými i zdrojovými soubory, včetně:",
"fileList": "- \"(Final Karaoke Lossless).mkv\": kombinované karaoke video ve 4K H264 s bezztrátovým zvukem FLAC\n- \"(Final Karaoke).mp4\": kombinované karaoke video s úvodní/závěrečnou obrazovkou ve 4K H264/AAC\n- \"(Final Karaoke 720p).mp4\": kombinované karaoke video v 720p H264/AAC (menší soubor pro starší systémy)\n- \"(With Vocals).mp4\": video pro zpívání s původními vokály ve 4K H264/AAC\n- \"(Karaoke).mov\": výstupní karaoke video z MidiCo (bez úvodní/závěrečné obrazovky)\n- \"(Title).mov\"/\"(End).mov\": videa úvodní a závěrečné obrazovky\n- \"(Final Karaoke CDG).zip\": formát CDG+MP3 pro starší/komerční karaoke systémy\n- \"(Final Karaoke TXT).zip\": formát TXT+MP3 pro Power Karaoke\n- stems/*.flac: různé oddělené instrumentální a vokální stopy v bezztrátovém formátu\n- lyrics/*.txt texty písní z různých zdrojů v prostém textovém formátu",
"fixOffer": "Dej mi vědět, pokud něco není perfektní, a rád to doladím / opravím, nebo pokud to potřebuješ v jiném formátu, pravděpodobně to pro tebe dokážu převést!",
"feedbackRequest": "Pokud máš chvilku, moc bych ocenil tvou zpětnou vazbu (zabere to 2 minuty):",
"signOff": "Ještě jednou díky a přeji skvělý den!\n-Andrew",
"youtubeQueued": "Tvé nahrání na YouTube je ve frontě a bude zpracováno automaticky. Brzy obdržíš další e-mail s odkazem."
},
"actionLyrics": {
"greeting": "Ahoj {name},",
"ready": "Tvoje karaoke video pro \"{artist} - {title}\" je připraveno ke kontrole!",
"instructions": "Náš systém přepsal a zesynchronizoval text, ale možná bude potřebovat nějaké opravy. Budeš si také moci vybrat svou preferovanou instrumentální stopu (s doprovodnými vokály nebo bez nich).",
"reviewPrompt": "Zkontroluj prosím text a vyber instrumentál:",
"duration": "Většinou to zabere jen pár minut.",
"signOff": "Díky!\n-Andrew"
},
"actionInstrumental": {
"greeting": "Ahoj {name},",
"almostDone": "Tvoje karaoke video pro \"{artist} - {title}\" je skoro hotové!",
"instructions": "Oddělili jsme zvuk do různých verzí. Vyber prosím, kterou instrumentální stopu chceš použít pro finální video.",
"selectPrompt": "Vyber si svůj instrumentál zde:",
"signOff": "Díky!\n-Andrew"
},
"youtubeComplete": {
"greeting": "Ahoj {name},",
"greatNews": "Skvělé zprávy! Tvoje karaoke video pro \"{artist} - {title}\" bylo nahráno na YouTube:",
"delayNote": "Toto nahrání bylo krátce zpožděno, zatímco naše systémy zpracovávaly jiná nahrání, ale teď už je vše připraveno.",
"signOff": "Díky!\n-Andrew"
}
}
}
}
+338
View File
@@ -0,0 +1,338 @@
{
"auth": {
"unknownService": "Ukendt tjeneste: {service}",
"invalidCredentials": "Følgende tjenester kræver genautorisering: {services}",
"validCredentials": "Alle anmodede legitimationsoplysninger er gyldige",
"youtubeAuthInstructions": "Besøg {verification_url} og indtast koden: {user_code}",
"youtubeAuthStartFailed": "Kunne ikke starte YouTube-enhedsgodkendelse: {error}",
"gdriveLinkInstructions": "Besøg {verification_url} og indtast koden: {user_code}",
"gdriveAuthStartFailed": "Kunne ikke starte Google Drive-enhedsgodkendelse: {error}",
"discordAlertNotConfigured": "Discord-advarselswebhook er ikke konfigureret"
},
"jobs": {
"created": "Jobbet blev oprettet. Behandlingen er startet.",
"authError": "Godkendelsesfejl: ingen brugeridentitet tilgængelig",
"noDefaultTheme": "Intet standardtema konfigureret. Kontakt venligst support eller angiv et theme_id.",
"notFound": "Jobbet blev ikke fundet",
"noPermissionAccess": "Du har ikke tilladelse til at få adgang til dette job",
"noPermissionEdit": "Du har ikke tilladelse til at redigere dette job",
"noPermissionDelete": "Du har ikke tilladelse til at slette dette job",
"noPermissionModify": "Du har ikke tilladelse til at ændre dette job",
"notCompleted": "Kun fuldførte job kan redigeres. Nuværende status: {status}",
"alreadyBeingEdited": "Dette job er allerede ved at blive redigeret (output blev allerede slettet)",
"cleanupFailed": "Oprydning mislykkedes for {services}. Jobbet er ikke ændret. Prøv igen eller kontakt support.",
"reopened": "Sporet er genåbnet for redigering. Tidligere output er blevet fjernet.",
"invalidDatetimeFormat": "Ugyldigt {field} format: {value}",
"listError": "Fejl ved indlæsning af job: {error}",
"deleteError": "Fejl ved sletning af job {job_id}: {error}",
"deletionPreview": "Tilføj &confirm=true for at udføre sletning",
"deletionRequiresFilters": "Mindst ét filter (environment, client_id, status, created_before) er påkrævet",
"bulkDeleteError": "Fejl ved massesletning af job: {error}",
"reviewNotReady": "Jobbet er ikke klar til gennemgang (nuværende status: {status})",
"correctionsUnavailable": "Rettelsesdata er ikke tilgængelige",
"audioUnavailable": "Lyden er ikke tilgængelig til gennemgang",
"reviewCannotStart": "Kan ikke starte gennemgang",
"jobNotInReviewState": "Jobbet er ikke i gennemgangstilstand (nuværende status: {status})",
"correctionsProcessing": "Rettelser gemt. Kald /complete-review når du er færdig.",
"editLogSaveFailed": "Fejl ved lagring af redigeringslog for job {job_id}: {error}",
"stemsMissing": "Jobbet mangler påkrævede stems (instrumental_clean og/eller backing_vocals)",
"customInstrumentalFailed": "Fejl ved oprettelse af brugerdefineret instrumental for job {job_id}: {error}",
"audioProcessingFailed": "Kunne ikke behandle lydfil: {error}",
"durationMismatch": "Varigheden stemmer ikke overens: den uploadede fil er {upload_duration}s, men den originale lyd er {original_duration}s. Instrumentalen skal være præcis {original_duration}s (±0.5s).",
"reviewNotInState": "Jobbet er ikke i gennemgangstilstand (nuværende status: {status})",
"noLyricsDetected": "Kan ikke fuldføre gennemgangen: der blev ikke registreret nogen sangtekst i lyden. Dette kan ske, når inputlyden ikke har nogen vokal (f.eks. et karaokespor eller en instrumental). Du kan gå tilbage og indsætte sangteksten manuelt ved hjælp af 'Replace All', eller annullere dette job og prøve igen med en lydfil, der indeholder vokal.",
"reviewCompleteStartRendering": "Gennemgang fuldført. Videogengivelse er startet.",
"reviewCompleteError": "Fejl ved fuldførelse af gennemgang for job {job_id}: {error}",
"instrumentalSelectionRequired": "instrumental_selection er påkrævet. Skal være 'clean' eller 'with_backing'.",
"invalidInstrumentalSelection": "Ugyldig instrumental_selection. Skal være en af: {valid_selections}",
"instrumentalSelected": "Instrumental valgt. Videogenerering er startet.",
"instrumentalSelectionError": "Fejl ved valg af instrumental for job {job_id}: {error}",
"downloadUrlsError": "Fejl ved hentning af download-URL'er: {error}"
},
"review": {
"jobNotFound": "Jobbet blev ikke fundet",
"reviewNotReady": "Jobbet er ikke klar til gennemgang (nuværende status: {status})",
"correctionsNotFound": "Rettelsesdata blev ikke fundet. Behandlingen af sangteksten er muligvis ikke fuldført.",
"correctionsLoadFailed": "Fejl ved indlæsning af rettelser: {error}",
"audioNotFound": "Lydfilen blev ikke fundet",
"audioServeError": "Fejl ved servering af lyd: {error}",
"instrumentalSelectionRequired": "instrumental_selection er påkrævet. Skal være 'clean' eller 'with_backing'.",
"invalidInstrumentalSelection": "Ugyldig instrumental_selection. Skal være en af: {valid_selections}",
"reviewCompletedError": "Fejl ved fuldførelse af gennemgang: {error}",
"handlersUpdateNotImplemented": "Handler-opdateringer er endnu ikke implementeret",
"lyricsAddError": "Kunne ikke tilføje sangtekst: {error}",
"lyricsAddInvalidRequest": "Ugyldig anmodning om tilføjelse af sangtekst: {error}",
"lyricsSearchError": "Kunne ikke søge efter sangtekst: {error}",
"lyricsSearchInvalidRequest": "Ugyldig anmodning om søgning efter sangtekst: {error}",
"lyricsSearchNoResults": "Ingen matchende sangtekst fundet fra nogen udbyder",
"previewVideoGenerationError": "Kunne ikke generere forhåndsvisningsvideo: {error}",
"previewVideoNotFound": "Forhåndsvisningsvideoen blev ikke fundet",
"previewVideoStreamError": "Fejl ved streaming af forhåndsvisningsvideo: {error}",
"annotationSaveError": "Fejl ved lagring af anmærkninger: {error}",
"waveformGenerationError": "Fejl ved generering af bølgeformsdata: {error}",
"waveformNoAudio": "Ingen lyd tilgængelig til bølgeform",
"sessionSaveError": "Rettelsesdata er påkrævet"
},
"audioSearch": {
"notEnabled": "Lydsøgning er ikke aktiveret for denne lejer",
"disabled": "Lydsøgning er ikke tilgængelig",
"downloadError": "Download mislykkedes for job {job_id}: {error}",
"jobNotFound": "Jobbet {job_id} blev ikke fundet",
"noSearchResults": "Ingen søgeresultater tilgængelige",
"invalidSelectionIndex": "Ugyldigt valgindeks {selection_index}. Gyldigt område: 0-{max}",
"selectionError": "Fejl under lydvalg for job {job_id}: {error}",
"youtubeDownloadError": "YouTube-download mislykkedes: {error}",
"torrentDownloadError": "Kan ikke downloade fra {source} uden ekstern flacfetch-tjeneste. Konfigurer FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Ingen source_id eller remote_search_id tilgængelig for {source}-download",
"remoteDownloadCompleteNoPath": "Ekstern download fuldført, men ingen filsti blev returneret",
"spotifyDownloadError": "Kan ikke downloade fra Spotify uden ekstern flacfetch-tjeneste. Konfigurer FLACFETCH_API_URL.",
"genericDownloadError": "Ukendt kildetype: {source}, forsøger generisk download",
"jobNotFoundDuringDownload": "Jobbet {job_id} blev ikke fundet under baggrundsdownload",
"selectAudioError": "Fejl ved valg af lyd for job {job_id}: {error}",
"searchAudioError": "Fejl ved søgning efter lyd: {error}",
"searchCreatedSuccessfully": "Jobbet er oprettet. Søger efter lyd...",
"autoDownloadStarted": "Det bedste resultat blev valgt automatisk. Download starter..."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
"magicLinkSent": "Hvis denne e-mail er registreret, vil du modtage et login-link om kort tid.",
"emailServiceNotConfigured": "E-mail-tjenesten er ikke tilgængelig. Kontakt venligst support.",
"emailDomainNotAllowed": "E-mail-domænet er ikke tilladt for denne lejer",
"invalidToken": "Ugyldig token",
"verifyError": "Bekræftelse mislykkedes: {message}",
"magicLinkSuccess": "Du er nu logget ind",
"logoutSuccess": "Du er nu logget ud",
"userNotFound": "Brugeren blev ikke fundet",
"creditPackagesError": "Fejl ved indlæsning af kreditpakker: {error}",
"stripeSendError": "Fejl ved afsendelse af Stripe-betalingslink: {error}",
"stripeWebhookProcessingError": "Fejl ved behandling af Stripe-webhook: {error}",
"feedbackSaveError": "Fejl ved lagring af feedback: {error}",
"feedbackNotEligible": "Brugeren er ikke berettiget til feedback"
},
"fileUpload": {
"invalidTheme": "Temaet blev ikke fundet: {theme_id}. Brug GET /api/themes til at se tilgængelige temaer.",
"uploadSuccess": "Filen blev uploadet. Behandlingen er startet.",
"uploadError": "Fejl ved upload af fil: {error}",
"urlDownloadError": "Fejl ved download fra URL: {error}",
"invalidContentType": "Ugyldig indholdstype: {content_type}",
"fileSizeError": "Filen er for stor: {size}. Maksimum: {max_size}",
"invalidFileType": "Ugyldig filtype: {file_type}",
"multipleAudioFilesNotAllowed": "Kun én lydfil kan uploades",
"noAudioFileProvided": "Ingen lydfil angivet",
"urlCreationSuccess": "Jobbet blev oprettet. Upload-URL'er er genereret.",
"urlCreationError": "Fejl ved oprettelse af job med upload-URL'er: {error}",
"uploadsCompleteSuccess": "Uploads er fuldført. Behandlingen er startet.",
"uploadsCompleteError": "Fejl ved fuldførelse af uploads: {error}",
"noUploadedFiles": "Ingen uploadede filer angivet",
"styleUploadUrlsSuccess": "Stil-upload-URL'er er genereret.",
"styleUploadsCompleteSuccess": "Stilfiler er opdateret. Behandlingen er genstartet.",
"styleUploadsCompleteError": "Fejl ved fuldførelse af stil-uploads: {error}"
},
"catalog": {
"rateLimitExceeded": "Hastighedsgrænsen er overskredet. Maksimalt {max_requests} kataloganmodninger pr. minut.",
"catalogSearchError": "Fejl ved søgning i katalog: {error}",
"communityCheckError": "Fejl ved kontrol af community-versioner: {error}"
},
"themes": {
"themesLoadError": "Kunne ikke indlæse temaer",
"themeNotFound": "Temaet blev ikke fundet: {theme_id}",
"themeLoadError": "Kunne ikke indlæse tema",
"previewNotAvailable": "Ingen forhåndsvisning tilgængelig for tema: {theme_id}",
"previewLoadError": "Kunne ikke indlæse tema-forhåndsvisning",
"youtubeDescriptionNotFound": "Temaet blev ikke fundet: {theme_id}",
"youtubeDescriptionLoadError": "Kunne ikke indlæse YouTube-beskrivelse"
},
"tenant": {
"assetNotFound": "Aktivet blev ikke fundet"
},
"push": {
"disabled": "Push-meddelelser er ikke aktiveret",
"userEmailNotAvailable": "Brugerens e-mail er ikke tilgængelig",
"missingEncryptionKeys": "Mangler påkrævede nøgler (p256dh, auth)",
"subscriptionSaveFailed": "Kunne ikke gemme abonnement",
"subscriptionRegistered": "Push-abonnementet blev registreret",
"subscriptionNotFound": "Abonnementet blev fjernet (eller ikke fundet)",
"subscriptionRemoved": "Push-abonnementet blev fjernet",
"testNotificationSent": "Testmeddelelse sendt til {sent_count} enhed(er)"
},
"pushNotifications": {
"reviewLyricsTitle": "Gennemgå sangtekst",
"reviewLyricsBody": "\"{title}\" af {artist} kræver gennemgang af sangteksten",
"selectInstrumentalTitle": "Vælg instrumental",
"selectInstrumentalBody": "\"{title}\" af {artist} kræver valg af instrumental",
"videoReadyTitle": "Videoen er klar!",
"videoReadyBody": "Din karaokevideo til \"{title}\" af {artist} er klar til download"
},
"admin": {
"invalidDomainFormat": "Ugyldigt domæneformat",
"domainAddedToBl": "Domænet '{domain}' er tilføjet til blokeringslisten for engangsdomæner",
"domainNotFoundInBl": "Domænet blev ikke fundet på blokeringslisten",
"domainRemovedFromBl": "Domænet '{domain}' er fjernet fra blokeringslisten for engangsdomæner",
"domainAddedToAllowlist": "Domænet '{domain}' er tilføjet til tilladelseslisten",
"domainNotFoundInAllowlist": "Domænet blev ikke fundet på tilladelseslisten",
"domainRemovedFromAllowlist": "Domænet '{domain}' er fjernet fra tilladelseslisten",
"syncComplete": "Synkroniserede {external_count} eksterne domæner ({added} tilføjet, {removed} fjernet)",
"invalidEmailFormat": "Ugyldigt e-mail-format",
"emailAddedToBl": "E-mailen '{email}' er tilføjet til listen over blokerede e-mails",
"emailNotFoundInBl": "E-mailen blev ikke fundet på blokeringslisten",
"emailRemovedFromBl": "E-mailen '{email}' er fjernet fra listen over blokerede e-mails",
"invalidIPAddress": "Ugyldig IP-adresse",
"ipAddedToBl": "IP'en '{ip_address}' er tilføjet til listen over blokerede IP'er",
"ipNotFoundInBl": "IP'en blev ikke fundet på blokeringslisten",
"ipRemovedFromBl": "IP'en '{ip_address}' er fjernet fra listen over blokerede IP'er",
"youtubeUploadNotFound": "Upload blev ikke fundet eller er ikke i en tilstand, der kan forsøges igen for job {job_id}",
"youtubeUploadQueuedForRetry": "YouTube-upload for job {job_id} er sat i kø til nyt forsøg",
"youtubeQueueProcessingStarted": "Behandling af YouTube-kø er startet i baggrunden"
},
"rateLimits": {
"configNotFound": "Konfiguration for hastighedsgrænse blev ikke fundet: {config_id}",
"configUpdateError": "Fejl ved opdatering af konfiguration for hastighedsgrænse: {error}"
},
"errors": {
"insufficientCredits": "Utilstrækkelige kreditter til denne handling",
"insufficientCreditsBuyUrl": "/#pricing"
},
"emails": {
"magicLink": {
"subject": "Log ind på {brand_name}",
"greeting": "Hej,",
"signInPrompt": "Klik på knappen nedenfor for at logge ind på {brand_name}:",
"signInButton": "Log ind",
"expiryWarning": "Dette link udløber om 15 minutter og kan kun bruges én gang.",
"fallbackLink": "Hvis knappen ikke virker, kan du kopiere og indsætte dette link i din browser:",
"ignoreNote": "Hvis du ikke har anmodet om denne e-mail, kan du roligt ignorere den."
},
"welcome": {
"subject": "Velkommen til Nomad Karaoke!",
"welcomeGreeting": "Velkommen til Nomad Karaoke!",
"turnAnySong": "Forvandl enhver sang til en professionel karaokevideo på få minutter.",
"freeCreditsLabel": "Gratis kreditter",
"freeCreditsNote": "Hver kredit skaber én professionel karaokevideo",
"howItWorks": "Sådan fungerer det:",
"step1Title": "1. Søg efter en sang",
"step1Desc": "Indtast kunstner og titel, så finder vi lyd i høj kvalitet.",
"step2Title": "2. Vores system gør sin magi",
"step2Desc": "Vi adskiller vokal, transskriberer sangteksten og synkroniserer alt perfekt.",
"step3Title": "3. Gennemgå og tilpas",
"step3Desc": "Finjuster sangteksten, hvis det er nødvendigt, og vælg din instrumental.",
"step4Title": "4. Få din video",
"step4Desc": "Download din 4K karaokevideo eller upload direkte til YouTube.",
"feedbackBonus": "Gennemfør 2 videoer og tjen 2 ekstra gratis kreditter ved at dele din feedback!",
"getStartedButton": "Kom i gang"
},
"creditsAdded": {
"subject": "{credits} kreditter tilføjet til din Nomad Karaoke-konto",
"greatNews": "Gode nyheder!",
"creditsAddedMessage": "{credits} kreditter er blevet tilføjet til din konto.",
"yourBalance": "Din saldo:",
"credits": "kreditter",
"eachCreditLets": "Hver kredit lader dig oprette én professionel karaokevideo med:",
"featureVocalSeparation": "AI-drevet adskillelse af vokal/instrumental",
"featureLyrics": "Synkroniseret sangtekst med timing på ordniveau",
"feature4k": "4K video-output",
"featureYoutube": "YouTube-upload",
"createButton": "Opret karaoke nu"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (Din karaokevideo er klar!)",
"subject": "{artist} - {title} (Din karaokevideo er klar!)",
"subjectFallback": "Din karaokevideo er klar!"
},
"youtubeUpload": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (YouTube-upload er klar!)",
"subject": "{artist} - {title} (YouTube-upload er klar!)",
"subjectFallback": "Din YouTube-upload er klar!"
},
"actionReminder": {
"lyricsSubject": "Handling påkrævet: Gennemgå sangtekst for {artist} - {title}",
"lyricsSubjectFallback": "Handling påkrævet: Gennemgå sangtekst",
"instrumentalSubject": "Handling påkrævet: Vælg instrumental for {artist} - {title}",
"instrumentalSubjectFallback": "Handling påkrævet: Vælg instrumental",
"audioEditSubject": "Handling påkrævet for {artist} - {title}",
"audioEditSubjectFallback": "Handling påkrævet",
"alertHeading": "Din karaokevideo har brug for dit input!"
},
"reviewReminder": {
"subject": "Påmindelse: Din karaokevideo venter på gennemgang — {artist} - {title}",
"subjectFallback": "Påmindelse: Din karaokevideo venter på gennemgang",
"alertHeading": "Din karaokevideo venter på dig!",
"reminderIntro": "Bare en venlig påmindelse om, at din karaokevideo{song_name} er klar til gennemgang.",
"reviewButton": "Gennemgå din video",
"reviewInstructions": "Under gennemgangen kan du tjekke, at sangteksten er korrekt, og vælge dit foretrukne instrumentalspor. Det tager normalt kun et par minutter!",
"helpOffer": "Hvis du har problemer med gennemgangsprocessen, skal du bare svare på denne e-mail, så hjælper jeg dig gerne.",
"expiryWarning": "Bemærk venligst: Hvis gennemgangen ikke er fuldført inden for de næste 24 timer, udløber jobbet automatisk, og din kredit vil blive refunderet."
},
"reviewExpired": {
"subject": "Din karaokevideo er udløbet — {artist} - {title}",
"subjectFallback": "Din karaokevideo er udløbet",
"cancelNotice": "Din karaokevideo{song_name} er automatisk blevet annulleret, fordi gennemgangen ikke blev fuldført inden for 48 timer.",
"refundNotice": "Bare rolig — din kredit er blevet refunderet! Din nuværende saldo er {credits_balance} {credits_word}.",
"creditSingular": "kredit",
"creditPlural": "kreditter",
"createNewPrompt": "Du kan oprette en ny karaokevideo når som helst ved hjælp af dine kreditter:",
"createButton": "Opret ny video",
"helpOffer": "Hvis du havde problemer med gennemgangsprocessen eller har brug for hjælp, skal du bare svare på denne e-mail — jeg vil meget gerne hjælpe!"
},
"creditDenied": {
"subject": "Om dine gratis Nomad Karaoke-kreditter",
"greeting": "Hej,",
"thankYou": "Tak fordi du tilmeldte dig Nomad Karaoke!",
"deniedMessage": "Desværre kunne vi ikke tildele dine gratis {credit_type} denne gang. Vores system opdagede mønstre, der tyder på, at dette måske ikke er din første konto hos os, og hver karaoke-generering koster os rigtige penge i cloud computing og API-gebyrer.",
"mistakeNote": "Vi forstår fuldt ud, hvis dette er en fejl! Hvis du er en ægte ny bruger, skal du bare svare på denne e-mail og lade Andrew (grundlæggeren) vide det. Han byggede denne tjeneste og giver dig gerne nogle gratis kreditter til at prøve det — han beder bare om, at du giver ærlig feedback på oplevelsen til gengæld.",
"buyPrompt": "Hvis du vil i gang med det samme, kan du også købe kreditter:",
"buyButton": "Køb kreditter",
"costNote": "Vi holder omkostningerne nede, så vi kan tilbyde tjenesten til en overkommelig pris, hvilket betyder, at vi skal være forsigtige med misbrug af gratis kreditter. Tak for din forståelse!",
"welcomeCredits": "velkomstkreditter",
"feedbackCredits": "feedback-bonuskreditter"
},
"madeForYouConfirmation": {
"subject": "Ordrebekræftelse: {artist} - {title} | Nomad Karaoke",
"thankYou": "Tak for din ordre!",
"orderDetails": "Ordredetaljer",
"orderId": "Ordre-ID:",
"artist": "Kunstner:",
"title": "Titel:",
"yourNotes": "Dine noter:",
"deliveryTime": "Vores team vil oprette din brugerdefinerede karaokevideo inden for {hours} timer.",
"deliveryNotice": "Du modtager en e-mail med download-links, så snart din video er klar.",
"noAction": "Ingen handling påkrævet — læn dig tilbage, så tager vi os af alt!"
},
"shared": {
"footerHelp": "Hvis noget ikke er perfekt, skal du bare svare på denne e-mail, så ordner jeg det!"
},
"templates": {
"jobCompletion": {
"greeting": "Hej {name},",
"thanks": "Tak for din ordre!",
"youtubeLink": "Her er linket til karaokevideoen, der er udgivet på YouTube:",
"dropboxIntro": "Her er Dropbox-mappen med alle de færdige filer og kildefiler, herunder:",
"fileList": "- \"(Final Karaoke Lossless).mkv\": kombineret karaokevideo i 4K H264 med tabsfri FLAC-lyd\n- \"(Final Karaoke).mp4\": kombineret karaokevideo med titel/slutskærm i 4K H264/AAC\n- \"(Final Karaoke 720p).mp4\": kombineret karaokevideo i 720p H264/AAC (mindre fil til ældre systemer)\n- \"(With Vocals).mp4\": syng-med-video i 4K H264/AAC med original vokal\n- \"(Karaoke).mov\": karaokevideo-output fra MidiCo (ingen titel/slutskærm)\n- \"(Title).mov\"/\"(End).mov\": titelkort og slutskærmsvideoer\n- \"(Final Karaoke CDG).zip\": CDG+MP3-format til ældre/kommercielle karaokesystemer\n- \"(Final Karaoke TXT).zip\": TXT+MP3-format til Power Karaoke\n- stems/*.flac: forskellige adskilte instrumentale og vokale lyd-stems i tabsfrit format\n- lyrics/*.txt sangtekster fra forskellige kilder i almindeligt tekstformat",
"fixOffer": "Lad mig vide, hvis noget ikke er perfekt, så tilpasser/retter jeg det gerne, eller hvis du har brug for det i et andet format, kan jeg sandsynligvis konvertere det for dig!",
"feedbackRequest": "Hvis du har et øjeblik, vil jeg virkelig sætte pris på din feedback (tager 2 minutter):",
"signOff": "Tak igen og hav en god dag!\n-Andrew",
"youtubeQueued": "Din YouTube-upload er i kø og vil blive behandlet automatisk. Du modtager en opfølgende e-mail med linket om kort tid."
},
"actionLyrics": {
"greeting": "Hej {name},",
"ready": "Din karaokevideo til \"{artist} - {title}\" er klar til gennemgang!",
"instructions": "Vores system har transskriberet og synkroniseret sangteksten, men den kan have brug for nogle rettelser. Du vil også kunne vælge dit foretrukne instrumentalspor (med eller uden backingvokal).",
"reviewPrompt": "Gennemgå venligst din sangtekst og vælg en instrumental:",
"duration": "Dette tager normalt kun et par minutter.",
"signOff": "Tak!\n-Andrew"
},
"actionInstrumental": {
"greeting": "Hej {name},",
"almostDone": "Din karaokevideo til \"{artist} - {title}\" er næsten færdig!",
"instructions": "Vi har adskilt lyden i forskellige versioner. Vælg venligst, hvilket instrumentalspor du vil bruge til den endelige video.",
"selectPrompt": "Vælg din instrumental her:",
"signOff": "Tak!\n-Andrew"
},
"youtubeComplete": {
"greeting": "Hej {name},",
"greatNews": "Gode nyheder! Din karaokevideo til \"{artist} - {title}\" er blevet uploadet til YouTube:",
"delayNote": "Denne upload blev kortvarigt forsinket, mens vores systemer behandlede andre uploads, men alt er klar nu.",
"signOff": "Tak!\n-Andrew"
}
}
}
}
+338
View File
@@ -0,0 +1,338 @@
{
"auth": {
"unknownService": "Unbekannter Dienst: {service}",
"invalidCredentials": "Die folgenden Dienste müssen neu autorisiert werden: {services}",
"validCredentials": "Alle angeforderten Anmeldeinformationen sind gültig",
"youtubeAuthInstructions": "Besuche {verification_url} und gib den Code ein: {user_code}",
"youtubeAuthStartFailed": "YouTube-Geräteauthentifizierung konnte nicht gestartet werden: {error}",
"gdriveLinkInstructions": "Besuche {verification_url} und gib den Code ein: {user_code}",
"gdriveAuthStartFailed": "Google Drive-Geräteauthentifizierung konnte nicht gestartet werden: {error}",
"discordAlertNotConfigured": "Discord-Alert-Webhook nicht konfiguriert"
},
"jobs": {
"created": "Auftrag erfolgreich erstellt. Verarbeitung gestartet.",
"authError": "Authentifizierungsfehler: keine Benutzeridentität verfügbar",
"noDefaultTheme": "Kein Standard-Theme konfiguriert. Bitte kontaktiere den Support oder gib eine theme_id an.",
"notFound": "Auftrag nicht gefunden",
"noPermissionAccess": "Du hast keine Berechtigung, auf diesen Auftrag zuzugreifen",
"noPermissionEdit": "Du hast keine Berechtigung, diesen Auftrag zu bearbeiten",
"noPermissionDelete": "Du hast keine Berechtigung, diesen Auftrag zu löschen",
"noPermissionModify": "Du hast keine Berechtigung, diesen Auftrag zu ändern",
"notCompleted": "Nur abgeschlossene Aufträge können bearbeitet werden. Aktueller Status: {status}",
"alreadyBeingEdited": "Dieser Auftrag wird bereits bearbeitet (Ausgaben wurden bereits gelöscht)",
"cleanupFailed": "Bereinigung für {services} fehlgeschlagen. Auftrag nicht geändert. Bitte versuche es erneut oder kontaktiere den Support.",
"reopened": "Track zur Bearbeitung wieder geöffnet. Vorherige Ausgaben wurden entfernt.",
"invalidDatetimeFormat": "Ungültiges {field}-Format: {value}",
"listError": "Fehler beim Auflisten der Aufträge: {error}",
"deleteError": "Fehler beim Löschen von Auftrag {job_id}: {error}",
"deletionPreview": "Füge &confirm=true hinzu, um die Löschung auszuführen",
"deletionRequiresFilters": "Mindestens ein Filter (environment, client_id, status, created_before) ist erforderlich",
"bulkDeleteError": "Fehler beim massenhaften Löschen von Aufträgen: {error}",
"reviewNotReady": "Auftrag nicht bereit zur Überprüfung (aktueller Status: {status})",
"correctionsUnavailable": "Korrekturdaten nicht verfügbar",
"audioUnavailable": "Audio nicht zur Überprüfung verfügbar",
"reviewCannotStart": "Überprüfung kann nicht gestartet werden",
"jobNotInReviewState": "Auftrag nicht im Überprüfungsstatus (aktueller Status: {status})",
"correctionsProcessing": "Korrekturen gespeichert. Rufe /complete-review auf, wenn du fertig bist.",
"editLogSaveFailed": "Fehler beim Speichern des Bearbeitungsprotokolls für Auftrag {job_id}: {error}",
"stemsMissing": "Dem Auftrag fehlen erforderliche Stems (instrumental_clean und/oder backing_vocals)",
"customInstrumentalFailed": "Fehler beim Erstellen des benutzerdefinierten Instrumentals für Auftrag {job_id}: {error}",
"audioProcessingFailed": "Fehler beim Verarbeiten der Audiodatei: {error}",
"durationMismatch": "Dauer stimmt nicht überein: Die hochgeladene Datei ist {upload_duration}s lang, aber das Original-Audio ist {original_duration}s lang. Das Instrumental muss genau {original_duration}s (±0.5s) lang sein.",
"reviewNotInState": "Auftrag nicht im Überprüfungsstatus (aktueller Status: {status})",
"noLyricsDetected": "Überprüfung kann nicht abgeschlossen werden: Es wurde kein Text im Audio erkannt. Dies kann passieren, wenn das Eingabe-Audio keinen Gesang enthält (z. B. ein Karaoke-Track oder Instrumental). Du kannst zurückgehen und den Text manuell mit 'Alle ersetzen' einfügen oder diesen Auftrag abbrechen und es mit einer Audiodatei versuchen, die Gesang enthält.",
"reviewCompleteStartRendering": "Überprüfung abgeschlossen. Rendern des Videos gestartet.",
"reviewCompleteError": "Fehler beim Abschließen der Überprüfung für Auftrag {job_id}: {error}",
"instrumentalSelectionRequired": "instrumental_selection ist erforderlich. Muss 'clean' oder 'with_backing' sein.",
"invalidInstrumentalSelection": "Ungültige instrumental_selection. Muss eines der folgenden sein: {valid_selections}",
"instrumentalSelected": "Instrumental ausgewählt. Video-Generierung gestartet.",
"instrumentalSelectionError": "Fehler bei der Auswahl des Instrumentals für Auftrag {job_id}: {error}",
"downloadUrlsError": "Fehler beim Abrufen der Download-URLs: {error}"
},
"review": {
"jobNotFound": "Auftrag nicht gefunden",
"reviewNotReady": "Auftrag nicht bereit zur Überprüfung (aktueller Status: {status})",
"correctionsNotFound": "Korrekturdaten nicht gefunden. Die Textverarbeitung ist möglicherweise nicht abgeschlossen.",
"correctionsLoadFailed": "Fehler beim Laden der Korrekturen: {error}",
"audioNotFound": "Audiodatei nicht gefunden",
"audioServeError": "Fehler beim Bereitstellen von Audio: {error}",
"instrumentalSelectionRequired": "instrumental_selection ist erforderlich. Muss 'clean' oder 'with_backing' sein.",
"invalidInstrumentalSelection": "Ungültige instrumental_selection. Muss eines der folgenden sein: {valid_selections}",
"reviewCompletedError": "Fehler beim Abschließen der Überprüfung: {error}",
"handlersUpdateNotImplemented": "Handler-Updates noch nicht implementiert",
"lyricsAddError": "Fehler beim Hinzufügen des Textes: {error}",
"lyricsAddInvalidRequest": "Ungültige Anfrage zum Hinzufügen von Text: {error}",
"lyricsSearchError": "Fehler bei der Textsuche: {error}",
"lyricsSearchInvalidRequest": "Ungültige Anfrage zur Textsuche: {error}",
"lyricsSearchNoResults": "Kein passender Text von einem Anbieter gefunden",
"previewVideoGenerationError": "Fehler beim Generieren des Vorschau-Videos: {error}",
"previewVideoNotFound": "Vorschau-Video nicht gefunden",
"previewVideoStreamError": "Fehler beim Streamen des Vorschau-Videos: {error}",
"annotationSaveError": "Fehler beim Speichern der Anmerkungen: {error}",
"waveformGenerationError": "Fehler beim Generieren der Wellenform-Daten: {error}",
"waveformNoAudio": "Kein Audio für Wellenform verfügbar",
"sessionSaveError": "Korrekturdaten sind erforderlich"
},
"audioSearch": {
"notEnabled": "Die Audiosuche ist für diesen Mandanten nicht aktiviert",
"disabled": "Die Audiosuche ist nicht verfügbar",
"downloadError": "Download für Auftrag {job_id} fehlgeschlagen: {error}",
"jobNotFound": "Auftrag {job_id} nicht gefunden",
"noSearchResults": "Keine Suchergebnisse verfügbar",
"invalidSelectionIndex": "Ungültiger Auswahlindex {selection_index}. Gültiger Bereich: 0-{max}",
"selectionError": "Fehler bei der Audioauswahl für Auftrag {job_id}: {error}",
"youtubeDownloadError": "YouTube-Download fehlgeschlagen: {error}",
"torrentDownloadError": "Download von {source} ohne Remote-flacfetch-Dienst nicht möglich. Konfiguriere FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Keine source_id oder remote_search_id für den {source}-Download verfügbar",
"remoteDownloadCompleteNoPath": "Remote-Download abgeschlossen, aber kein Dateipfad zurückgegeben",
"spotifyDownloadError": "Download von Spotify ohne Remote-flacfetch-Dienst nicht möglich. Konfiguriere FLACFETCH_API_URL.",
"genericDownloadError": "Unbekannter Quelltyp: {source}, versuche generischen Download",
"jobNotFoundDuringDownload": "Auftrag {job_id} während des Hintergrund-Downloads nicht gefunden",
"selectAudioError": "Fehler bei der Audioauswahl für Auftrag {job_id}: {error}",
"searchAudioError": "Fehler bei der Audiosuche: {error}",
"searchCreatedSuccessfully": "Auftrag erstellt. Suche nach Audio...",
"autoDownloadStarted": "Bestes Ergebnis automatisch ausgewählt. Download startet..."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
"magicLinkSent": "Wenn diese E-Mail registriert ist, erhältst du in Kürze einen Anmeldelink.",
"emailServiceNotConfigured": "E-Mail-Dienst ist nicht verfügbar. Bitte kontaktiere den Support.",
"emailDomainNotAllowed": "E-Mail-Domain für diesen Mandanten nicht zulässig",
"invalidToken": "Ungültiges Token",
"verifyError": "Verifizierung fehlgeschlagen: {message}",
"magicLinkSuccess": "Erfolgreich angemeldet",
"logoutSuccess": "Erfolgreich abgemeldet",
"userNotFound": "Benutzer nicht gefunden",
"creditPackagesError": "Fehler beim Laden der Guthaben-Pakete: {error}",
"stripeSendError": "Fehler beim Senden des Stripe-Checkout-Links: {error}",
"stripeWebhookProcessingError": "Fehler bei der Verarbeitung des Stripe-Webhooks: {error}",
"feedbackSaveError": "Fehler beim Speichern des Feedbacks: {error}",
"feedbackNotEligible": "Benutzer ist nicht für Feedback berechtigt"
},
"fileUpload": {
"invalidTheme": "Theme nicht gefunden: {theme_id}. Verwende GET /api/themes, um verfügbare Themes aufzulisten.",
"uploadSuccess": "Datei erfolgreich hochgeladen. Verarbeitung gestartet.",
"uploadError": "Fehler beim Hochladen der Datei: {error}",
"urlDownloadError": "Fehler beim Herunterladen von der URL: {error}",
"invalidContentType": "Ungültiger Inhaltstyp: {content_type}",
"fileSizeError": "Datei ist zu groß: {size}. Maximum: {max_size}",
"invalidFileType": "Ungültiger Dateityp: {file_type}",
"multipleAudioFilesNotAllowed": "Es kann nur eine Audiodatei hochgeladen werden",
"noAudioFileProvided": "Keine Audiodatei bereitgestellt",
"urlCreationSuccess": "Auftrag erstellt. Upload-URLs generiert.",
"urlCreationError": "Fehler beim Erstellen des Auftrags mit Upload-URLs: {error}",
"uploadsCompleteSuccess": "Uploads abgeschlossen. Verarbeitung gestartet.",
"uploadsCompleteError": "Fehler beim Abschließen der Uploads: {error}",
"noUploadedFiles": "Keine hochgeladenen Dateien angegeben",
"styleUploadUrlsSuccess": "Style-Upload-URLs generiert.",
"styleUploadsCompleteSuccess": "Style-Dateien aktualisiert. Verarbeitung neu gestartet.",
"styleUploadsCompleteError": "Fehler beim Abschließen der Style-Uploads: {error}"
},
"catalog": {
"rateLimitExceeded": "Ratenlimit überschritten. Maximal {max_requests} Kataloganfragen pro Minute.",
"catalogSearchError": "Fehler bei der Katalogsuche: {error}",
"communityCheckError": "Fehler beim Überprüfen der Community-Versionen: {error}"
},
"themes": {
"themesLoadError": "Fehler beim Laden der Themes",
"themeNotFound": "Theme nicht gefunden: {theme_id}",
"themeLoadError": "Fehler beim Laden des Themes",
"previewNotAvailable": "Keine Vorschau für Theme verfügbar: {theme_id}",
"previewLoadError": "Fehler beim Laden der Theme-Vorschau",
"youtubeDescriptionNotFound": "Theme nicht gefunden: {theme_id}",
"youtubeDescriptionLoadError": "Fehler beim Laden der YouTube-Beschreibung"
},
"tenant": {
"assetNotFound": "Asset nicht gefunden"
},
"push": {
"disabled": "Push-Benachrichtigungen sind nicht aktiviert",
"userEmailNotAvailable": "Benutzer-E-Mail nicht verfügbar",
"missingEncryptionKeys": "Erforderliche Schlüssel fehlen (p256dh, auth)",
"subscriptionSaveFailed": "Fehler beim Speichern des Abonnements",
"subscriptionRegistered": "Push-Abonnement erfolgreich registriert",
"subscriptionNotFound": "Abonnement entfernt (oder nicht gefunden)",
"subscriptionRemoved": "Push-Abonnement erfolgreich entfernt",
"testNotificationSent": "Test-Benachrichtigung an {sent_count} Gerät(e) gesendet"
},
"pushNotifications": {
"reviewLyricsTitle": "Textüberprüfung",
"reviewLyricsBody": "\"{title}\" von {artist} benötigt eine Textüberprüfung",
"selectInstrumentalTitle": "Instrumental auswählen",
"selectInstrumentalBody": "\"{title}\" von {artist} benötigt eine Instrumentalauswahl",
"videoReadyTitle": "Video fertig!",
"videoReadyBody": "Dein Karaoke-Video für \"{title}\" von {artist} ist bereit zum Herunterladen"
},
"admin": {
"invalidDomainFormat": "Ungültiges Domain-Format",
"domainAddedToBl": "Domain '{domain}' zur Sperrliste für Wegwerf-Domains hinzugefügt",
"domainNotFoundInBl": "Domain nicht in der Sperrliste gefunden",
"domainRemovedFromBl": "Domain '{domain}' aus der Sperrliste für Wegwerf-Domains entfernt",
"domainAddedToAllowlist": "Domain '{domain}' zur Erlaubnisliste hinzugefügt",
"domainNotFoundInAllowlist": "Domain nicht in der Erlaubnisliste gefunden",
"domainRemovedFromAllowlist": "Domain '{domain}' aus der Erlaubnisliste entfernt",
"syncComplete": "{external_count} externe Domains synchronisiert ({added} hinzugefügt, {removed} entfernt)",
"invalidEmailFormat": "Ungültiges E-Mail-Format",
"emailAddedToBl": "E-Mail '{email}' zur Liste blockierter E-Mails hinzugefügt",
"emailNotFoundInBl": "E-Mail nicht in der Sperrliste gefunden",
"emailRemovedFromBl": "E-Mail '{email}' aus der Liste blockierter E-Mails entfernt",
"invalidIPAddress": "Ungültige IP-Adresse",
"ipAddedToBl": "IP '{ip_address}' zur Liste blockierter IPs hinzugefügt",
"ipNotFoundInBl": "IP nicht in der Sperrliste gefunden",
"ipRemovedFromBl": "IP '{ip_address}' aus der Liste blockierter IPs entfernt",
"youtubeUploadNotFound": "Upload nicht gefunden oder nicht in einem wiederholbaren Status für Auftrag {job_id}",
"youtubeUploadQueuedForRetry": "YouTube-Upload für Auftrag {job_id} für erneuten Versuch in die Warteschlange eingereiht",
"youtubeQueueProcessingStarted": "Verarbeitung der YouTube-Warteschlange im Hintergrund gestartet"
},
"rateLimits": {
"configNotFound": "Ratenlimit-Konfiguration nicht gefunden: {config_id}",
"configUpdateError": "Fehler beim Aktualisieren der Ratenlimit-Konfiguration: {error}"
},
"errors": {
"insufficientCredits": "Unzureichendes Guthaben für diesen Vorgang",
"insufficientCreditsBuyUrl": "/#pricing"
},
"emails": {
"magicLink": {
"subject": "Melde dich bei {brand_name} an",
"greeting": "Hallo,",
"signInPrompt": "Klicke auf den untenstehenden Button, um dich bei {brand_name} anzumelden:",
"signInButton": "Anmelden",
"expiryWarning": "Dieser Link läuft in 15 Minuten ab und kann nur einmal verwendet werden.",
"fallbackLink": "Wenn der Button nicht funktioniert, kopiere diesen Link und füge ihn in deinen Browser ein:",
"ignoreNote": "Wenn du diese E-Mail nicht angefordert hast, kannst du sie getrost ignorieren."
},
"welcome": {
"subject": "Willkommen bei Nomad Karaoke!",
"welcomeGreeting": "Willkommen bei Nomad Karaoke!",
"turnAnySong": "Verwandle jeden Song in wenigen Minuten in ein professionelles Karaoke-Video.",
"freeCreditsLabel": "Kostenloses Guthaben",
"freeCreditsNote": "Mit jedem Guthaben kannst du ein professionelles Karaoke-Video erstellen",
"howItWorks": "So funktioniert's:",
"step1Title": "1. Suche nach einem Song",
"step1Desc": "Gib den Künstler und den Titel ein, und wir finden hochwertiges Audio.",
"step2Title": "2. Unser System zaubert",
"step2Desc": "Wir trennen den Gesang, transkribieren den Text und synchronisieren alles perfekt.",
"step3Title": "3. Überprüfen & anpassen",
"step3Desc": "Passe den Text bei Bedarf an und wähle dein Instrumental.",
"step4Title": "4. Hol dir dein Video",
"step4Desc": "Lade dein 4K-Karaoke-Video herunter oder lade es direkt auf YouTube hoch.",
"feedbackBonus": "Erstelle 2 Videos und erhalte 2 weitere kostenlose Guthaben, indem du dein Feedback mit uns teilst!",
"getStartedButton": "Loslegen"
},
"creditsAdded": {
"subject": "{credits} Guthaben zu deinem Nomad Karaoke-Konto hinzugefügt",
"greatNews": "Gute Neuigkeiten!",
"creditsAddedMessage": "{credits} Guthaben wurden deinem Konto hinzugefügt.",
"yourBalance": "Dein Kontostand:",
"credits": "Guthaben",
"eachCreditLets": "Mit jedem Guthaben kannst du ein professionelles Karaoke-Video erstellen mit:",
"featureVocalSeparation": "KI-gestützte Gesangs- und Instrumentaltrennung",
"featureLyrics": "Synchronisierter Text mit Timing auf Wortebene",
"feature4k": "4K-Videoausgabe",
"featureYoutube": "YouTube-Upload",
"createButton": "Jetzt Karaoke erstellen"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (Dein Karaoke-Video ist fertig!)",
"subject": "{artist} - {title} (Dein Karaoke-Video ist fertig!)",
"subjectFallback": "Dein Karaoke-Video ist fertig!"
},
"youtubeUpload": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (YouTube-Upload bereit!)",
"subject": "{artist} - {title} (YouTube-Upload bereit!)",
"subjectFallback": "Dein YouTube-Upload ist bereit!"
},
"actionReminder": {
"lyricsSubject": "Aktion erforderlich: Textüberprüfung für {artist} - {title}",
"lyricsSubjectFallback": "Aktion erforderlich: Textüberprüfung",
"instrumentalSubject": "Aktion erforderlich: Instrumental auswählen für {artist} - {title}",
"instrumentalSubjectFallback": "Aktion erforderlich: Instrumental auswählen",
"audioEditSubject": "Aktion erforderlich für {artist} - {title}",
"audioEditSubjectFallback": "Aktion erforderlich",
"alertHeading": "Dein Karaoke-Video benötigt deine Eingabe!"
},
"reviewReminder": {
"subject": "Erinnerung: Dein Karaoke-Video wartet auf Überprüfung — {artist} - {title}",
"subjectFallback": "Erinnerung: Dein Karaoke-Video wartet auf Überprüfung",
"alertHeading": "Dein Karaoke-Video wartet auf dich!",
"reminderIntro": "Nur eine kurze Erinnerung, dass dein Karaoke-Video{song_name} zur Überprüfung bereit ist.",
"reviewButton": "Dein Video überprüfen",
"reviewInstructions": "Während der Überprüfung kannst du kontrollieren, ob der Text korrekt ist, und deine bevorzugte Instrumentalspur auswählen. Das dauert normalerweise nur ein paar Minuten!",
"helpOffer": "Wenn du Probleme mit dem Überprüfungsprozess hast, antworte einfach auf diese E-Mail und ich helfe dir gerne weiter.",
"expiryWarning": "Bitte beachte: Wenn die Überprüfung nicht innerhalb der nächsten 24 Stunden abgeschlossen wird, läuft der Auftrag automatisch ab und dein Guthaben wird erstattet."
},
"reviewExpired": {
"subject": "Dein Karaoke-Video ist abgelaufen — {artist} - {title}",
"subjectFallback": "Dein Karaoke-Video ist abgelaufen",
"cancelNotice": "Dein Karaoke-Video{song_name} wurde automatisch abgebrochen, da die Überprüfung nicht innerhalb von 48 Stunden abgeschlossen wurde.",
"refundNotice": "Keine Sorge — dein Guthaben wurde erstattet! Dein aktueller Kontostand beträgt {credits_balance} {credits_word}.",
"creditSingular": "Guthaben",
"creditPlural": "Guthaben",
"createNewPrompt": "Du kannst jederzeit ein neues Karaoke-Video mit deinem Guthaben erstellen:",
"createButton": "Neues Video erstellen",
"helpOffer": "Wenn du Probleme mit dem Überprüfungsprozess hattest oder Hilfe benötigst, antworte einfach auf diese E-Mail — ich helfe dir gerne!"
},
"creditDenied": {
"subject": "Über dein kostenloses Nomad Karaoke-Guthaben",
"greeting": "Hallo,",
"thankYou": "Danke für deine Anmeldung bei Nomad Karaoke!",
"deniedMessage": "Leider konnten wir dir dieses Mal dein kostenloses {credit_type} nicht gewähren. Unser System hat Muster erkannt, die darauf hindeuten, dass dies möglicherweise nicht dein erstes Konto bei uns ist, und jeder Karaoke-Generierungsauftrag kostet uns echtes Geld für Cloud-Computing und API-Gebühren.",
"mistakeNote": "Wir verstehen vollkommen, wenn das ein Fehler ist! Wenn du ein echter neuer Benutzer bist, antworte einfach auf diese E-Mail und lass es Andrew (dem Gründer) wissen. Er hat diesen Dienst entwickelt und gibt dir gerne etwas kostenloses Guthaben zum Ausprobieren — er bittet dich nur darum, im Gegenzug ehrliches Feedback zu deinen Erfahrungen zu geben.",
"buyPrompt": "Wenn du sofort loslegen möchtest, kannst du auch Guthaben kaufen:",
"buyButton": "Guthaben kaufen",
"costNote": "Wir halten die Kosten niedrig, damit wir den Dienst günstig anbieten können, was bedeutet, dass wir bei Missbrauch von kostenlosem Guthaben vorsichtig sein müssen. Danke für dein Verständnis!",
"welcomeCredits": "Willkommensguthaben",
"feedbackCredits": "Feedback-Bonus-Guthaben"
},
"madeForYouConfirmation": {
"subject": "Bestellung bestätigt: {artist} - {title} | Nomad Karaoke",
"thankYou": "Vielen Dank für deine Bestellung!",
"orderDetails": "Bestelldetails",
"orderId": "Bestell-ID:",
"artist": "Künstler:",
"title": "Titel:",
"yourNotes": "Deine Notizen:",
"deliveryTime": "Unser Team wird dein benutzerdefiniertes Karaoke-Video innerhalb von {hours} Stunden erstellen.",
"deliveryNotice": "Du erhältst eine E-Mail mit Download-Links, sobald dein Video fertig ist.",
"noAction": "Keine Aktion erforderlich — lehn dich zurück und wir kümmern uns um alles!"
},
"shared": {
"footerHelp": "Wenn etwas nicht perfekt ist, antworte einfach auf diese E-Mail und ich werde es beheben!"
},
"templates": {
"jobCompletion": {
"greeting": "Hallo {name},",
"thanks": "Danke für deine Bestellung!",
"youtubeLink": "Hier ist der Link für das auf YouTube veröffentlichte Karaoke-Video:",
"dropboxIntro": "Hier ist der Dropbox-Ordner mit allen fertigen Dateien und Quelldateien, einschließlich:",
"fileList": "- \"(Final Karaoke Lossless).mkv\": kombiniertes Karaoke-Video in 4K H264 mit verlustfreiem FLAC-Audio\n- \"(Final Karaoke).mp4\": kombiniertes Karaoke-Video mit Titelbildschirm/Endbildschirm in 4K H264/AAC\n- \"(Final Karaoke 720p).mp4\": kombiniertes Karaoke-Video in 720p H264/AAC (kleinere Datei für ältere Systeme)\n- \"(With Vocals).mp4\": Video zum Mitsingen in 4K H264/AAC mit Originalgesang\n- \"(Karaoke).mov\": Karaoke-Videoausgabe von MidiCo (ohne Titelbildschirm/Endbildschirm)\n- \"(Title).mov\"/\"(End).mov\": Titelkarte und Endbildschirm-Videos\n- \"(Final Karaoke CDG).zip\": CDG+MP3-Format für ältere/kommerzielle Karaoke-Systeme\n- \"(Final Karaoke TXT).zip\": TXT+MP3-Format für Power Karaoke\n- stems/*.flac: verschiedene getrennte Instrumental- und Gesangs-Audio-Stems im verlustfreien Format\n- lyrics/*.txt Songtexte aus verschiedenen Quellen im reinen Textformat",
"fixOffer": "Lass mich wissen, wenn etwas nicht perfekt ist, und ich werde es gerne anpassen / beheben, oder wenn du es in einem anderen Format benötigst, kann ich es wahrscheinlich für dich konvertieren!",
"feedbackRequest": "Wenn du einen Moment Zeit hast, würde ich mich sehr über dein Feedback freuen (dauert 2 Minuten):",
"signOff": "Nochmals vielen Dank und einen schönen Tag!\n-Andrew",
"youtubeQueued": "Dein YouTube-Upload ist in der Warteschlange und wird automatisch verarbeitet. Du erhältst in Kürze eine Folge-E-Mail mit dem Link."
},
"actionLyrics": {
"greeting": "Hallo {name},",
"ready": "Dein Karaoke-Video für \"{artist} - {title}\" ist bereit zur Überprüfung!",
"instructions": "Unser System hat den Text transkribiert und synchronisiert, aber er benötigt möglicherweise einige Korrekturen. Du kannst auch deine bevorzugte Instrumentalspur (mit oder ohne Hintergrundgesang) auswählen.",
"reviewPrompt": "Bitte überprüfe deinen Text und wähle ein Instrumental aus:",
"duration": "Das dauert normalerweise nur ein paar Minuten.",
"signOff": "Danke!\n-Andrew"
},
"actionInstrumental": {
"greeting": "Hallo {name},",
"almostDone": "Dein Karaoke-Video für \"{artist} - {title}\" ist fast fertig!",
"instructions": "Wir haben das Audio in verschiedene Versionen getrennt. Bitte wähle aus, welche Instrumentalspur du für das endgültige Video verwenden möchtest.",
"selectPrompt": "Wähle hier dein Instrumental aus:",
"signOff": "Danke!\n-Andrew"
},
"youtubeComplete": {
"greeting": "Hallo {name},",
"greatNews": "Gute Neuigkeiten! Dein Karaoke-Video für \"{artist} - {title}\" wurde auf YouTube hochgeladen:",
"delayNote": "Dieser Upload wurde kurzzeitig verzögert, während unsere Systeme andere Uploads verarbeitet haben, aber jetzt ist alles bereit.",
"signOff": "Danke!\n-Andrew"
}
}
}
}
+338
View File
@@ -0,0 +1,338 @@
{
"auth": {
"unknownService": "Άγνωστη υπηρεσία: {service}",
"invalidCredentials": "Οι ακόλουθες υπηρεσίες χρειάζονται εκ νέου εξουσιοδότηση: {services}",
"validCredentials": "Όλα τα διαπιστευτήρια που ζητήθηκαν είναι έγκυρα",
"youtubeAuthInstructions": "Επισκέψου το {verification_url} και εισήγαγε τον κωδικό: {user_code}",
"youtubeAuthStartFailed": "Αποτυχία εκκίνησης ελέγχου ταυτότητας συσκευής YouTube: {error}",
"gdriveLinkInstructions": "Επισκέψου το {verification_url} και εισήγαγε τον κωδικό: {user_code}",
"gdriveAuthStartFailed": "Αποτυχία εκκίνησης ελέγχου ταυτότητας συσκευής Google Drive: {error}",
"discordAlertNotConfigured": "Το webhook ειδοποιήσεων Discord δεν έχει ρυθμιστεί"
},
"jobs": {
"created": "Η εργασία δημιουργήθηκε με επιτυχία. Η επεξεργασία ξεκίνησε.",
"authError": "Σφάλμα ελέγχου ταυτότητας: δεν υπάρχει διαθέσιμη ταυτότητα χρήστη",
"noDefaultTheme": "Δεν έχει ρυθμιστεί προεπιλεγμένο θέμα. Επικοινώνησε με την υποστήριξη ή καθόρισε ένα theme_id.",
"notFound": "Η εργασία δεν βρέθηκε",
"noPermissionAccess": "Δεν έχεις άδεια πρόσβασης σε αυτήν την εργασία",
"noPermissionEdit": "Δεν έχεις άδεια επεξεργασίας αυτής της εργασίας",
"noPermissionDelete": "Δεν έχεις άδεια διαγραφής αυτής της εργασίας",
"noPermissionModify": "Δεν έχεις άδεια τροποποίησης αυτής της εργασίας",
"notCompleted": "Μπορείς να επεξεργαστείς μόνο ολοκληρωμένες εργασίες. Τρέχουσα κατάσταση: {status}",
"alreadyBeingEdited": "Αυτή η εργασία βρίσκεται ήδη σε επεξεργασία (τα αποτελέσματα έχουν ήδη διαγραφεί)",
"cleanupFailed": "Ο καθαρισμός απέτυχε για {services}. Η εργασία δεν τροποποιήθηκε. Δοκίμασε ξανά ή επικοινώνησε με την υποστήριξη.",
"reopened": "Το κομμάτι άνοιξε ξανά για επεξεργασία. Τα προηγούμενα αποτελέσματα έχουν αφαιρεθεί.",
"invalidDatetimeFormat": "Μη έγκυρη μορφή {field}: {value}",
"listError": "Σφάλμα κατά τη λίστα εργασιών: {error}",
"deleteError": "Σφάλμα κατά τη διαγραφή της εργασίας {job_id}: {error}",
"deletionPreview": "Πρόσθεσε &confirm=true για να εκτελέσεις τη διαγραφή",
"deletionRequiresFilters": "Απαιτείται τουλάχιστον ένα φίλτρο (environment, client_id, status, created_before)",
"bulkDeleteError": "Σφάλμα κατά τη μαζική διαγραφή εργασιών: {error}",
"reviewNotReady": "Η εργασία δεν είναι έτοιμη για έλεγχο (τρέχουσα κατάσταση: {status})",
"correctionsUnavailable": "Τα δεδομένα διορθώσεων δεν είναι διαθέσιμα",
"audioUnavailable": "Ο ήχος δεν είναι διαθέσιμος για έλεγχο",
"reviewCannotStart": "Δεν είναι δυνατή η έναρξη του ελέγχου",
"jobNotInReviewState": "Η εργασία δεν βρίσκεται σε κατάσταση ελέγχου (τρέχουσα κατάσταση: {status})",
"correctionsProcessing": "Οι διορθώσεις αποθηκεύτηκαν. Κάλεσε το /complete-review όταν τελειώσεις.",
"editLogSaveFailed": "Σφάλμα κατά την αποθήκευση του αρχείου καταγραφής επεξεργασίας για την εργασία {job_id}: {error}",
"stemsMissing": "Λείπουν τα απαιτούμενα stems από την εργασία (instrumental_clean ή/και backing_vocals)",
"customInstrumentalFailed": "Σφάλμα κατά τη δημιουργία προσαρμοσμένου instrumental για την εργασία {job_id}: {error}",
"audioProcessingFailed": "Αποτυχία επεξεργασίας αρχείου ήχου: {error}",
"durationMismatch": "Αναντιστοιχία διάρκειας: το αρχείο που ανέβασες έχει διάρκεια {upload_duration}s αλλά ο αρχικός ήχος είναι {original_duration}s. Το instrumental πρέπει να είναι ακριβώς {original_duration}s (±0.5s).",
"reviewNotInState": "Η εργασία δεν βρίσκεται σε κατάσταση ελέγχου (τρέχουσα κατάσταση: {status})",
"noLyricsDetected": "Δεν είναι δυνατή η ολοκλήρωση του ελέγχου: δεν εντοπίστηκαν στίχοι στον ήχο. Αυτό μπορεί να συμβεί όταν ο ήχος εισόδου δεν έχει φωνητικά (π.χ. ένα κομμάτι καραόκε ή instrumental). Μπορείς να πας πίσω και να επικολλήσεις τους στίχους χειροκίνητα χρησιμοποιώντας το 'Αντικατάσταση όλων', ή να ακυρώσεις αυτήν την εργασία και να δοκιμάσεις ξανά με ένα αρχείο ήχου που περιέχει φωνητικά.",
"reviewCompleteStartRendering": "Ο έλεγχος ολοκληρώθηκε. Ξεκίνησε η δημιουργία του βίντεο.",
"reviewCompleteError": "Σφάλμα κατά την ολοκλήρωση του ελέγχου για την εργασία {job_id}: {error}",
"instrumentalSelectionRequired": "Το instrumental_selection είναι υποχρεωτικό. Πρέπει να είναι 'clean' ή 'with_backing'.",
"invalidInstrumentalSelection": "Μη έγκυρο instrumental_selection. Πρέπει να είναι ένα από τα: {valid_selections}",
"instrumentalSelected": "Το instrumental επιλέχθηκε. Ξεκίνησε η δημιουργία βίντεο.",
"instrumentalSelectionError": "Σφάλμα κατά την επιλογή instrumental για την εργασία {job_id}: {error}",
"downloadUrlsError": "Σφάλμα κατά τη λήψη των URL λήψης: {error}"
},
"review": {
"jobNotFound": "Η εργασία δεν βρέθηκε",
"reviewNotReady": "Η εργασία δεν είναι έτοιμη για έλεγχο (τρέχουσα κατάσταση: {status})",
"correctionsNotFound": "Τα δεδομένα διορθώσεων δεν βρέθηκαν. Η επεξεργασία στίχων μπορεί να μην έχει ολοκληρωθεί.",
"correctionsLoadFailed": "Σφάλμα κατά τη φόρτωση των διορθώσεων: {error}",
"audioNotFound": "Το αρχείο ήχου δεν βρέθηκε",
"audioServeError": "Σφάλμα κατά την παροχή του ήχου: {error}",
"instrumentalSelectionRequired": "Το instrumental_selection είναι υποχρεωτικό. Πρέπει να είναι 'clean' ή 'with_backing'.",
"invalidInstrumentalSelection": "Μη έγκυρο instrumental_selection. Πρέπει να είναι ένα από τα: {valid_selections}",
"reviewCompletedError": "Σφάλμα κατά την ολοκλήρωση του ελέγχου: {error}",
"handlersUpdateNotImplemented": "Οι ενημερώσεις χειριστών δεν έχουν εφαρμοστεί ακόμα",
"lyricsAddError": "Αποτυχία προσθήκης στίχων: {error}",
"lyricsAddInvalidRequest": "Μη έγκυρο αίτημα προσθήκης στίχων: {error}",
"lyricsSearchError": "Αποτυχία αναζήτησης στίχων: {error}",
"lyricsSearchInvalidRequest": "Μη έγκυρο αίτημα αναζήτησης στίχων: {error}",
"lyricsSearchNoResults": "Δεν βρέθηκαν αντίστοιχοι στίχοι από κανέναν πάροχο",
"previewVideoGenerationError": "Αποτυχία δημιουργίας βίντεο προεπισκόπησης: {error}",
"previewVideoNotFound": "Το βίντεο προεπισκόπησης δεν βρέθηκε",
"previewVideoStreamError": "Σφάλμα κατά τη ροή του βίντεο προεπισκόπησης: {error}",
"annotationSaveError": "Σφάλμα κατά την αποθήκευση των σχολίων: {error}",
"waveformGenerationError": "Σφάλμα κατά τη δημιουργία δεδομένων κυματομορφής: {error}",
"waveformNoAudio": "Δεν υπάρχει διαθέσιμος ήχος για την κυματομορφή",
"sessionSaveError": "Απαιτούνται δεδομένα διόρθωσης"
},
"audioSearch": {
"notEnabled": "Η αναζήτηση ήχου δεν είναι ενεργοποιημένη για αυτόν τον μισθωτή",
"disabled": "Η αναζήτηση ήχου δεν είναι διαθέσιμη",
"downloadError": "Η λήψη απέτυχε για την εργασία {job_id}: {error}",
"jobNotFound": "Η εργασία {job_id} δεν βρέθηκε",
"noSearchResults": "Δεν υπάρχουν διαθέσιμα αποτελέσματα αναζήτησης",
"invalidSelectionIndex": "Μη έγκυρο ευρετήριο επιλογής {selection_index}. Έγκυρο εύρος: 0-{max}",
"selectionError": "Σφάλμα κατά την επιλογή ήχου για την εργασία {job_id}: {error}",
"youtubeDownloadError": "Η λήψη από το YouTube απέτυχε: {error}",
"torrentDownloadError": "Δεν είναι δυνατή η λήψη από το {source} χωρίς την απομακρυσμένη υπηρεσία flacfetch. Ρύθμισε το FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Δεν υπάρχει διαθέσιμο source_id ή remote_search_id για τη λήψη από το {source}",
"remoteDownloadCompleteNoPath": "Η απομακρυσμένη λήψη ολοκληρώθηκε αλλά δεν επιστράφηκε διαδρομή αρχείου",
"spotifyDownloadError": "Δεν είναι δυνατή η λήψη από το Spotify χωρίς την απομακρυσμένη υπηρεσία flacfetch. Ρύθμισε το FLACFETCH_API_URL.",
"genericDownloadError": "Άγνωστος τύπος πηγής: {source}, προσπάθεια γενικής λήψης",
"jobNotFoundDuringDownload": "Η εργασία {job_id} δεν βρέθηκε κατά τη λήψη στο παρασκήνιο",
"selectAudioError": "Σφάλμα κατά την επιλογή ήχου για την εργασία {job_id}: {error}",
"searchAudioError": "Σφάλμα κατά την αναζήτηση ήχου: {error}",
"searchCreatedSuccessfully": "Η εργασία δημιουργήθηκε. Αναζήτηση για ήχο...",
"autoDownloadStarted": "Το καλύτερο αποτέλεσμα επιλέχθηκε αυτόματα. Η λήψη ξεκινά..."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
"magicLinkSent": "Αν αυτό το email είναι εγγεγραμμένο, θα λάβεις έναν σύνδεσμο σύνδεσης σύντομα.",
"emailServiceNotConfigured": "Η υπηρεσία email δεν είναι διαθέσιμη. Επικοινώνησε με την υποστήριξη.",
"emailDomainNotAllowed": "Ο τομέας email δεν επιτρέπεται για αυτόν τον μισθωτή",
"invalidToken": "Μη έγκυρο διακριτικό",
"verifyError": "Η επαλήθευση απέτυχε: {message}",
"magicLinkSuccess": "Συνδέθηκες με επιτυχία",
"logoutSuccess": "Αποσυνδέθηκες με επιτυχία",
"userNotFound": "Ο χρήστης δεν βρέθηκε",
"creditPackagesError": "Σφάλμα κατά τη φόρτωση των πακέτων μονάδων: {error}",
"stripeSendError": "Σφάλμα κατά την αποστολή του συνδέσμου πληρωμής Stripe: {error}",
"stripeWebhookProcessingError": "Σφάλμα κατά την επεξεργασία του webhook του Stripe: {error}",
"feedbackSaveError": "Σφάλμα κατά την αποθήκευση των σχολίων: {error}",
"feedbackNotEligible": "Ο χρήστης δεν δικαιούται να αφήσει σχόλια"
},
"fileUpload": {
"invalidTheme": "Το θέμα δεν βρέθηκε: {theme_id}. Χρησιμοποίησε το GET /api/themes για να δεις τα διαθέσιμα θέματα.",
"uploadSuccess": "Το αρχείο ανέβηκε με επιτυχία. Η επεξεργασία ξεκίνησε.",
"uploadError": "Σφάλμα κατά το ανέβασμα του αρχείου: {error}",
"urlDownloadError": "Σφάλμα κατά τη λήψη από το URL: {error}",
"invalidContentType": "Μη έγκυρος τύπος περιεχομένου: {content_type}",
"fileSizeError": "Το αρχείο είναι πολύ μεγάλο: {size}. Μέγιστο: {max_size}",
"invalidFileType": "Μη έγκυρος τύπος αρχείου: {file_type}",
"multipleAudioFilesNotAllowed": "Μόνο ένα αρχείο ήχου μπορεί να ανέβει",
"noAudioFileProvided": "Δεν δόθηκε αρχείο ήχου",
"urlCreationSuccess": "Η εργασία δημιουργήθηκε. Δημιουργήθηκαν τα URL ανεβάσματος.",
"urlCreationError": "Σφάλμα κατά τη δημιουργία εργασίας με URL ανεβάσματος: {error}",
"uploadsCompleteSuccess": "Τα ανεβάσματα ολοκληρώθηκαν. Η επεξεργασία ξεκίνησε.",
"uploadsCompleteError": "Σφάλμα κατά την ολοκλήρωση των ανεβασμάτων: {error}",
"noUploadedFiles": "Δεν καθορίστηκαν ανεβασμένα αρχεία",
"styleUploadUrlsSuccess": "Δημιουργήθηκαν τα URL ανεβάσματος στυλ.",
"styleUploadsCompleteSuccess": "Τα αρχεία στυλ ενημερώθηκαν. Η επεξεργασία ξεκίνησε ξανά.",
"styleUploadsCompleteError": "Σφάλμα κατά την ολοκλήρωση των ανεβασμάτων στυλ: {error}"
},
"catalog": {
"rateLimitExceeded": "Υπέρβαση ορίου αιτημάτων. Μέγιστο {max_requests} αιτήματα καταλόγου ανά λεπτό.",
"catalogSearchError": "Σφάλμα κατά την αναζήτηση στον κατάλογο: {error}",
"communityCheckError": "Σφάλμα κατά τον έλεγχο των εκδόσεων της κοινότητας: {error}"
},
"themes": {
"themesLoadError": "Αποτυχία φόρτωσης θεμάτων",
"themeNotFound": "Το θέμα δεν βρέθηκε: {theme_id}",
"themeLoadError": "Αποτυχία φόρτωσης θέματος",
"previewNotAvailable": "Δεν υπάρχει διαθέσιμη προεπισκόπηση για το θέμα: {theme_id}",
"previewLoadError": "Αποτυχία φόρτωσης προεπισκόπησης θέματος",
"youtubeDescriptionNotFound": "Το θέμα δεν βρέθηκε: {theme_id}",
"youtubeDescriptionLoadError": "Αποτυχία φόρτωσης περιγραφής YouTube"
},
"tenant": {
"assetNotFound": "Το στοιχείο δεν βρέθηκε"
},
"push": {
"disabled": "Οι ειδοποιήσεις push δεν είναι ενεργοποιημένες",
"userEmailNotAvailable": "Το email του χρήστη δεν είναι διαθέσιμο",
"missingEncryptionKeys": "Λείπουν τα απαιτούμενα κλειδιά (p256dh, auth)",
"subscriptionSaveFailed": "Αποτυχία αποθήκευσης συνδρομής",
"subscriptionRegistered": "Η συνδρομή push εγγράφηκε με επιτυχία",
"subscriptionNotFound": "Η συνδρομή αφαιρέθηκε (ή δεν βρέθηκε)",
"subscriptionRemoved": "Η συνδρομή push αφαιρέθηκε με επιτυχία",
"testNotificationSent": "Η δοκιμαστική ειδοποίηση στάλθηκε σε {sent_count} συσκευή(ές)"
},
"pushNotifications": {
"reviewLyricsTitle": "Έλεγχος Στίχων",
"reviewLyricsBody": "Το \"{title}\" από {artist} χρειάζεται έλεγχο στίχων",
"selectInstrumentalTitle": "Επιλογή Instrumental",
"selectInstrumentalBody": "Το \"{title}\" από {artist} χρειάζεται επιλογή instrumental",
"videoReadyTitle": "Το Βίντεο Είναι Έτοιμο!",
"videoReadyBody": "Το καραόκε βίντεό σου για το \"{title}\" από {artist} είναι έτοιμο για λήψη"
},
"admin": {
"invalidDomainFormat": "Μη έγκυρη μορφή τομέα",
"domainAddedToBl": "Ο τομέας '{domain}' προστέθηκε στη λίστα αποκλεισμού προσωρινών τομέων",
"domainNotFoundInBl": "Ο τομέας δεν βρέθηκε στη λίστα αποκλεισμού",
"domainRemovedFromBl": "Ο τομέας '{domain}' αφαιρέθηκε από τη λίστα αποκλεισμού προσωρινών τομέων",
"domainAddedToAllowlist": "Ο τομέας '{domain}' προστέθηκε στη λίστα επιτρεπόμενων",
"domainNotFoundInAllowlist": "Ο τομέας δεν βρέθηκε στη λίστα επιτρεπόμενων",
"domainRemovedFromAllowlist": "Ο τομέας '{domain}' αφαιρέθηκε από τη λίστα επιτρεπόμενων",
"syncComplete": "Συγχρονίστηκαν {external_count} εξωτερικοί τομείς ({added} προστέθηκαν, {removed} αφαιρέθηκαν)",
"invalidEmailFormat": "Μη έγκυρη μορφή email",
"emailAddedToBl": "Το email '{email}' προστέθηκε στη λίστα αποκλεισμένων email",
"emailNotFoundInBl": "Το email δεν βρέθηκε στη λίστα αποκλεισμού",
"emailRemovedFromBl": "Το email '{email}' αφαιρέθηκε από τη λίστα αποκλεισμένων email",
"invalidIPAddress": "Μη έγκυρη διεύθυνση IP",
"ipAddedToBl": "Η IP '{ip_address}' προστέθηκε στη λίστα αποκλεισμένων IP",
"ipNotFoundInBl": "Η IP δεν βρέθηκε στη λίστα αποκλεισμού",
"ipRemovedFromBl": "Η IP '{ip_address}' αφαιρέθηκε από τη λίστα αποκλεισμένων IP",
"youtubeUploadNotFound": "Το ανέβασμα δεν βρέθηκε ή δεν είναι σε κατάσταση επανάληψης για την εργασία {job_id}",
"youtubeUploadQueuedForRetry": "Το ανέβασμα στο YouTube για την εργασία {job_id} μπήκε στην ουρά για επανάληψη",
"youtubeQueueProcessingStarted": "Η επεξεργασία της ουράς του YouTube ξεκίνησε στο παρασκήνιο"
},
"rateLimits": {
"configNotFound": "Η ρύθμιση ορίου αιτημάτων δεν βρέθηκε: {config_id}",
"configUpdateError": "Σφάλμα κατά την ενημέρωση της ρύθμισης ορίου αιτημάτων: {error}"
},
"errors": {
"insufficientCredits": "Ανεπαρκείς μονάδες (credits) για αυτήν τη λειτουργία",
"insufficientCreditsBuyUrl": "/#pricing"
},
"emails": {
"magicLink": {
"subject": "Σύνδεση στο {brand_name}",
"greeting": "Γεια σου,",
"signInPrompt": "Κάνε κλικ στο παρακάτω κουμπί για να συνδεθείς στο {brand_name}:",
"signInButton": "Σύνδεση",
"expiryWarning": "Αυτός ο σύνδεσμος λήγει σε 15 λεπτά και μπορεί να χρησιμοποιηθεί μόνο μία φορά.",
"fallbackLink": "Αν το κουμπί δεν λειτουργεί, αντέγραψε και επικόλλησε αυτόν τον σύνδεσμο στο πρόγραμμα περιήγησής σου:",
"ignoreNote": "Αν δεν ζήτησες αυτό το email, μπορείς να το αγνοήσεις με ασφάλεια."
},
"welcome": {
"subject": "Καλώς ήρθες στο Nomad Karaoke!",
"welcomeGreeting": "Καλώς ήρθες στο Nomad Karaoke!",
"turnAnySong": "Μετάτρεψε οποιοδήποτε τραγούδι σε επαγγελματικό βίντεο καραόκε μέσα σε λίγα λεπτά.",
"freeCreditsLabel": "Δωρεάν Μονάδες (Credits)",
"freeCreditsNote": "Κάθε μονάδα δημιουργεί ένα επαγγελματικό βίντεο καραόκε",
"howItWorks": "Δες πώς λειτουργεί:",
"step1Title": "1. Αναζήτησε ένα τραγούδι",
"step1Desc": "Βάλε τον καλλιτέχνη και τον τίτλο, και θα βρούμε ήχο υψηλής ποιότητας.",
"step2Title": "2. Το σύστημά μας κάνει τα μαγικά του",
"step2Desc": "Διαχωρίζουμε τα φωνητικά, μεταγράφουμε τους στίχους και τα συγχρονίζουμε όλα τέλεια.",
"step3Title": "3. Έλεγχος & προσαρμογή",
"step3Desc": "Διόρθωσε τους στίχους αν χρειάζεται, διάλεξε το instrumental σου.",
"step4Title": "4. Πάρε το βίντεό σου",
"step4Desc": "Κατέβασε το 4K καραόκε βίντεό σου ή ανέβασέ το απευθείας στο YouTube.",
"feedbackBonus": "Ολοκλήρωσε 2 βίντεο και κέρδισε 2 ακόμα δωρεάν μονάδες (credits) αφήνοντας τα σχόλιά σου!",
"getStartedButton": "Ξεκίνα"
},
"creditsAdded": {
"subject": "{credits} μονάδες προστέθηκαν στον λογαριασμό σου στο Nomad Karaoke",
"greatNews": "Υπέροχα νέα!",
"creditsAddedMessage": "{credits} μονάδες προστέθηκαν στον λογαριασμό σου.",
"yourBalance": "Το υπόλοιπό σου:",
"credits": "μονάδες",
"eachCreditLets": "Κάθε μονάδα σου επιτρέπει να δημιουργήσεις ένα επαγγελματικό βίντεο καραόκε με:",
"featureVocalSeparation": "Διαχωρισμό φωνητικών/instrumental με τεχνητή νοημοσύνη",
"featureLyrics": "Συγχρονισμένους στίχους με χρονισμό ανά λέξη",
"feature4k": "Έξοδο βίντεο 4K",
"featureYoutube": "Ανέβασμα στο YouTube",
"createButton": "Δημιούργησε Καραόκε Τώρα"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (Το καραόκε βίντεό σου είναι έτοιμο!)",
"subject": "{artist} - {title} (Το καραόκε βίντεό σου είναι έτοιμο!)",
"subjectFallback": "Το καραόκε βίντεό σου είναι έτοιμο!"
},
"youtubeUpload": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (Το ανέβασμα στο YouTube είναι έτοιμο!)",
"subject": "{artist} - {title} (Το ανέβασμα στο YouTube είναι έτοιμο!)",
"subjectFallback": "Το ανέβασμα στο YouTube είναι έτοιμο!"
},
"actionReminder": {
"lyricsSubject": "Απαιτείται ενέργεια: Έλεγξε τους στίχους για το {artist} - {title}",
"lyricsSubjectFallback": "Απαιτείται ενέργεια: Έλεγξε τους στίχους",
"instrumentalSubject": "Απαιτείται ενέργεια: Επίλεξε instrumental για το {artist} - {title}",
"instrumentalSubjectFallback": "Απαιτείται ενέργεια: Επίλεξε instrumental",
"audioEditSubject": "Απαιτείται ενέργεια για το {artist} - {title}",
"audioEditSubjectFallback": "Απαιτείται ενέργεια",
"alertHeading": "Το καραόκε βίντεό σου χρειάζεται τη συμβολή σου!"
},
"reviewReminder": {
"subject": "Υπενθύμιση: Το καραόκε βίντεό σου περιμένει για έλεγχο — {artist} - {title}",
"subjectFallback": "Υπενθύμιση: Το καραόκε βίντεό σου περιμένει για έλεγχο",
"alertHeading": "Το καραόκε βίντεό σου σε περιμένει!",
"reminderIntro": "Μια φιλική υπενθύμιση ότι το καραόκε βίντεό σου{song_name} είναι έτοιμο για έλεγχο.",
"reviewButton": "Έλεγξε το Βίντεό σου",
"reviewInstructions": "Κατά τη διάρκεια του ελέγχου, μπορείς να ελέγξεις αν οι στίχοι είναι σωστοί και να επιλέξεις το αγαπημένο σου instrumental κομμάτι. Συνήθως παίρνει μόνο λίγα λεπτά!",
"helpOffer": "Αν αντιμετωπίζεις οποιοδήποτε πρόβλημα με τη διαδικασία ελέγχου, απλώς απάντησε σε αυτό το email και θα χαρώ να σε βοηθήσω.",
"expiryWarning": "Σημείωση: αν ο έλεγχος δεν ολοκληρωθεί μέσα στις επόμενες 24 ώρες, η εργασία θα λήξει αυτόματα και η μονάδα σου (credit) θα επιστραφεί."
},
"reviewExpired": {
"subject": "Το καραόκε βίντεό σου έχει λήξει — {artist} - {title}",
"subjectFallback": "Το καραόκε βίντεό σου έχει λήξει",
"cancelNotice": "Το καραόκε βίντεό σου{song_name} ακυρώθηκε αυτόματα επειδή ο έλεγχος δεν ολοκληρώθηκε μέσα σε 48 ώρες.",
"refundNotice": "Μην ανησυχείς — η μονάδα σου (credit) επιστράφηκε! Το τρέχον υπόλοιπό σου είναι {credits_balance} {credits_word}.",
"creditSingular": "μονάδα",
"creditPlural": "μονάδες",
"createNewPrompt": "Μπορείς να δημιουργήσεις ένα νέο βίντεο καραόκε οποιαδήποτε στιγμή χρησιμοποιώντας τις μονάδες σου:",
"createButton": "Δημιουργία Νέου Βίντεο",
"helpOffer": "Αν είχες οποιοδήποτε πρόβλημα με τη διαδικασία ελέγχου ή χρειάζεσαι βοήθεια, απλώς απάντησε σε αυτό το email — θα χαρώ να βοηθήσω!"
},
"creditDenied": {
"subject": "Σχετικά με τις δωρεάν μονάδες σου στο Nomad Karaoke",
"greeting": "Γεια σου,",
"thankYou": "Ευχαριστούμε που γράφτηκες στο Nomad Karaoke!",
"deniedMessage": "Δυστυχώς, δεν μπορέσαμε να σου δώσουμε τις δωρεάν {credit_type} αυτή τη φορά. Το σύστημά μας εντόπισε μοτίβα που υποδηλώνουν ότι ίσως αυτός να μην είναι ο πρώτος σου λογαριασμός σε εμάς, και κάθε εργασία δημιουργίας καραόκε μας κοστίζει πραγματικά χρήματα σε υπολογιστικούς πόρους και χρεώσεις API.",
"mistakeNote": "Καταλαβαίνουμε απόλυτα αν πρόκειται για λάθος! Αν είσαι πραγματικά νέος χρήστης, απλώς απάντησε σε αυτό το email και ενημέρωσε τον Andrew (τον ιδρυτή). Έφτιαξε αυτήν την υπηρεσία και με χαρά θα σου δώσει μερικές δωρεάν μονάδες για να τη δοκιμάσεις — το μόνο που ζητάει είναι να αφήσεις τα ειλικρινή σου σχόλια για την εμπειρία σου ως αντάλλαγμα.",
"buyPrompt": "Αν θέλεις να ξεκινήσεις αμέσως, μπορείς επίσης να αγοράσεις μονάδες:",
"buyButton": "Αγορά Μονάδων",
"costNote": "Κρατάμε το κόστος χαμηλά για να μπορούμε να προσφέρουμε την υπηρεσία προσιτά, πράγμα που σημαίνει ότι πρέπει να είμαστε προσεκτικοί με την κατάχρηση των δωρεάν μονάδων. Ευχαριστούμε για την κατανόηση!",
"welcomeCredits": "μονάδες καλωσορίσματος",
"feedbackCredits": "μονάδες μπόνους σχολίων"
},
"madeForYouConfirmation": {
"subject": "Επιβεβαίωση Παραγγελίας: {artist} - {title} | Nomad Karaoke",
"thankYou": "Ευχαριστούμε για την Παραγγελία σου!",
"orderDetails": "Λεπτομέρειες Παραγγελίας",
"orderId": "Αναγνωριστικό Παραγγελίας:",
"artist": "Καλλιτέχνης:",
"title": "Τίτλος:",
"yourNotes": "Οι Σημειώσεις σου:",
"deliveryTime": "Η ομάδα μας θα δημιουργήσει το προσαρμοσμένο καραόκε βίντεό σου μέσα σε {hours} ώρες.",
"deliveryNotice": "Θα λάβεις ένα email με τους συνδέσμους λήψης μόλις το βίντεό σου είναι έτοιμο.",
"noAction": "Δεν χρειάζεται να κάνεις τίποτα — χαλάρωσε και θα τα φροντίσουμε όλα εμείς!"
},
"shared": {
"footerHelp": "Αν κάτι δεν είναι τέλειο, απλώς απάντησε σε αυτό το email και θα το φτιάξω!"
},
"templates": {
"jobCompletion": {
"greeting": "Γεια σου {name},",
"thanks": "Ευχαριστούμε για την παραγγελία σου!",
"youtubeLink": "Εδώ είναι ο σύνδεσμος για το καραόκε βίντεο που δημοσιεύτηκε στο YouTube:",
"dropboxIntro": "Εδώ είναι ο φάκελος Dropbox με όλα τα τελικά αρχεία και τα αρχεία προέλευσης, συμπεριλαμβανομένων:",
"fileList": "- \"(Final Karaoke Lossless).mkv\": συνδυασμένο καραόκε βίντεο σε 4K H264 με ήχο FLAC χωρίς απώλειες\n- \"(Final Karaoke).mp4\": συνδυασμένο καραόκε βίντεο με οθόνη τίτλου/τέλους σε 4K H264/AAC\n- \"(Final Karaoke 720p).mp4\": συνδυασμένο καραόκε βίντεο σε 720p H264/AAC (μικρότερο αρχείο για παλαιότερα συστήματα)\n- \"(With Vocals).mp4\": βίντεο για να τραγουδήσεις μαζί σε 4K H264/AAC με τα αρχικά φωνητικά\n- \"(Karaoke).mov\": έξοδος βίντεο καραόκε από το MidiCo (χωρίς οθόνη τίτλου/τέλους)\n- \"(Title).mov\"/\"(End).mov\": βίντεο κάρτας τίτλου και οθόνης τέλους\n- \"(Final Karaoke CDG).zip\": μορφή CDG+MP3 για παλαιότερα/εμπορικά συστήματα καραόκε\n- \"(Final Karaoke TXT).zip\": μορφή TXT+MP3 για Power Karaoke\n- stems/*.flac: διάφορα διαχωρισμένα instrumental και φωνητικά stems σε μορφή χωρίς απώλειες\n- lyrics/*.txt στίχοι τραγουδιού από διάφορες πηγές σε μορφή απλού κειμένου",
"fixOffer": "Ενημέρωσέ με αν κάτι δεν είναι τέλειο και θα το προσαρμόσω / διορθώσω με χαρά, ή αν το χρειάζεσαι σε οποιαδήποτε άλλη μορφή μπορώ πιθανώς να το μετατρέψω για σένα!",
"feedbackRequest": "Αν έχεις λίγο χρόνο, θα εκτιμούσα πραγματικά τα σχόλιά σου (παίρνει 2 λεπτά):",
"signOff": "Ευχαριστώ ξανά και να έχεις μια υπέροχη μέρα!\n-Andrew",
"youtubeQueued": "Το ανέβασμά σου στο YouTube μπήκε στην ουρά και θα επεξεργαστεί αυτόματα. Θα λάβεις ένα email παρακολούθησης με τον σύνδεσμο σύντομα."
},
"actionLyrics": {
"greeting": "Γεια σου {name},",
"ready": "Το καραόκε βίντεό σου για το \"{artist} - {title}\" είναι έτοιμο για έλεγχο!",
"instructions": "Το σύστημά μας έχει μεταγράψει και συγχρονίσει τους στίχους, αλλά ίσως χρειάζονται κάποιες διορθώσεις. Θα μπορείς επίσης να επιλέξεις το αγαπημένο σου instrumental κομμάτι (με ή χωρίς δεύτερα φωνητικά).",
"reviewPrompt": "Σε παρακαλώ έλεγξε τους στίχους σου και επίλεξε ένα instrumental:",
"duration": "Αυτό συνήθως παίρνει μόνο λίγα λεπτά.",
"signOff": "Ευχαριστώ!\n-Andrew"
},
"actionInstrumental": {
"greeting": "Γεια σου {name},",
"almostDone": "Το καραόκε βίντεό σου για το \"{artist} - {title}\" είναι σχεδόν έτοιμο!",
"instructions": "Έχουμε διαχωρίσει τον ήχο σε διαφορετικές εκδόσεις. Σε παρακαλώ επίλεξε ποιο instrumental κομμάτι θα ήθελες να χρησιμοποιήσεις για το τελικό βίντεο.",
"selectPrompt": "Επίλεξε το instrumental σου εδώ:",
"signOff": "Ευχαριστώ!\n-Andrew"
},
"youtubeComplete": {
"greeting": "Γεια σου {name},",
"greatNews": "Υπέροχα νέα! Το καραόκε βίντεό σου για το \"{artist} - {title}\" ανέβηκε στο YouTube:",
"delayNote": "Αυτό το ανέβασμα καθυστέρησε για λίγο ενώ τα συστήματά μας επεξεργάζονταν άλλα ανεβάσματα, αλλά τώρα όλα είναι έτοιμα.",
"signOff": "Ευχαριστώ!\n-Andrew"
}
}
}
}
+338
View File
@@ -0,0 +1,338 @@
{
"auth": {
"unknownService": "Unknown service: {service}",
"invalidCredentials": "The following services need re-authorization: {services}",
"validCredentials": "All requested credentials are valid",
"youtubeAuthInstructions": "Visit {verification_url} and enter code: {user_code}",
"youtubeAuthStartFailed": "Failed to start YouTube device auth: {error}",
"gdriveLinkInstructions": "Visit {verification_url} and enter code: {user_code}",
"gdriveAuthStartFailed": "Failed to start Google Drive device auth: {error}",
"discordAlertNotConfigured": "Discord alert webhook not configured"
},
"jobs": {
"created": "Job created successfully. Processing started.",
"authError": "Authentication error: no user identity available",
"noDefaultTheme": "No default theme configured. Please contact support or specify a theme_id.",
"notFound": "Job not found",
"noPermissionAccess": "You don't have permission to access this job",
"noPermissionEdit": "You don't have permission to edit this job",
"noPermissionDelete": "You don't have permission to delete this job",
"noPermissionModify": "You don't have permission to modify this job",
"notCompleted": "Only completed jobs can be edited. Current status: {status}",
"alreadyBeingEdited": "This job is already being edited (outputs were already deleted)",
"cleanupFailed": "Cleanup failed for {services}. Job not modified. Please try again or contact support.",
"reopened": "Track reopened for editing. Previous outputs have been removed.",
"invalidDatetimeFormat": "Invalid {field} format: {value}",
"listError": "Error listing jobs: {error}",
"deleteError": "Error deleting job {job_id}: {error}",
"deletionPreview": "Add &confirm=true to execute deletion",
"deletionRequiresFilters": "At least one filter (environment, client_id, status, created_before) is required",
"bulkDeleteError": "Error bulk deleting jobs: {error}",
"reviewNotReady": "Job not ready for review (current status: {status})",
"correctionsUnavailable": "Corrections data not available",
"audioUnavailable": "Audio not available for review",
"reviewCannotStart": "Cannot start review",
"jobNotInReviewState": "Job not in review state (current status: {status})",
"correctionsProcessing": "Corrections saved. Call /complete-review when done.",
"editLogSaveFailed": "Error saving edit log for job {job_id}: {error}",
"stemsMissing": "Job missing required stems (instrumental_clean and/or backing_vocals)",
"customInstrumentalFailed": "Error creating custom instrumental for job {job_id}: {error}",
"audioProcessingFailed": "Failed to process audio file: {error}",
"durationMismatch": "Duration mismatch: uploaded file is {upload_duration}s but original audio is {original_duration}s. The instrumental must be exactly {original_duration}s (±0.5s).",
"reviewNotInState": "Job not in review state (current status: {status})",
"noLyricsDetected": "Cannot complete review: no lyrics were detected in the audio. This can happen when the input audio has no vocals (e.g. a karaoke track or instrumental). You can go back and paste lyrics manually using 'Replace All', or cancel this job and try again with an audio file that contains vocals.",
"reviewCompleteStartRendering": "Review complete. Video rendering started.",
"reviewCompleteError": "Error completing review for job {job_id}: {error}",
"instrumentalSelectionRequired": "instrumental_selection is required. Must be 'clean' or 'with_backing'.",
"invalidInstrumentalSelection": "Invalid instrumental_selection. Must be one of: {valid_selections}",
"instrumentalSelected": "Instrumental selected. Video generation started.",
"instrumentalSelectionError": "Error selecting instrumental for job {job_id}: {error}",
"downloadUrlsError": "Error getting download URLs: {error}"
},
"review": {
"jobNotFound": "Job not found",
"reviewNotReady": "Job not ready for review (current status: {status})",
"correctionsNotFound": "Corrections data not found. Lyrics processing may not be complete.",
"correctionsLoadFailed": "Error loading corrections: {error}",
"audioNotFound": "Audio file not found",
"audioServeError": "Error serving audio: {error}",
"instrumentalSelectionRequired": "instrumental_selection is required. Must be 'clean' or 'with_backing'.",
"invalidInstrumentalSelection": "Invalid instrumental_selection. Must be one of: {valid_selections}",
"reviewCompletedError": "Error completing review: {error}",
"handlersUpdateNotImplemented": "Handler updates not yet implemented",
"lyricsAddError": "Failed to add lyrics: {error}",
"lyricsAddInvalidRequest": "Invalid add lyrics request: {error}",
"lyricsSearchError": "Failed to search lyrics: {error}",
"lyricsSearchInvalidRequest": "Invalid search lyrics request: {error}",
"lyricsSearchNoResults": "No matching lyrics found from any provider",
"previewVideoGenerationError": "Failed to generate preview video: {error}",
"previewVideoNotFound": "Preview video not found",
"previewVideoStreamError": "Error streaming preview video: {error}",
"annotationSaveError": "Error saving annotations: {error}",
"waveformGenerationError": "Error generating waveform data: {error}",
"waveformNoAudio": "No audio available for waveform",
"sessionSaveError": "Correction data is required"
},
"audioSearch": {
"notEnabled": "Audio search is not enabled for this tenant",
"disabled": "Audio search is not available",
"downloadError": "Download failed for job {job_id}: {error}",
"jobNotFound": "Job {job_id} not found",
"noSearchResults": "No search results available",
"invalidSelectionIndex": "Invalid selection index {selection_index}. Valid range: 0-{max}",
"selectionError": "Error during audio selection for job {job_id}: {error}",
"youtubeDownloadError": "YouTube download failed: {error}",
"torrentDownloadError": "Cannot download from {source} without remote flacfetch service. Configure FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "No source_id or remote_search_id available for {source} download",
"remoteDownloadCompleteNoPath": "Remote download completed but no file path returned",
"spotifyDownloadError": "Cannot download from Spotify without remote flacfetch service. Configure FLACFETCH_API_URL.",
"genericDownloadError": "Unknown source type: {source}, attempting generic download",
"jobNotFoundDuringDownload": "Job {job_id} not found during background download",
"selectAudioError": "Error selecting audio for job {job_id}: {error}",
"searchAudioError": "Error searching audio: {error}",
"searchCreatedSuccessfully": "Job created. Searching for audio...",
"autoDownloadStarted": "Best result selected automatically. Download starting..."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
"magicLinkSent": "If this email is registered, you will receive a sign-in link shortly.",
"emailServiceNotConfigured": "Email service is not available. Please contact support.",
"emailDomainNotAllowed": "Email domain not allowed for this tenant",
"invalidToken": "Invalid token",
"verifyError": "Verification failed: {message}",
"magicLinkSuccess": "Successfully signed in",
"logoutSuccess": "Successfully logged out",
"userNotFound": "User not found",
"creditPackagesError": "Error loading credit packages: {error}",
"stripeSendError": "Error sending Stripe checkout link: {error}",
"stripeWebhookProcessingError": "Error processing Stripe webhook: {error}",
"feedbackSaveError": "Error saving feedback: {error}",
"feedbackNotEligible": "User not eligible for feedback"
},
"fileUpload": {
"invalidTheme": "Theme not found: {theme_id}. Use GET /api/themes to list available themes.",
"uploadSuccess": "File uploaded successfully. Processing started.",
"uploadError": "Error uploading file: {error}",
"urlDownloadError": "Error downloading from URL: {error}",
"invalidContentType": "Invalid content type: {content_type}",
"fileSizeError": "File is too large: {size}. Maximum: {max_size}",
"invalidFileType": "Invalid file type: {file_type}",
"multipleAudioFilesNotAllowed": "Only one audio file can be uploaded",
"noAudioFileProvided": "No audio file provided",
"urlCreationSuccess": "Job created. Upload URLs generated.",
"urlCreationError": "Error creating job with upload URLs: {error}",
"uploadsCompleteSuccess": "Uploads complete. Processing started.",
"uploadsCompleteError": "Error completing uploads: {error}",
"noUploadedFiles": "No uploaded files specified",
"styleUploadUrlsSuccess": "Style upload URLs generated.",
"styleUploadsCompleteSuccess": "Style files updated. Processing restarted.",
"styleUploadsCompleteError": "Error completing style uploads: {error}"
},
"catalog": {
"rateLimitExceeded": "Rate limit exceeded. Maximum {max_requests} catalog requests per minute.",
"catalogSearchError": "Error searching catalog: {error}",
"communityCheckError": "Error checking community versions: {error}"
},
"themes": {
"themesLoadError": "Failed to load themes",
"themeNotFound": "Theme not found: {theme_id}",
"themeLoadError": "Failed to load theme",
"previewNotAvailable": "No preview available for theme: {theme_id}",
"previewLoadError": "Failed to load theme preview",
"youtubeDescriptionNotFound": "Theme not found: {theme_id}",
"youtubeDescriptionLoadError": "Failed to load YouTube description"
},
"tenant": {
"assetNotFound": "Asset not found"
},
"push": {
"disabled": "Push notifications are not enabled",
"userEmailNotAvailable": "User email not available",
"missingEncryptionKeys": "Missing required keys (p256dh, auth)",
"subscriptionSaveFailed": "Failed to save subscription",
"subscriptionRegistered": "Push subscription registered successfully",
"subscriptionNotFound": "Subscription removed (or was not found)",
"subscriptionRemoved": "Push subscription removed successfully",
"testNotificationSent": "Test notification sent to {sent_count} device(s)"
},
"pushNotifications": {
"reviewLyricsTitle": "Review Lyrics",
"reviewLyricsBody": "\"{title}\" by {artist} needs lyrics review",
"selectInstrumentalTitle": "Select Instrumental",
"selectInstrumentalBody": "\"{title}\" by {artist} needs instrumental selection",
"videoReadyTitle": "Video Ready!",
"videoReadyBody": "Your karaoke video for \"{title}\" by {artist} is ready to download"
},
"admin": {
"invalidDomainFormat": "Invalid domain format",
"domainAddedToBl": "Domain '{domain}' added to disposable domains blocklist",
"domainNotFoundInBl": "Domain not found in blocklist",
"domainRemovedFromBl": "Domain '{domain}' removed from disposable domains blocklist",
"domainAddedToAllowlist": "Domain '{domain}' added to allowlist",
"domainNotFoundInAllowlist": "Domain not found in allowlist",
"domainRemovedFromAllowlist": "Domain '{domain}' removed from allowlist",
"syncComplete": "Synced {external_count} external domains ({added} added, {removed} removed)",
"invalidEmailFormat": "Invalid email format",
"emailAddedToBl": "Email '{email}' added to blocked emails list",
"emailNotFoundInBl": "Email not found in blocklist",
"emailRemovedFromBl": "Email '{email}' removed from blocked emails list",
"invalidIPAddress": "Invalid IP address",
"ipAddedToBl": "IP '{ip_address}' added to blocked IPs list",
"ipNotFoundInBl": "IP not found in blocklist",
"ipRemovedFromBl": "IP '{ip_address}' removed from blocked IPs list",
"youtubeUploadNotFound": "Upload not found or not in retryable state for job {job_id}",
"youtubeUploadQueuedForRetry": "YouTube upload for job {job_id} queued for retry",
"youtubeQueueProcessingStarted": "YouTube queue processing started in background"
},
"rateLimits": {
"configNotFound": "Rate limit config not found: {config_id}",
"configUpdateError": "Error updating rate limit config: {error}"
},
"errors": {
"insufficientCredits": "Insufficient credits for this operation",
"insufficientCreditsBuyUrl": "/#pricing"
},
"emails": {
"magicLink": {
"subject": "Sign in to {brand_name}",
"greeting": "Hi there,",
"signInPrompt": "Click the button below to sign in to {brand_name}:",
"signInButton": "Sign In",
"expiryWarning": "This link expires in 15 minutes and can only be used once.",
"fallbackLink": "If the button doesn't work, copy and paste this link into your browser:",
"ignoreNote": "If you didn't request this email, you can safely ignore it."
},
"welcome": {
"subject": "Welcome to Nomad Karaoke!",
"welcomeGreeting": "Welcome to Nomad Karaoke!",
"turnAnySong": "Turn any song into a professional karaoke video in minutes.",
"freeCreditsLabel": "Free Credits",
"freeCreditsNote": "Each credit creates one professional karaoke video",
"howItWorks": "Here's how it works:",
"step1Title": "1. Search for a song",
"step1Desc": "Enter the artist and title, and we'll find high-quality audio.",
"step2Title": "2. Our system works its magic",
"step2Desc": "We separate vocals, transcribe lyrics, and sync everything perfectly.",
"step3Title": "3. Review & customize",
"step3Desc": "Fine-tune the lyrics if needed, choose your instrumental.",
"step4Title": "4. Get your video",
"step4Desc": "Download your 4K karaoke video or upload directly to YouTube.",
"feedbackBonus": "Complete 2 videos and earn 2 more free credits by sharing your feedback!",
"getStartedButton": "Get Started"
},
"creditsAdded": {
"subject": "{credits} credits added to your Nomad Karaoke account",
"greatNews": "Great news!",
"creditsAddedMessage": "{credits} credits have been added to your account.",
"yourBalance": "Your balance:",
"credits": "credits",
"eachCreditLets": "Each credit lets you create one professional karaoke video with:",
"featureVocalSeparation": "AI-powered vocal/instrumental separation",
"featureLyrics": "Synchronized lyrics with word-level timing",
"feature4k": "4K video output",
"featureYoutube": "YouTube upload",
"createButton": "Create Karaoke Now"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (Your karaoke video is ready!)",
"subject": "{artist} - {title} (Your karaoke video is ready!)",
"subjectFallback": "Your karaoke video is ready!"
},
"youtubeUpload": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (YouTube upload ready!)",
"subject": "{artist} - {title} (YouTube upload ready!)",
"subjectFallback": "Your YouTube upload is ready!"
},
"actionReminder": {
"lyricsSubject": "Action needed: Review lyrics for {artist} - {title}",
"lyricsSubjectFallback": "Action needed: Review lyrics",
"instrumentalSubject": "Action needed: Select instrumental for {artist} - {title}",
"instrumentalSubjectFallback": "Action needed: Select instrumental",
"audioEditSubject": "Action needed for {artist} - {title}",
"audioEditSubjectFallback": "Action needed",
"alertHeading": "Your karaoke video needs input from you!"
},
"reviewReminder": {
"subject": "Reminder: Your karaoke video is waiting for review — {artist} - {title}",
"subjectFallback": "Reminder: Your karaoke video is waiting for review",
"alertHeading": "Your karaoke video is waiting for you!",
"reminderIntro": "Just a friendly reminder that your karaoke video{song_name} is ready for review.",
"reviewButton": "Review Your Video",
"reviewInstructions": "During the review, you can check the lyrics are correct and choose your preferred instrumental track. It usually only takes a few minutes!",
"helpOffer": "If you're having any trouble with the review process, just reply to this email and I'll be happy to help you out.",
"expiryWarning": "Please note: if the review isn't completed within the next 24 hours, the job will automatically expire and your credit will be refunded."
},
"reviewExpired": {
"subject": "Your karaoke video has expired — {artist} - {title}",
"subjectFallback": "Your karaoke video has expired",
"cancelNotice": "Your karaoke video{song_name} has been automatically cancelled because the review wasn't completed within 48 hours.",
"refundNotice": "Don't worry — your credit has been refunded! Your current balance is {credits_balance} {credits_word}.",
"creditSingular": "credit",
"creditPlural": "credits",
"createNewPrompt": "You can create a new karaoke video anytime using your credits:",
"createButton": "Create New Video",
"helpOffer": "If you had any trouble with the review process or need help, just reply to this email — I'd love to help!"
},
"creditDenied": {
"subject": "About your Nomad Karaoke free credits",
"greeting": "Hi there,",
"thankYou": "Thanks for signing up for Nomad Karaoke!",
"deniedMessage": "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.",
"mistakeNote": "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.",
"buyPrompt": "If you'd like to get started right away, you can also purchase credits:",
"buyButton": "Buy Credits",
"costNote": "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!",
"welcomeCredits": "welcome credits",
"feedbackCredits": "feedback bonus credits"
},
"madeForYouConfirmation": {
"subject": "Order Confirmed: {artist} - {title} | Nomad Karaoke",
"thankYou": "Thank You for Your Order!",
"orderDetails": "Order Details",
"orderId": "Order ID:",
"artist": "Artist:",
"title": "Title:",
"yourNotes": "Your Notes:",
"deliveryTime": "Our team will create your custom karaoke video within {hours} hours.",
"deliveryNotice": "You'll receive an email with download links as soon as your video is ready.",
"noAction": "No action needed — sit back and we'll take care of everything!"
},
"shared": {
"footerHelp": "If anything isn't perfect, just reply to this email and I'll fix it!"
},
"templates": {
"jobCompletion": {
"greeting": "Hi {name},",
"thanks": "Thanks for your order!",
"youtubeLink": "Here's the link for the karaoke video published to YouTube:",
"dropboxIntro": "Here's the dropbox folder with all the finished files and source files, including:",
"fileList": "- \"(Final Karaoke Lossless).mkv\": combined karaoke video in 4k H264 with lossless FLAC audio\n- \"(Final Karaoke).mp4\": combined karaoke video with title/end screen in 4k H264/AAC\n- \"(Final Karaoke 720p).mp4\": combined karaoke video in 720p H264/AAC (smaller file for older systems)\n- \"(With Vocals).mp4\": sing along video in 4k H264/AAC with original vocals\n- \"(Karaoke).mov\": karaoke video output from MidiCo (no title/end screen)\n- \"(Title).mov\"/\"(End).mov\": title card and end screen videos\n- \"(Final Karaoke CDG).zip\": CDG+MP3 format for older/commercial karaoke systems\n- \"(Final Karaoke TXT).zip\": TXT+MP3 format for Power Karaoke\n- stems/*.flac: various separated instrumental and vocal audio stems in lossless format\n- lyrics/*.txt song lyrics from various sources in plain text format",
"fixOffer": "Let me know if anything isn't perfect and I'll happily tweak / fix, or if you need it in any other format I can probably convert it for you!",
"feedbackRequest": "If you have a moment, I'd really appreciate your feedback (takes 2 minutes):",
"signOff": "Thanks again and have a great day!\n-Andrew",
"youtubeQueued": "Your YouTube upload is queued and will be processed automatically. You'll receive a follow-up email with the link shortly."
},
"actionLyrics": {
"greeting": "Hi {name},",
"ready": "Your karaoke video for \"{artist} - {title}\" is ready for review!",
"instructions": "Our system has transcribed and synchronized the lyrics, but they may need some corrections. You'll also be able to select your preferred instrumental track (with or without backing vocals).",
"reviewPrompt": "Please review your lyrics and select an instrumental:",
"duration": "This usually takes just a few minutes.",
"signOff": "Thanks!\n-Andrew"
},
"actionInstrumental": {
"greeting": "Hi {name},",
"almostDone": "Your karaoke video for \"{artist} - {title}\" is almost done!",
"instructions": "We've separated the audio into different versions. Please select which instrumental track you'd like to use for the final video.",
"selectPrompt": "Select your instrumental here:",
"signOff": "Thanks!\n-Andrew"
},
"youtubeComplete": {
"greeting": "Hi {name},",
"greatNews": "Great news! Your karaoke video for \"{artist} - {title}\" has been uploaded to YouTube:",
"delayNote": "This upload was briefly delayed while our systems processed other uploads, but everything is all set now.",
"signOff": "Thanks!\n-Andrew"
}
}
}
}
+338
View File
@@ -0,0 +1,338 @@
{
"auth": {
"unknownService": "Servicio desconocido: {service}",
"invalidCredentials": "Los siguientes servicios necesitan reautorización: {services}",
"validCredentials": "Todas las credenciales solicitadas son válidas",
"youtubeAuthInstructions": "Visita {verification_url} e ingresa el código: {user_code}",
"youtubeAuthStartFailed": "Error al iniciar la autenticación de dispositivo de YouTube: {error}",
"gdriveLinkInstructions": "Visita {verification_url} e ingresa el código: {user_code}",
"gdriveAuthStartFailed": "Error al iniciar la autenticación de dispositivo de Google Drive: {error}",
"discordAlertNotConfigured": "El webhook de alerta de Discord no está configurado"
},
"jobs": {
"created": "Trabajo creado con éxito. Procesamiento iniciado.",
"authError": "Error de autenticación: no hay identidad de usuario disponible",
"noDefaultTheme": "No hay un tema predeterminado configurado. Por favor, contacta a soporte o especifica un theme_id.",
"notFound": "Trabajo no encontrado",
"noPermissionAccess": "No tienes permiso para acceder a este trabajo",
"noPermissionEdit": "No tienes permiso para editar este trabajo",
"noPermissionDelete": "No tienes permiso para eliminar este trabajo",
"noPermissionModify": "No tienes permiso para modificar este trabajo",
"notCompleted": "Solo los trabajos completados pueden ser editados. Estado actual: {status}",
"alreadyBeingEdited": "Este trabajo ya está siendo editado (los resultados ya fueron eliminados)",
"cleanupFailed": "La limpieza falló para {services}. Trabajo no modificado. Por favor, inténtalo de nuevo o contacta a soporte.",
"reopened": "Pista reabierta para edición. Los resultados anteriores han sido eliminados.",
"invalidDatetimeFormat": "Formato de {field} inválido: {value}",
"listError": "Error al listar trabajos: {error}",
"deleteError": "Error al eliminar el trabajo {job_id}: {error}",
"deletionPreview": "Agrega &confirm=true para ejecutar la eliminación",
"deletionRequiresFilters": "Se requiere al menos un filtro (environment, client_id, status, created_before)",
"bulkDeleteError": "Error al eliminar trabajos en masa: {error}",
"reviewNotReady": "El trabajo no está listo para revisión (estado actual: {status})",
"correctionsUnavailable": "Los datos de correcciones no están disponibles",
"audioUnavailable": "El audio no está disponible para revisión",
"reviewCannotStart": "No se puede iniciar la revisión",
"jobNotInReviewState": "El trabajo no está en estado de revisión (estado actual: {status})",
"correctionsProcessing": "Correcciones guardadas. Llama a /complete-review cuando termines.",
"editLogSaveFailed": "Error al guardar el registro de edición para el trabajo {job_id}: {error}",
"stemsMissing": "Al trabajo le faltan pistas de audio requeridas (instrumental_clean y/o backing_vocals)",
"customInstrumentalFailed": "Error al crear el instrumental personalizado para el trabajo {job_id}: {error}",
"audioProcessingFailed": "Error al procesar el archivo de audio: {error}",
"durationMismatch": "Discrepancia de duración: el archivo subido dura {upload_duration}s pero el audio original dura {original_duration}s. El instrumental debe durar exactamente {original_duration}s (±0.5s).",
"reviewNotInState": "El trabajo no está en estado de revisión (estado actual: {status})",
"noLyricsDetected": "No se puede completar la revisión: no se detectaron letras en el audio. Esto puede suceder cuando el audio de entrada no tiene voces (por ejemplo, una pista de karaoke o instrumental). Puedes volver y pegar las letras manualmente usando 'Reemplazar todo', o cancelar este trabajo e intentarlo de nuevo con un archivo de audio que contenga voces.",
"reviewCompleteStartRendering": "Revisión completa. Renderizado de video iniciado.",
"reviewCompleteError": "Error al completar la revisión para el trabajo {job_id}: {error}",
"instrumentalSelectionRequired": "Se requiere instrumental_selection. Debe ser 'clean' o 'with_backing'.",
"invalidInstrumentalSelection": "instrumental_selection inválido. Debe ser uno de: {valid_selections}",
"instrumentalSelected": "Instrumental seleccionado. Generación de video iniciada.",
"instrumentalSelectionError": "Error al seleccionar el instrumental para el trabajo {job_id}: {error}",
"downloadUrlsError": "Error al obtener las URLs de descarga: {error}"
},
"review": {
"jobNotFound": "Trabajo no encontrado",
"reviewNotReady": "El trabajo no está listo para revisión (estado actual: {status})",
"correctionsNotFound": "Datos de correcciones no encontrados. El procesamiento de letras puede no estar completo.",
"correctionsLoadFailed": "Error al cargar las correcciones: {error}",
"audioNotFound": "Archivo de audio no encontrado",
"audioServeError": "Error al servir el audio: {error}",
"instrumentalSelectionRequired": "Se requiere instrumental_selection. Debe ser 'clean' o 'with_backing'.",
"invalidInstrumentalSelection": "instrumental_selection inválido. Debe ser uno de: {valid_selections}",
"reviewCompletedError": "Error al completar la revisión: {error}",
"handlersUpdateNotImplemented": "Las actualizaciones de manejadores aún no están implementadas",
"lyricsAddError": "Error al agregar letras: {error}",
"lyricsAddInvalidRequest": "Solicitud de agregar letras inválida: {error}",
"lyricsSearchError": "Error al buscar letras: {error}",
"lyricsSearchInvalidRequest": "Solicitud de búsqueda de letras inválida: {error}",
"lyricsSearchNoResults": "No se encontraron letras coincidentes de ningún proveedor",
"previewVideoGenerationError": "Error al generar el video de vista previa: {error}",
"previewVideoNotFound": "Video de vista previa no encontrado",
"previewVideoStreamError": "Error al transmitir el video de vista previa: {error}",
"annotationSaveError": "Error al guardar las anotaciones: {error}",
"waveformGenerationError": "Error al generar los datos de la forma de onda: {error}",
"waveformNoAudio": "No hay audio disponible para la forma de onda",
"sessionSaveError": "Se requieren datos de corrección"
},
"audioSearch": {
"notEnabled": "La búsqueda de audio no está habilitada para este inquilino",
"disabled": "La búsqueda de audio no está disponible",
"downloadError": "La descarga falló para el trabajo {job_id}: {error}",
"jobNotFound": "Trabajo {job_id} no encontrado",
"noSearchResults": "No hay resultados de búsqueda disponibles",
"invalidSelectionIndex": "Índice de selección inválido {selection_index}. Rango válido: 0-{max}",
"selectionError": "Error durante la selección de audio para el trabajo {job_id}: {error}",
"youtubeDownloadError": "La descarga de YouTube falló: {error}",
"torrentDownloadError": "No se puede descargar de {source} sin el servicio remoto flacfetch. Configura FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "No hay source_id o remote_search_id disponible para la descarga de {source}",
"remoteDownloadCompleteNoPath": "Descarga remota completada pero no se devolvió la ruta del archivo",
"spotifyDownloadError": "No se puede descargar de Spotify sin el servicio remoto flacfetch. Configura FLACFETCH_API_URL.",
"genericDownloadError": "Tipo de fuente desconocido: {source}, intentando descarga genérica",
"jobNotFoundDuringDownload": "Trabajo {job_id} no encontrado durante la descarga en segundo plano",
"selectAudioError": "Error al seleccionar el audio para el trabajo {job_id}: {error}",
"searchAudioError": "Error al buscar audio: {error}",
"searchCreatedSuccessfully": "Trabajo creado. Buscando audio...",
"autoDownloadStarted": "Mejor resultado seleccionado automáticamente. Iniciando descarga..."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
"magicLinkSent": "Si este correo está registrado, recibirás un enlace de inicio de sesión en breve.",
"emailServiceNotConfigured": "El servicio de correo no está disponible. Por favor, contacta a soporte.",
"emailDomainNotAllowed": "Dominio de correo no permitido para este inquilino",
"invalidToken": "Token inválido",
"verifyError": "La verificación falló: {message}",
"magicLinkSuccess": "Has iniciado sesión con éxito",
"logoutSuccess": "Has cerrado sesión con éxito",
"userNotFound": "Usuario no encontrado",
"creditPackagesError": "Error al cargar los paquetes de créditos: {error}",
"stripeSendError": "Error al enviar el enlace de pago de Stripe: {error}",
"stripeWebhookProcessingError": "Error al procesar el webhook de Stripe: {error}",
"feedbackSaveError": "Error al guardar los comentarios: {error}",
"feedbackNotEligible": "El usuario no es elegible para dar comentarios"
},
"fileUpload": {
"invalidTheme": "Tema no encontrado: {theme_id}. Usa GET /api/themes para listar los temas disponibles.",
"uploadSuccess": "Archivo subido con éxito. Procesamiento iniciado.",
"uploadError": "Error al subir el archivo: {error}",
"urlDownloadError": "Error al descargar desde la URL: {error}",
"invalidContentType": "Tipo de contenido inválido: {content_type}",
"fileSizeError": "El archivo es demasiado grande: {size}. Máximo: {max_size}",
"invalidFileType": "Tipo de archivo inválido: {file_type}",
"multipleAudioFilesNotAllowed": "Solo se puede subir un archivo de audio",
"noAudioFileProvided": "No se proporcionó ningún archivo de audio",
"urlCreationSuccess": "Trabajo creado. URLs de subida generadas.",
"urlCreationError": "Error al crear el trabajo con URLs de subida: {error}",
"uploadsCompleteSuccess": "Subidas completadas. Procesamiento iniciado.",
"uploadsCompleteError": "Error al completar las subidas: {error}",
"noUploadedFiles": "No se especificaron archivos subidos",
"styleUploadUrlsSuccess": "URLs de subida de estilo generadas.",
"styleUploadsCompleteSuccess": "Archivos de estilo actualizados. Procesamiento reiniciado.",
"styleUploadsCompleteError": "Error al completar las subidas de estilo: {error}"
},
"catalog": {
"rateLimitExceeded": "Límite de solicitudes excedido. Máximo {max_requests} solicitudes de catálogo por minuto.",
"catalogSearchError": "Error al buscar en el catálogo: {error}",
"communityCheckError": "Error al comprobar las versiones de la comunidad: {error}"
},
"themes": {
"themesLoadError": "Error al cargar los temas",
"themeNotFound": "Tema no encontrado: {theme_id}",
"themeLoadError": "Error al cargar el tema",
"previewNotAvailable": "No hay vista previa disponible para el tema: {theme_id}",
"previewLoadError": "Error al cargar la vista previa del tema",
"youtubeDescriptionNotFound": "Tema no encontrado: {theme_id}",
"youtubeDescriptionLoadError": "Error al cargar la descripción de YouTube"
},
"tenant": {
"assetNotFound": "Recurso no encontrado"
},
"push": {
"disabled": "Las notificaciones push no están habilitadas",
"userEmailNotAvailable": "El correo del usuario no está disponible",
"missingEncryptionKeys": "Faltan claves requeridas (p256dh, auth)",
"subscriptionSaveFailed": "Error al guardar la suscripción",
"subscriptionRegistered": "Suscripción push registrada con éxito",
"subscriptionNotFound": "Suscripción eliminada (o no se encontró)",
"subscriptionRemoved": "Suscripción push eliminada con éxito",
"testNotificationSent": "Notificación de prueba enviada a {sent_count} dispositivo(s)"
},
"pushNotifications": {
"reviewLyricsTitle": "Revisión de letras",
"reviewLyricsBody": "\"{title}\" de {artist} necesita revisión de letras",
"selectInstrumentalTitle": "Seleccionar instrumental",
"selectInstrumentalBody": "\"{title}\" de {artist} necesita selección de instrumental",
"videoReadyTitle": "¡Video listo!",
"videoReadyBody": "Tu video de karaoke para \"{title}\" de {artist} está listo para descargar"
},
"admin": {
"invalidDomainFormat": "Formato de dominio inválido",
"domainAddedToBl": "Dominio '{domain}' agregado a la lista de bloqueo de dominios desechables",
"domainNotFoundInBl": "Dominio no encontrado en la lista de bloqueo",
"domainRemovedFromBl": "Dominio '{domain}' eliminado de la lista de bloqueo de dominios desechables",
"domainAddedToAllowlist": "Dominio '{domain}' agregado a la lista de permitidos",
"domainNotFoundInAllowlist": "Dominio no encontrado en la lista de permitidos",
"domainRemovedFromAllowlist": "Dominio '{domain}' eliminado de la lista de permitidos",
"syncComplete": "Sincronizados {external_count} dominios externos ({added} agregados, {removed} eliminados)",
"invalidEmailFormat": "Formato de correo inválido",
"emailAddedToBl": "Correo '{email}' agregado a la lista de correos bloqueados",
"emailNotFoundInBl": "Correo no encontrado en la lista de bloqueo",
"emailRemovedFromBl": "Correo '{email}' eliminado de la lista de correos bloqueados",
"invalidIPAddress": "Dirección IP inválida",
"ipAddedToBl": "IP '{ip_address}' agregada a la lista de IPs bloqueadas",
"ipNotFoundInBl": "IP no encontrada en la lista de bloqueo",
"ipRemovedFromBl": "IP '{ip_address}' eliminada de la lista de IPs bloqueadas",
"youtubeUploadNotFound": "Subida no encontrada o no en estado de reintento para el trabajo {job_id}",
"youtubeUploadQueuedForRetry": "Subida a YouTube para el trabajo {job_id} en cola para reintento",
"youtubeQueueProcessingStarted": "Procesamiento de la cola de YouTube iniciado en segundo plano"
},
"rateLimits": {
"configNotFound": "Configuración de límite de solicitudes no encontrada: {config_id}",
"configUpdateError": "Error al actualizar la configuración de límite de solicitudes: {error}"
},
"errors": {
"insufficientCredits": "Créditos insuficientes para esta operación",
"insufficientCreditsBuyUrl": "/#pricing"
},
"emails": {
"magicLink": {
"subject": "Inicia sesión en {brand_name}",
"greeting": "Hola,",
"signInPrompt": "Haz clic en el botón de abajo para iniciar sesión en {brand_name}:",
"signInButton": "Iniciar sesión",
"expiryWarning": "Este enlace expira en 15 minutos y solo se puede usar una vez.",
"fallbackLink": "Si el botón no funciona, copia y pega este enlace en tu navegador:",
"ignoreNote": "Si no solicitaste este correo, puedes ignorarlo de forma segura."
},
"welcome": {
"subject": "¡Bienvenido a Nomad Karaoke!",
"welcomeGreeting": "¡Bienvenido a Nomad Karaoke!",
"turnAnySong": "Convierte cualquier canción en un video de karaoke profesional en minutos.",
"freeCreditsLabel": "Créditos gratis",
"freeCreditsNote": "Cada crédito crea un video de karaoke profesional",
"howItWorks": "Así es como funciona:",
"step1Title": "1. Busca una canción",
"step1Desc": "Ingresa el artista y el título, y encontraremos audio de alta calidad.",
"step2Title": "2. Nuestro sistema hace su magia",
"step2Desc": "Separamos las voces, transcribimos las letras y sincronizamos todo perfectamente.",
"step3Title": "3. Revisa y personaliza",
"step3Desc": "Ajusta las letras si es necesario, elige tu instrumental.",
"step4Title": "4. Obtén tu video",
"step4Desc": "Descarga tu video de karaoke en 4K o súbelo directamente a YouTube.",
"feedbackBonus": "¡Completa 2 videos y gana 2 créditos gratis más compartiendo tus comentarios!",
"getStartedButton": "Comenzar"
},
"creditsAdded": {
"subject": "{credits} créditos agregados a tu cuenta de Nomad Karaoke",
"greatNews": "¡Excelentes noticias!",
"creditsAddedMessage": "Se han agregado {credits} créditos a tu cuenta.",
"yourBalance": "Tu saldo:",
"credits": "créditos",
"eachCreditLets": "Cada crédito te permite crear un video de karaoke profesional con:",
"featureVocalSeparation": "Separación vocal/instrumental impulsada por IA",
"featureLyrics": "Letras sincronizadas con sincronización a nivel de palabra",
"feature4k": "Salida de video en 4K",
"featureYoutube": "Subida a YouTube",
"createButton": "Crear karaoke ahora"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (¡Tu video de karaoke está listo!)",
"subject": "{artist} - {title} (¡Tu video de karaoke está listo!)",
"subjectFallback": "¡Tu video de karaoke está listo!"
},
"youtubeUpload": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (¡Subida a YouTube lista!)",
"subject": "{artist} - {title} (¡Subida a YouTube lista!)",
"subjectFallback": "¡Tu subida a YouTube está lista!"
},
"actionReminder": {
"lyricsSubject": "Acción necesaria: Revisión de letras para {artist} - {title}",
"lyricsSubjectFallback": "Acción necesaria: Revisión de letras",
"instrumentalSubject": "Acción necesaria: Seleccionar instrumental para {artist} - {title}",
"instrumentalSubjectFallback": "Acción necesaria: Seleccionar instrumental",
"audioEditSubject": "Acción necesaria para {artist} - {title}",
"audioEditSubjectFallback": "Acción necesaria",
"alertHeading": "¡Tu video de karaoke necesita tu atención!"
},
"reviewReminder": {
"subject": "Recordatorio: Tu video de karaoke está esperando revisión — {artist} - {title}",
"subjectFallback": "Recordatorio: Tu video de karaoke está esperando revisión",
"alertHeading": "¡Tu video de karaoke te está esperando!",
"reminderIntro": "Solo un recordatorio amistoso de que tu video de karaoke{song_name} está listo para revisión.",
"reviewButton": "Revisar tu video",
"reviewInstructions": "Durante la revisión, puedes comprobar que las letras son correctas y elegir tu pista instrumental preferida. ¡Normalmente solo toma unos minutos!",
"helpOffer": "Si tienes algún problema con el proceso de revisión, simplemente responde a este correo y estaré encantado de ayudarte.",
"expiryWarning": "Ten en cuenta: si la revisión no se completa en las próximas 24 horas, el trabajo expirará automáticamente y se te reembolsará tu crédito."
},
"reviewExpired": {
"subject": "Tu video de karaoke ha expirado — {artist} - {title}",
"subjectFallback": "Tu video de karaoke ha expirado",
"cancelNotice": "Tu video de karaoke{song_name} ha sido cancelado automáticamente porque la revisión no se completó en 48 horas.",
"refundNotice": "No te preocupes — ¡tu crédito ha sido reembolsado! Tu saldo actual es de {credits_balance} {credits_word}.",
"creditSingular": "crédito",
"creditPlural": "créditos",
"createNewPrompt": "Puedes crear un nuevo video de karaoke en cualquier momento usando tus créditos:",
"createButton": "Crear nuevo video",
"helpOffer": "Si tuviste algún problema con el proceso de revisión o necesitas ayuda, simplemente responde a este correo — ¡me encantaría ayudarte!"
},
"creditDenied": {
"subject": "Sobre tus créditos gratis de Nomad Karaoke",
"greeting": "Hola,",
"thankYou": "¡Gracias por registrarte en Nomad Karaoke!",
"deniedMessage": "Lamentablemente, no pudimos otorgar tus {credit_type} gratis esta vez. Nuestro sistema detectó patrones que sugieren que esta puede no ser tu primera cuenta con nosotros, y cada trabajo de generación de karaoke nos cuesta dinero real en computación en la nube y tarifas de API.",
"mistakeNote": "¡Entendemos totalmente si esto es un error! Si eres un usuario nuevo genuino, simplemente responde a este correo y avísale a Andrew (el fundador). Él construyó este servicio y estará encantado de otorgarte algunos créditos gratis para que lo pruebes — solo pide que a cambio proporciones comentarios honestos sobre la experiencia.",
"buyPrompt": "Si deseas comenzar de inmediato, también puedes comprar créditos:",
"buyButton": "Comprar créditos",
"costNote": "Mantenemos los costos bajos para poder ofrecer el servicio de manera asequible, lo que significa que debemos tener cuidado con el abuso de créditos gratis. ¡Gracias por entender!",
"welcomeCredits": "créditos de bienvenida",
"feedbackCredits": "créditos de bonificación por comentarios"
},
"madeForYouConfirmation": {
"subject": "Pedido confirmado: {artist} - {title} | Nomad Karaoke",
"thankYou": "¡Gracias por tu pedido!",
"orderDetails": "Detalles del pedido",
"orderId": "ID del pedido:",
"artist": "Artista:",
"title": "Título:",
"yourNotes": "Tus notas:",
"deliveryTime": "Nuestro equipo creará tu video de karaoke personalizado en {hours} horas.",
"deliveryNotice": "Recibirás un correo con los enlaces de descarga tan pronto como tu video esté listo.",
"noAction": "No es necesario hacer nada — ¡siéntate y nosotros nos encargaremos de todo!"
},
"shared": {
"footerHelp": "Si algo no es perfecto, simplemente responde a este correo y lo arreglaré."
},
"templates": {
"jobCompletion": {
"greeting": "Hola {name},",
"thanks": "¡Gracias por tu pedido!",
"youtubeLink": "Aquí tienes el enlace del video de karaoke publicado en YouTube:",
"dropboxIntro": "Aquí tienes la carpeta de Dropbox con todos los archivos terminados y archivos fuente, incluyendo:",
"fileList": "- \"(Final Karaoke Lossless).mkv\": video de karaoke combinado en 4K H264 con audio FLAC sin pérdida\n- \"(Final Karaoke).mp4\": video de karaoke combinado con pantalla de título/final en 4K H264/AAC\n- \"(Final Karaoke 720p).mp4\": video de karaoke combinado en 720p H264/AAC (archivo más pequeño para sistemas antiguos)\n- \"(With Vocals).mp4\": video para cantar junto en 4K H264/AAC con voces originales\n- \"(Karaoke).mov\": salida de video de karaoke de MidiCo (sin pantalla de título/final)\n- \"(Title).mov\"/\"(End).mov\": videos de tarjeta de título y pantalla final\n- \"(Final Karaoke CDG).zip\": formato CDG+MP3 para sistemas de karaoke antiguos/comerciales\n- \"(Final Karaoke TXT).zip\": formato TXT+MP3 para Power Karaoke\n- stems/*.flac: varias pistas de audio instrumentales y vocales separadas en formato sin pérdida\n- lyrics/*.txt letras de canciones de varias fuentes en formato de texto plano",
"fixOffer": "Avísame si algo no es perfecto y con gusto lo ajustaré / arreglaré, o si lo necesitas en cualquier otro formato, ¡probablemente pueda convertirlo para ti!",
"feedbackRequest": "Si tienes un momento, realmente apreciaría tus comentarios (toma 2 minutos):",
"signOff": "¡Gracias de nuevo y que tengas un gran día!\n-Andrew",
"youtubeQueued": "Tu subida a YouTube está en cola y se procesará automáticamente. Recibirás un correo de seguimiento con el enlace en breve."
},
"actionLyrics": {
"greeting": "Hola {name},",
"ready": "¡Tu video de karaoke para \"{artist} - {title}\" está listo para revisión!",
"instructions": "Nuestro sistema ha transcrito y sincronizado las letras, pero pueden necesitar algunas correcciones. También podrás seleccionar tu pista instrumental preferida (con o sin coros).",
"reviewPrompt": "Por favor revisa tus letras y selecciona un instrumental:",
"duration": "Esto normalmente toma solo unos minutos.",
"signOff": "¡Gracias!\n-Andrew"
},
"actionInstrumental": {
"greeting": "Hola {name},",
"almostDone": "¡Tu video de karaoke para \"{artist} - {title}\" está casi listo!",
"instructions": "Hemos separado el audio en diferentes versiones. Por favor selecciona qué pista instrumental te gustaría usar para el video final.",
"selectPrompt": "Selecciona tu instrumental aquí:",
"signOff": "¡Gracias!\n-Andrew"
},
"youtubeComplete": {
"greeting": "Hola {name},",
"greatNews": "¡Excelentes noticias! Tu video de karaoke para \"{artist} - {title}\" ha sido subido a YouTube:",
"delayNote": "Esta subida se retrasó brevemente mientras nuestros sistemas procesaban otras subidas, pero ya está todo listo.",
"signOff": "¡Gracias!\n-Andrew"
}
}
}
}
+338
View File
@@ -0,0 +1,338 @@
{
"auth": {
"unknownService": "Tuntematon palvelu: {service}",
"invalidCredentials": "Seuraavat palvelut vaativat uudelleenvaltuutuksen: {services}",
"validCredentials": "Kaikki pyydetyt valtuudet ovat voimassa",
"youtubeAuthInstructions": "Käy osoitteessa {verification_url} ja syötä koodi: {user_code}",
"youtubeAuthStartFailed": "YouTube-laitteen valtuutuksen aloittaminen epäonnistui: {error}",
"gdriveLinkInstructions": "Käy osoitteessa {verification_url} ja syötä koodi: {user_code}",
"gdriveAuthStartFailed": "Google Drive -laitteen valtuutuksen aloittaminen epäonnistui: {error}",
"discordAlertNotConfigured": "Discord-hälytyksen webhookia ei ole määritetty"
},
"jobs": {
"created": "Työ luotu onnistuneesti. Käsittely aloitettu.",
"authError": "Todennusvirhe: käyttäjän identiteettiä ei ole saatavilla",
"noDefaultTheme": "Oletusteemaa ei ole määritetty. Ota yhteyttä tukeen tai määritä theme_id.",
"notFound": "Työtä ei löytynyt",
"noPermissionAccess": "Sinulla ei ole oikeutta tarkastella tätä työtä",
"noPermissionEdit": "Sinulla ei ole oikeutta muokata tätä työtä",
"noPermissionDelete": "Sinulla ei ole oikeutta poistaa tätä työtä",
"noPermissionModify": "Sinulla ei ole oikeutta muuttaa tätä työtä",
"notCompleted": "Vain valmistuneita töitä voi muokata. Nykyinen tila: {status}",
"alreadyBeingEdited": "Tätä työtä muokataan jo (tulosteet on jo poistettu)",
"cleanupFailed": "Puhdistus epäonnistui palveluille {services}. Työtä ei muokattu. Yritä uudelleen tai ota yhteyttä tukeen.",
"reopened": "Kappale avattu uudelleen muokattavaksi. Aiemmat tulosteet on poistettu.",
"invalidDatetimeFormat": "Virheellinen {field} -muoto: {value}",
"listError": "Virhe listattaessa töitä: {error}",
"deleteError": "Virhe poistettaessa työtä {job_id}: {error}",
"deletionPreview": "Lisää &confirm=true suorittaaksesi poiston",
"deletionRequiresFilters": "Vähintään yksi suodatin (environment, client_id, status, created_before) vaaditaan",
"bulkDeleteError": "Virhe poistettaessa töitä massana: {error}",
"reviewNotReady": "Työ ei ole valmis tarkistettavaksi (nykyinen tila: {status})",
"correctionsUnavailable": "Korjaustietoja ei ole saatavilla",
"audioUnavailable": "Ääntä ei ole saatavilla tarkistusta varten",
"reviewCannotStart": "Tarkistusta ei voida aloittaa",
"jobNotInReviewState": "Työ ei ole tarkistustilassa (nykyinen tila: {status})",
"correctionsProcessing": "Korjaukset tallennettu. Kutsu /complete-review kun olet valmis.",
"editLogSaveFailed": "Virhe tallennettaessa muokkauslokia työlle {job_id}: {error}",
"stemsMissing": "Työstä puuttuu vaadittuja raitoja (instrumental_clean ja/tai backing_vocals)",
"customInstrumentalFailed": "Virhe luotaessa mukautettua instrumentaalia työlle {job_id}: {error}",
"audioProcessingFailed": "Äänitiedoston käsittely epäonnistui: {error}",
"durationMismatch": "Keston epäsuhta: ladattu tiedosto on {upload_duration}s mutta alkuperäinen ääni on {original_duration}s. Instrumentaalin on oltava tasan {original_duration}s (±0.5s).",
"reviewNotInState": "Työ ei ole tarkistustilassa (nykyinen tila: {status})",
"noLyricsDetected": "Tarkistusta ei voida suorittaa loppuun: äänestä ei tunnistettu sanoituksia. Näin voi käydä, kun syöteäänessä ei ole laulua (esim. karaokeraita tai instrumentaali). Voit palata takaisin ja liittää sanoitukset manuaalisesti käyttämällä 'Replace All', tai peruuttaa tämän työn ja yrittää uudelleen äänitiedostolla, joka sisältää laulua.",
"reviewCompleteStartRendering": "Tarkistus valmis. Videon renderöinti aloitettu.",
"reviewCompleteError": "Virhe viimeisteltäessä tarkistusta työlle {job_id}: {error}",
"instrumentalSelectionRequired": "instrumental_selection on pakollinen. Täytyy olla 'clean' tai 'with_backing'.",
"invalidInstrumentalSelection": "Virheellinen instrumental_selection. Täytyy olla jokin näistä: {valid_selections}",
"instrumentalSelected": "Instrumentaali valittu. Videon luonti aloitettu.",
"instrumentalSelectionError": "Virhe valittaessa instrumentaalia työlle {job_id}: {error}",
"downloadUrlsError": "Virhe haettaessa latausosoitteita: {error}"
},
"review": {
"jobNotFound": "Työtä ei löytynyt",
"reviewNotReady": "Työ ei ole valmis tarkistettavaksi (nykyinen tila: {status})",
"correctionsNotFound": "Korjaustietoja ei löytynyt. Sanoitusten käsittely ei ehkä ole valmis.",
"correctionsLoadFailed": "Virhe ladattaessa korjauksia: {error}",
"audioNotFound": "Äänitiedostoa ei löytynyt",
"audioServeError": "Virhe tarjoiltaessa ääntä: {error}",
"instrumentalSelectionRequired": "instrumental_selection on pakollinen. Täytyy olla 'clean' tai 'with_backing'.",
"invalidInstrumentalSelection": "Virheellinen instrumental_selection. Täytyy olla jokin näistä: {valid_selections}",
"reviewCompletedError": "Virhe viimeisteltäessä tarkistusta: {error}",
"handlersUpdateNotImplemented": "Käsittelijöiden päivitystä ei ole vielä toteutettu",
"lyricsAddError": "Sanoitusten lisääminen epäonnistui: {error}",
"lyricsAddInvalidRequest": "Virheellinen sanoitusten lisäyspyyntö: {error}",
"lyricsSearchError": "Sanoitusten haku epäonnistui: {error}",
"lyricsSearchInvalidRequest": "Virheellinen sanoitusten hakupyyntö: {error}",
"lyricsSearchNoResults": "Vastaavia sanoituksia ei löytynyt miltään tarjoajalta",
"previewVideoGenerationError": "Esikatseluvideon luonti epäonnistui: {error}",
"previewVideoNotFound": "Esikatseluvideota ei löytynyt",
"previewVideoStreamError": "Virhe suoratoistettaessa esikatseluvideota: {error}",
"annotationSaveError": "Virhe tallennettaessa merkintöjä: {error}",
"waveformGenerationError": "Virhe luotaessa aaltomuotodataa: {error}",
"waveformNoAudio": "Ääntä ei ole saatavilla aaltomuotoa varten",
"sessionSaveError": "Korjaustiedot vaaditaan"
},
"audioSearch": {
"notEnabled": "Äänihaku ei ole käytössä tälle asiakkaalle",
"disabled": "Äänihaku ei ole saatavilla",
"downloadError": "Lataus epäonnistui työlle {job_id}: {error}",
"jobNotFound": "Työtä {job_id} ei löytynyt",
"noSearchResults": "Hakutuloksia ei ole saatavilla",
"invalidSelectionIndex": "Virheellinen valintaindeksi {selection_index}. Sallittu väli: 0-{max}",
"selectionError": "Virhe äänen valinnassa työlle {job_id}: {error}",
"youtubeDownloadError": "YouTube-lataus epäonnistui: {error}",
"torrentDownloadError": "Ei voida ladata lähteestä {source} ilman etä-flacfetch-palvelua. Määritä FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Lähdetunnusta (source_id) tai etähakutunnusta (remote_search_id) ei ole saatavilla {source}-lataukseen",
"remoteDownloadCompleteNoPath": "Etälataus valmistui, mutta tiedostopolkua ei palautettu",
"spotifyDownloadError": "Ei voida ladata Spotifysta ilman etä-flacfetch-palvelua. Määritä FLACFETCH_API_URL.",
"genericDownloadError": "Tuntematon lähdetyyppi: {source}, yritetään yleistä latausta",
"jobNotFoundDuringDownload": "Työtä {job_id} ei löytynyt taustalatauksen aikana",
"selectAudioError": "Virhe valittaessa ääntä työlle {job_id}: {error}",
"searchAudioError": "Virhe haettaessa ääntä: {error}",
"searchCreatedSuccessfully": "Työ luotu. Etsitään ääntä...",
"autoDownloadStarted": "Paras tulos valittu automaattisesti. Lataus alkaa..."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
"magicLinkSent": "Jos tämä sähköposti on rekisteröity, saat kirjautumislinkin hetken kuluttua.",
"emailServiceNotConfigured": "Sähköpostipalvelu ei ole saatavilla. Ota yhteyttä tukeen.",
"emailDomainNotAllowed": "Sähköpostin verkkotunnus ei ole sallittu tälle asiakkaalle",
"invalidToken": "Virheellinen tunniste",
"verifyError": "Vahvistus epäonnistui: {message}",
"magicLinkSuccess": "Kirjautuminen onnistui",
"logoutSuccess": "Uloskirjautuminen onnistui",
"userNotFound": "Käyttäjää ei löytynyt",
"creditPackagesError": "Virhe ladattaessa krediittipaketteja: {error}",
"stripeSendError": "Virhe lähetettäessä Stripe-kassalinkkiä: {error}",
"stripeWebhookProcessingError": "Virhe käsiteltäessä Stripe-webhookia: {error}",
"feedbackSaveError": "Virhe tallennettaessa palautetta: {error}",
"feedbackNotEligible": "Käyttäjä ei ole oikeutettu antamaan palautetta"
},
"fileUpload": {
"invalidTheme": "Teemaa ei löytynyt: {theme_id}. Käytä GET /api/themes listataksesi saatavilla olevat teemat.",
"uploadSuccess": "Tiedosto ladattu onnistuneesti. Käsittely aloitettu.",
"uploadError": "Virhe ladattaessa tiedostoa: {error}",
"urlDownloadError": "Virhe ladattaessa URL-osoitteesta: {error}",
"invalidContentType": "Virheellinen sisältötyyppi: {content_type}",
"fileSizeError": "Tiedosto on liian suuri: {size}. Maksimi: {max_size}",
"invalidFileType": "Virheellinen tiedostotyyppi: {file_type}",
"multipleAudioFilesNotAllowed": "Vain yksi äänitiedosto voidaan ladata",
"noAudioFileProvided": "Äänitiedostoa ei annettu",
"urlCreationSuccess": "Työ luotu. Latausosoitteet luotu.",
"urlCreationError": "Virhe luotaessa työtä latausosoitteilla: {error}",
"uploadsCompleteSuccess": "Lataukset valmiit. Käsittely aloitettu.",
"uploadsCompleteError": "Virhe viimeisteltäessä latauksia: {error}",
"noUploadedFiles": "Ladattuja tiedostoja ei määritetty",
"styleUploadUrlsSuccess": "Tyylien latausosoitteet luotu.",
"styleUploadsCompleteSuccess": "Tyylitiedostot päivitetty. Käsittely käynnistetty uudelleen.",
"styleUploadsCompleteError": "Virhe viimeisteltäessä tyylilatauksia: {error}"
},
"catalog": {
"rateLimitExceeded": "Nopeusrajoitus ylitetty. Enintään {max_requests} katalogipyyntöä minuutissa.",
"catalogSearchError": "Virhe haettaessa katalogista: {error}",
"communityCheckError": "Virhe tarkistettaessa yhteisöversioita: {error}"
},
"themes": {
"themesLoadError": "Teemojen lataaminen epäonnistui",
"themeNotFound": "Teemaa ei löytynyt: {theme_id}",
"themeLoadError": "Teeman lataaminen epäonnistui",
"previewNotAvailable": "Esikatselua ei saatavilla teemalle: {theme_id}",
"previewLoadError": "Teeman esikatselun lataaminen epäonnistui",
"youtubeDescriptionNotFound": "Teemaa ei löytynyt: {theme_id}",
"youtubeDescriptionLoadError": "YouTube-kuvauksen lataaminen epäonnistui"
},
"tenant": {
"assetNotFound": "Resurssia ei löytynyt"
},
"push": {
"disabled": "Push-ilmoitukset eivät ole käytössä",
"userEmailNotAvailable": "Käyttäjän sähköpostia ei ole saatavilla",
"missingEncryptionKeys": "Vaadittuja avaimia puuttuu (p256dh, auth)",
"subscriptionSaveFailed": "Tilauksen tallentaminen epäonnistui",
"subscriptionRegistered": "Push-tilaus rekisteröity onnistuneesti",
"subscriptionNotFound": "Tilaus poistettu (tai sitä ei löytynyt)",
"subscriptionRemoved": "Push-tilaus poistettu onnistuneesti",
"testNotificationSent": "Testi-ilmoitus lähetetty {sent_count} laitteeseen"
},
"pushNotifications": {
"reviewLyricsTitle": "Tarkista sanoitukset",
"reviewLyricsBody": "\"{title}\" esittäjältä {artist} vaatii sanoitusten tarkistusta",
"selectInstrumentalTitle": "Valitse instrumentaali",
"selectInstrumentalBody": "\"{title}\" esittäjältä {artist} vaatii instrumentaalin valintaa",
"videoReadyTitle": "Video on valmis!",
"videoReadyBody": "Karaokevideosi kappaleelle \"{title}\" esittäjältä {artist} on valmis ladattavaksi"
},
"admin": {
"invalidDomainFormat": "Virheellinen verkkotunnuksen muoto",
"domainAddedToBl": "Verkkotunnus '{domain}' lisätty kertakäyttöisten verkkotunnusten estolistalle",
"domainNotFoundInBl": "Verkkotunnusta ei löytynyt estolistalta",
"domainRemovedFromBl": "Verkkotunnus '{domain}' poistettu kertakäyttöisten verkkotunnusten estolistalta",
"domainAddedToAllowlist": "Verkkotunnus '{domain}' lisätty sallittujen listalle",
"domainNotFoundInAllowlist": "Verkkotunnusta ei löytynyt sallittujen listalta",
"domainRemovedFromAllowlist": "Verkkotunnus '{domain}' poistettu sallittujen listalta",
"syncComplete": "Synkronoitu {external_count} ulkoista verkkotunnusta ({added} lisätty, {removed} poistettu)",
"invalidEmailFormat": "Virheellinen sähköpostin muoto",
"emailAddedToBl": "Sähköposti '{email}' lisätty estettyjen sähköpostien listalle",
"emailNotFoundInBl": "Sähköpostia ei löytynyt estolistalta",
"emailRemovedFromBl": "Sähköposti '{email}' poistettu estettyjen sähköpostien listalta",
"invalidIPAddress": "Virheellinen IP-osoite",
"ipAddedToBl": "IP '{ip_address}' lisätty estettyjen IP-osoitteiden listalle",
"ipNotFoundInBl": "IP-osoitetta ei löytynyt estolistalta",
"ipRemovedFromBl": "IP '{ip_address}' poistettu estettyjen IP-osoitteiden listalta",
"youtubeUploadNotFound": "Latausta ei löytynyt tai se ei ole uudelleenyritettävässä tilassa työlle {job_id}",
"youtubeUploadQueuedForRetry": "YouTube-lataus työlle {job_id} asetettu jonoon uudelleenyritystä varten",
"youtubeQueueProcessingStarted": "YouTube-jonon käsittely aloitettu taustalla"
},
"rateLimits": {
"configNotFound": "Nopeusrajoituksen asetuksia ei löytynyt: {config_id}",
"configUpdateError": "Virhe päivitettäessä nopeusrajoituksen asetuksia: {error}"
},
"errors": {
"insufficientCredits": "Ei tarpeeksi krediittejä tähän toimintoon",
"insufficientCreditsBuyUrl": "/#pricing"
},
"emails": {
"magicLink": {
"subject": "Kirjaudu sisään palveluun {brand_name}",
"greeting": "Hei,",
"signInPrompt": "Klikkaa alla olevaa painiketta kirjautuaksesi sisään palveluun {brand_name}:",
"signInButton": "Kirjaudu sisään",
"expiryWarning": "Tämä linkki vanhenee 15 minuutin kuluttua ja sitä voi käyttää vain kerran.",
"fallbackLink": "Jos painike ei toimi, kopioi ja liitä tämä linkki selaimeesi:",
"ignoreNote": "Jos et pyytänyt tätä sähköpostia, voit jättää sen huomiotta."
},
"welcome": {
"subject": "Tervetuloa Nomad Karaoke -palveluun!",
"welcomeGreeting": "Tervetuloa Nomad Karaoke -palveluun!",
"turnAnySong": "Muuta mikä tahansa kappale ammattimaiseksi karaokevideoksi minuuteissa.",
"freeCreditsLabel": "Ilmaiset krediitit",
"freeCreditsNote": "Jokainen krediitti luo yhden ammattimaisen karaokevideon",
"howItWorks": "Näin se toimii:",
"step1Title": "1. Etsi kappale",
"step1Desc": "Syötä esittäjä ja kappaleen nimi, niin etsimme korkealaatuisen äänen.",
"step2Title": "2. Järjestelmämme tekee taikojaan",
"step2Desc": "Erottelemme laulun, kirjoitamme sanoitukset puhtaaksi ja synkronoimme kaiken täydellisesti.",
"step3Title": "3. Tarkista ja mukauta",
"step3Desc": "Hienosäädä sanoituksia tarvittaessa ja valitse instrumentaalisi.",
"step4Title": "4. Hae videosi",
"step4Desc": "Lataa 4K-karaokevideosi tai lataa se suoraan YouTube-palveluun.",
"feedbackBonus": "Tee 2 videota ja ansaitse 2 ilmaista krediittiä lisää jakamalla palautteesi!",
"getStartedButton": "Aloita"
},
"creditsAdded": {
"subject": "{credits} krediittiä lisätty Nomad Karaoke -tilillesi",
"greatNews": "Loistavia uutisia!",
"creditsAddedMessage": "{credits} krediittiä on lisätty tilillesi.",
"yourBalance": "Saldosi:",
"credits": "krediittiä",
"eachCreditLets": "Jokaisella krediitillä voit luoda yhden ammattimaisen karaokevideon, jossa on:",
"featureVocalSeparation": "Tekoälypohjainen laulun/instrumentaalin erottelu",
"featureLyrics": "Synkronoidut sanoitukset sanatasoisella ajoituksella",
"feature4k": "4K-videotuloste",
"featureYoutube": "YouTube-lataus",
"createButton": "Luo karaoke nyt"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (Karaokevideosi on valmis!)",
"subject": "{artist} - {title} (Karaokevideosi on valmis!)",
"subjectFallback": "Karaokevideosi on valmis!"
},
"youtubeUpload": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (YouTube-lataus on valmis!)",
"subject": "{artist} - {title} (YouTube-lataus on valmis!)",
"subjectFallback": "YouTube-latauksesi on valmis!"
},
"actionReminder": {
"lyricsSubject": "Toimenpiteitä tarvitaan: Tarkista sanoitukset kappaleelle {artist} - {title}",
"lyricsSubjectFallback": "Toimenpiteitä tarvitaan: Tarkista sanoitukset",
"instrumentalSubject": "Toimenpiteitä tarvitaan: Valitse instrumentaali kappaleelle {artist} - {title}",
"instrumentalSubjectFallback": "Toimenpiteitä tarvitaan: Valitse instrumentaali",
"audioEditSubject": "Toimenpiteitä tarvitaan kappaleelle {artist} - {title}",
"audioEditSubjectFallback": "Toimenpiteitä tarvitaan",
"alertHeading": "Karaokevideosi tarvitsee sinulta syötettä!"
},
"reviewReminder": {
"subject": "Muistutus: Karaokevideosi odottaa tarkistusta — {artist} - {title}",
"subjectFallback": "Muistutus: Karaokevideosi odottaa tarkistusta",
"alertHeading": "Karaokevideosi odottaa sinua!",
"reminderIntro": "Ystävällinen muistutus, että karaokevideosi{song_name} on valmis tarkistettavaksi.",
"reviewButton": "Tarkista videosi",
"reviewInstructions": "Tarkistuksen aikana voit varmistaa, että sanoitukset ovat oikein, ja valita haluamasi instrumentaaliraidan. Tämä vie yleensä vain muutaman minuutin!",
"helpOffer": "Jos sinulla on ongelmia tarkistusprosessin kanssa, vastaa vain tähän sähköpostiin ja autan sinua mielelläni.",
"expiryWarning": "Huomaa: jos tarkistusta ei suoriteta seuraavan 24 tunnin kuluessa, työ vanhenee automaattisesti ja krediittisi palautetaan."
},
"reviewExpired": {
"subject": "Karaokevideosi on vanhentunut — {artist} - {title}",
"subjectFallback": "Karaokevideosi on vanhentunut",
"cancelNotice": "Karaokevideosi{song_name} on peruutettu automaattisesti, koska tarkistusta ei suoritettu 48 tunnin kuluessa.",
"refundNotice": "Älä huoli — krediittisi on palautettu! Nykyinen saldosi on {credits_balance} {credits_word}.",
"creditSingular": "krediitti",
"creditPlural": "krediittiä",
"createNewPrompt": "Voit luoda uuden karaokevideon milloin tahansa käyttämällä krediittejäsi:",
"createButton": "Luo uusi video",
"helpOffer": "Jos sinulla oli ongelmia tarkistusprosessin kanssa tai tarvitset apua, vastaa vain tähän sähköpostiin — autan mielelläni!"
},
"creditDenied": {
"subject": "Tietoa Nomad Karaoke -ilmaiskrediiteistäsi",
"greeting": "Hei,",
"thankYou": "Kiitos, että rekisteröidyit Nomad Karaoke -palveluun!",
"deniedMessage": "Valitettavasti emme voineet myöntää ilmaista {credit_type} tällä kertaa. Järjestelmämme havaitsi kaavoja, jotka viittaavat siihen, että tämä ei ehkä ole ensimmäinen tilisi meillä, ja jokainen karaoken luontityö maksaa meille oikeaa rahaa pilvipalvelu- ja API-kuluina.",
"mistakeNote": "Ymmärrämme täysin, jos tämä on virhe! Jos olet aito uusi käyttäjä, vastaa vain tähän sähköpostiin ja kerro asiasta Andrew'lle (perustajalle). Hän on rakentanut tämän palvelun ja antaa sinulle mielellään muutaman ilmaisen krediitin kokeiltavaksi — hän pyytää vain, että annat vastineeksi rehellistä palautetta kokemuksestasi.",
"buyPrompt": "Jos haluat aloittaa heti, voit myös ostaa krediittejä:",
"buyButton": "Osta krediittejä",
"costNote": "Pidämme kustannukset alhaisina, jotta voimme tarjota palvelua edullisesti, mikä tarkoittaa, että meidän on oltava varovaisia ilmaiskrediittien väärinkäytön suhteen. Kiitos ymmärryksestä!",
"welcomeCredits": "tervetuliaiskrediittiäsi",
"feedbackCredits": "palautekrediittiäsi"
},
"madeForYouConfirmation": {
"subject": "Tilaus vahvistettu: {artist} - {title} | Nomad Karaoke",
"thankYou": "Kiitos tilauksestasi!",
"orderDetails": "Tilauksen tiedot",
"orderId": "Tilausnumero:",
"artist": "Esittäjä:",
"title": "Kappale:",
"yourNotes": "Muistiinpanosi:",
"deliveryTime": "Tiimimme luo mukautetun karaokevideosi {hours} tunnin kuluessa.",
"deliveryNotice": "Saat sähköpostin, jossa on latauslinkit, heti kun videosi on valmis.",
"noAction": "Toimenpiteitä ei tarvita — istu alas ja me hoidamme kaiken!"
},
"shared": {
"footerHelp": "Jos jokin ei ole täydellistä, vastaa vain tähän sähköpostiin ja korjaan sen!"
},
"templates": {
"jobCompletion": {
"greeting": "Hei {name},",
"thanks": "Kiitos tilauksestasi!",
"youtubeLink": "Tässä on linkki YouTube-palveluun julkaistuun karaokevideoon:",
"dropboxIntro": "Tässä on Dropbox-kansio, jossa on kaikki valmiit tiedostot ja lähdetiedostot, mukaan lukien:",
"fileList": "- \"(Final Karaoke Lossless).mkv\": yhdistetty karaokevideo 4K H264 -muodossa häviöttömällä FLAC-äänellä\n- \"(Final Karaoke).mp4\": yhdistetty karaokevideo otsikko-/loppunäytöllä 4K H264/AAC -muodossa\n- \"(Final Karaoke 720p).mp4\": yhdistetty karaokevideo 720p H264/AAC -muodossa (pienempi tiedosto vanhemmille järjestelmille)\n- \"(With Vocals).mp4\": mukana laulettava video 4K H264/AAC -muodossa alkuperäisillä lauluosuuksilla\n- \"(Karaoke).mov\": karaokevideotuloste MidiCosta (ei otsikko-/loppunäyttöä)\n- \"(Title).mov\"/\"(End).mov\": otsikkokortti- ja loppunäyttövideot\n- \"(Final Karaoke CDG).zip\": CDG+MP3-muoto vanhemmille/kaupallisille karaokejärjestelmille\n- \"(Final Karaoke TXT).zip\": TXT+MP3-muoto Power Karaokelle\n- stems/*.flac: erilaisia eroteltuja instrumentaali- ja lauluraitoja häviöttömässä muodossa\n- lyrics/*.txt kappaleen sanoitukset eri lähteistä pelkkänä tekstinä",
"fixOffer": "Kerro minulle, jos jokin ei ole täydellistä, niin hienosäädän / korjaan sen mielelläni, tai jos tarvitset sen jossain muussa muodossa, voin todennäköisesti muuntaa sen sinulle!",
"feedbackRequest": "Jos sinulla on hetki aikaa, arvostaisin todella palautettasi (kestää 2 minuuttia):",
"signOff": "Kiitos vielä kerran ja mukavaa päivää!\n-Andrew",
"youtubeQueued": "YouTube-latauksesi on jonossa ja se käsitellään automaattisesti. Saat pian seurantaviestin, jossa on linkki."
},
"actionLyrics": {
"greeting": "Hei {name},",
"ready": "Karaokevideosi kappaleelle \"{artist} - {title}\" on valmis tarkistettavaksi!",
"instructions": "Järjestelmämme on kirjoittanut puhtaaksi ja synkronoinut sanoitukset, mutta ne saattavat vaatia joitain korjauksia. Pääset myös valitsemaan haluamasi instrumentaaliraidan (taustalaululla tai ilman).",
"reviewPrompt": "Tarkista sanoituksesi ja valitse instrumentaali:",
"duration": "Tämä vie yleensä vain muutaman minuutin.",
"signOff": "Kiitos!\n-Andrew"
},
"actionInstrumental": {
"greeting": "Hei {name},",
"almostDone": "Karaokevideosi kappaleelle \"{artist} - {title}\" on melkein valmis!",
"instructions": "Olemme erotelleet äänen eri versioihin. Valitse, mitä instrumentaaliraitaa haluat käyttää lopullisessa videossa.",
"selectPrompt": "Valitse instrumentaalisi tästä:",
"signOff": "Kiitos!\n-Andrew"
},
"youtubeComplete": {
"greeting": "Hei {name},",
"greatNews": "Loistavia uutisia! Karaokevideosi kappaleelle \"{artist} - {title}\" on ladattu YouTube-palveluun:",
"delayNote": "Tämä lataus viivästyi hetkellisesti, kun järjestelmämme käsittelivät muita latauksia, mutta nyt kaikki on valmista.",
"signOff": "Kiitos!\n-Andrew"
}
}
}
}
+338
View File
@@ -0,0 +1,338 @@
{
"auth": {
"unknownService": "Service inconnu : {service}",
"invalidCredentials": "Les services suivants nécessitent une nouvelle autorisation : {services}",
"validCredentials": "Tous les identifiants demandés sont valides",
"youtubeAuthInstructions": "Rends-toi sur {verification_url} et saisis le code : {user_code}",
"youtubeAuthStartFailed": "Échec du démarrage de l'authentification de l'appareil YouTube : {error}",
"gdriveLinkInstructions": "Rends-toi sur {verification_url} et saisis le code : {user_code}",
"gdriveAuthStartFailed": "Échec du démarrage de l'authentification de l'appareil Google Drive : {error}",
"discordAlertNotConfigured": "Le webhook d'alerte Discord n'est pas configuré"
},
"jobs": {
"created": "Tâche créée avec succès. Le traitement a commencé.",
"authError": "Erreur d'authentification : aucune identité d'utilisateur disponible",
"noDefaultTheme": "Aucun thème par défaut configuré. Contacte le support ou spécifie un theme_id.",
"notFound": "Tâche introuvable",
"noPermissionAccess": "Tu n'as pas l'autorisation d'accéder à cette tâche",
"noPermissionEdit": "Tu n'as pas l'autorisation de modifier cette tâche",
"noPermissionDelete": "Tu n'as pas l'autorisation de supprimer cette tâche",
"noPermissionModify": "Tu n'as pas l'autorisation de modifier cette tâche",
"notCompleted": "Seules les tâches terminées peuvent être modifiées. Statut actuel : {status}",
"alreadyBeingEdited": "Cette tâche est déjà en cours de modification (les résultats ont déjà été supprimés)",
"cleanupFailed": "Le nettoyage a échoué pour {services}. Tâche non modifiée. Réessaie ou contacte le support.",
"reopened": "Piste rouverte pour modification. Les résultats précédents ont été supprimés.",
"invalidDatetimeFormat": "Format {field} invalide : {value}",
"listError": "Erreur lors de la récupération de la liste des tâches : {error}",
"deleteError": "Erreur lors de la suppression de la tâche {job_id} : {error}",
"deletionPreview": "Ajoute &confirm=true pour exécuter la suppression",
"deletionRequiresFilters": "Au moins un filtre (environment, client_id, status, created_before) est requis",
"bulkDeleteError": "Erreur lors de la suppression en masse des tâches : {error}",
"reviewNotReady": "La tâche n'est pas prête pour la révision (statut actuel : {status})",
"correctionsUnavailable": "Données de correction non disponibles",
"audioUnavailable": "Audio non disponible pour la révision",
"reviewCannotStart": "Impossible de démarrer la révision",
"jobNotInReviewState": "La tâche n'est pas en attente de révision (statut actuel : {status})",
"correctionsProcessing": "Corrections enregistrées. Appelle /complete-review quand tu as terminé.",
"editLogSaveFailed": "Erreur lors de l'enregistrement du journal de modification pour la tâche {job_id} : {error}",
"stemsMissing": "Pistes requises manquantes pour cette tâche (instrumental_clean et/ou backing_vocals)",
"customInstrumentalFailed": "Erreur lors de la création de l'instrumental personnalisé pour la tâche {job_id} : {error}",
"audioProcessingFailed": "Échec du traitement du fichier audio : {error}",
"durationMismatch": "Incohérence de durée : le fichier importé fait {upload_duration} s mais l'audio original fait {original_duration} s. L'instrumental doit faire exactement {original_duration} s (±0.5s).",
"reviewNotInState": "La tâche n'est pas en attente de révision (statut actuel : {status})",
"noLyricsDetected": "Impossible de terminer la révision : aucune parole n'a été détectée dans l'audio. Cela peut arriver quand l'audio d'entrée n'a pas de voix (ex: une piste karaoké ou instrumentale). Tu peux revenir en arrière et coller les paroles manuellement en utilisant 'Replace All', ou annuler cette tâche et réessayer avec un fichier audio qui contient des voix.",
"reviewCompleteStartRendering": "Révision terminée. Le rendu vidéo a commencé.",
"reviewCompleteError": "Erreur lors de la finalisation de la révision pour la tâche {job_id} : {error}",
"instrumentalSelectionRequired": "instrumental_selection est requis. Doit être 'clean' ou 'with_backing'.",
"invalidInstrumentalSelection": "instrumental_selection invalide. Doit être l'un de : {valid_selections}",
"instrumentalSelected": "Instrumental sélectionné. La génération de la vidéo a commencé.",
"instrumentalSelectionError": "Erreur lors de la sélection de l'instrumental pour la tâche {job_id} : {error}",
"downloadUrlsError": "Erreur lors de l'obtention des URL de téléchargement : {error}"
},
"review": {
"jobNotFound": "Tâche introuvable",
"reviewNotReady": "La tâche n'est pas prête pour la révision (statut actuel : {status})",
"correctionsNotFound": "Données de correction introuvables. Le traitement des paroles n'est peut-être pas terminé.",
"correctionsLoadFailed": "Erreur lors du chargement des corrections : {error}",
"audioNotFound": "Fichier audio introuvable",
"audioServeError": "Erreur lors de la distribution de l'audio : {error}",
"instrumentalSelectionRequired": "instrumental_selection est requis. Doit être 'clean' ou 'with_backing'.",
"invalidInstrumentalSelection": "instrumental_selection invalide. Doit être l'un de : {valid_selections}",
"reviewCompletedError": "Erreur lors de la finalisation de la révision : {error}",
"handlersUpdateNotImplemented": "Les mises à jour des gestionnaires ne sont pas encore implémentées",
"lyricsAddError": "Échec de l'ajout des paroles : {error}",
"lyricsAddInvalidRequest": "Requête d'ajout de paroles invalide : {error}",
"lyricsSearchError": "Échec de la recherche de paroles : {error}",
"lyricsSearchInvalidRequest": "Requête de recherche de paroles invalide : {error}",
"lyricsSearchNoResults": "Aucune parole correspondante n'a été trouvée",
"previewVideoGenerationError": "Échec de la génération de la vidéo d'aperçu : {error}",
"previewVideoNotFound": "Vidéo d'aperçu introuvable",
"previewVideoStreamError": "Erreur lors de la diffusion de la vidéo d'aperçu : {error}",
"annotationSaveError": "Erreur lors de l'enregistrement des annotations : {error}",
"waveformGenerationError": "Erreur lors de la génération des données de forme d'onde : {error}",
"waveformNoAudio": "Aucun audio disponible pour la forme d'onde",
"sessionSaveError": "Les données de correction sont requises"
},
"audioSearch": {
"notEnabled": "La recherche audio n'est pas activée pour ce compte",
"disabled": "La recherche audio n'est pas disponible",
"downloadError": "Le téléchargement a échoué pour la tâche {job_id} : {error}",
"jobNotFound": "Tâche {job_id} introuvable",
"noSearchResults": "Aucun résultat de recherche disponible",
"invalidSelectionIndex": "Index de sélection invalide {selection_index}. Plage valide : 0-{max}",
"selectionError": "Erreur lors de la sélection audio pour la tâche {job_id} : {error}",
"youtubeDownloadError": "Le téléchargement YouTube a échoué : {error}",
"torrentDownloadError": "Impossible de télécharger depuis {source} sans le service flacfetch distant. Configure FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Aucun source_id ou remote_search_id disponible pour le téléchargement {source}",
"remoteDownloadCompleteNoPath": "Téléchargement distant terminé mais aucun chemin de fichier retourné",
"spotifyDownloadError": "Impossible de télécharger depuis Spotify sans le service flacfetch distant. Configure FLACFETCH_API_URL.",
"genericDownloadError": "Type de source inconnu : {source}, tentative de téléchargement générique",
"jobNotFoundDuringDownload": "Tâche {job_id} introuvable pendant le téléchargement en arrière-plan",
"selectAudioError": "Erreur lors de la sélection de l'audio pour la tâche {job_id} : {error}",
"searchAudioError": "Erreur lors de la recherche audio : {error}",
"searchCreatedSuccessfully": "Tâche créée. Recherche de l'audio en cours...",
"autoDownloadStarted": "Meilleur résultat sélectionné automatiquement. Le téléchargement commence..."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
"magicLinkSent": "Si cet e-mail est enregistré, tu recevras un lien de connexion sous peu.",
"emailServiceNotConfigured": "Le service d'e-mail n'est pas disponible. Contacte le support.",
"emailDomainNotAllowed": "Domaine d'e-mail non autorisé pour ce compte",
"invalidToken": "Jeton invalide",
"verifyError": "La vérification a échoué : {message}",
"magicLinkSuccess": "Connecté avec succès",
"logoutSuccess": "Déconnecté avec succès",
"userNotFound": "Utilisateur introuvable",
"creditPackagesError": "Erreur lors du chargement des forfaits de crédits : {error}",
"stripeSendError": "Erreur lors de l'envoi du lien de paiement Stripe : {error}",
"stripeWebhookProcessingError": "Erreur lors du traitement du webhook Stripe : {error}",
"feedbackSaveError": "Erreur lors de l'enregistrement des commentaires : {error}",
"feedbackNotEligible": "Utilisateur non éligible pour laisser des commentaires"
},
"fileUpload": {
"invalidTheme": "Thème introuvable : {theme_id}. Utilise GET /api/themes pour lister les thèmes disponibles.",
"uploadSuccess": "Fichier importé avec succès. Le traitement a commencé.",
"uploadError": "Erreur lors de l'importation du fichier : {error}",
"urlDownloadError": "Erreur lors du téléchargement depuis l'URL : {error}",
"invalidContentType": "Type de contenu invalide : {content_type}",
"fileSizeError": "Le fichier est trop volumineux : {size}. Maximum : {max_size}",
"invalidFileType": "Type de fichier invalide : {file_type}",
"multipleAudioFilesNotAllowed": "Un seul fichier audio peut être importé",
"noAudioFileProvided": "Aucun fichier audio fourni",
"urlCreationSuccess": "Tâche créée. URL d'importation générées.",
"urlCreationError": "Erreur lors de la création de la tâche avec les URL d'importation : {error}",
"uploadsCompleteSuccess": "Importations terminées. Le traitement a commencé.",
"uploadsCompleteError": "Erreur lors de la finalisation des importations : {error}",
"noUploadedFiles": "Aucun fichier importé spécifié",
"styleUploadUrlsSuccess": "URL d'importation de style générées.",
"styleUploadsCompleteSuccess": "Fichiers de style mis à jour. Le traitement a redémarré.",
"styleUploadsCompleteError": "Erreur lors de la finalisation des importations de style : {error}"
},
"catalog": {
"rateLimitExceeded": "Limite de requêtes dépassée. Maximum {max_requests} requêtes de catalogue par minute.",
"catalogSearchError": "Erreur lors de la recherche dans le catalogue : {error}",
"communityCheckError": "Erreur lors de la vérification des versions de la communauté : {error}"
},
"themes": {
"themesLoadError": "Échec du chargement des thèmes",
"themeNotFound": "Thème introuvable : {theme_id}",
"themeLoadError": "Échec du chargement du thème",
"previewNotAvailable": "Aucun aperçu disponible pour le thème : {theme_id}",
"previewLoadError": "Échec du chargement de l'aperçu du thème",
"youtubeDescriptionNotFound": "Thème introuvable : {theme_id}",
"youtubeDescriptionLoadError": "Échec du chargement de la description YouTube"
},
"tenant": {
"assetNotFound": "Ressource introuvable"
},
"push": {
"disabled": "Les notifications push ne sont pas activées",
"userEmailNotAvailable": "E-mail de l'utilisateur non disponible",
"missingEncryptionKeys": "Clés requises manquantes (p256dh, auth)",
"subscriptionSaveFailed": "Échec de l'enregistrement de l'abonnement",
"subscriptionRegistered": "Abonnement push enregistré avec succès",
"subscriptionNotFound": "Abonnement supprimé (ou introuvable)",
"subscriptionRemoved": "Abonnement push supprimé avec succès",
"testNotificationSent": "Notification de test envoyée à {sent_count} appareil(s)"
},
"pushNotifications": {
"reviewLyricsTitle": "Réviser les paroles",
"reviewLyricsBody": "\"{title}\" de {artist} nécessite une révision des paroles",
"selectInstrumentalTitle": "Sélectionner l'instrumental",
"selectInstrumentalBody": "\"{title}\" de {artist} nécessite la sélection d'un instrumental",
"videoReadyTitle": "Vidéo prête !",
"videoReadyBody": "Ta vidéo karaoké pour \"{title}\" de {artist} est prête à être téléchargée"
},
"admin": {
"invalidDomainFormat": "Format de domaine invalide",
"domainAddedToBl": "Domaine '{domain}' ajouté à la liste de blocage des domaines jetables",
"domainNotFoundInBl": "Domaine introuvable dans la liste de blocage",
"domainRemovedFromBl": "Domaine '{domain}' retiré de la liste de blocage des domaines jetables",
"domainAddedToAllowlist": "Domaine '{domain}' ajouté à la liste blanche",
"domainNotFoundInAllowlist": "Domaine introuvable dans la liste blanche",
"domainRemovedFromAllowlist": "Domaine '{domain}' retiré de la liste blanche",
"syncComplete": "{external_count} domaines externes synchronisés ({added} ajoutés, {removed} retirés)",
"invalidEmailFormat": "Format d'e-mail invalide",
"emailAddedToBl": "E-mail '{email}' ajouté à la liste des e-mails bloqués",
"emailNotFoundInBl": "E-mail introuvable dans la liste de blocage",
"emailRemovedFromBl": "E-mail '{email}' retiré de la liste des e-mails bloqués",
"invalidIPAddress": "Adresse IP invalide",
"ipAddedToBl": "IP '{ip_address}' ajoutée à la liste des IP bloquées",
"ipNotFoundInBl": "IP introuvable dans la liste de blocage",
"ipRemovedFromBl": "IP '{ip_address}' retirée de la liste des IP bloquées",
"youtubeUploadNotFound": "Mise en ligne introuvable ou pas dans un état réessayable pour la tâche {job_id}",
"youtubeUploadQueuedForRetry": "La mise en ligne YouTube pour la tâche {job_id} est en file d'attente pour un nouvel essai",
"youtubeQueueProcessingStarted": "Le traitement de la file d'attente YouTube a commencé en arrière-plan"
},
"rateLimits": {
"configNotFound": "Configuration de limite de requêtes introuvable : {config_id}",
"configUpdateError": "Erreur lors de la mise à jour de la configuration de limite de requêtes : {error}"
},
"errors": {
"insufficientCredits": "Crédits insuffisants pour cette opération",
"insufficientCreditsBuyUrl": "/#pricing"
},
"emails": {
"magicLink": {
"subject": "Connecte-toi à {brand_name}",
"greeting": "Salut,",
"signInPrompt": "Clique sur le bouton ci-dessous pour te connecter à {brand_name} :",
"signInButton": "Se connecter",
"expiryWarning": "Ce lien expire dans 15 minutes et ne peut être utilisé qu'une seule fois.",
"fallbackLink": "Si le bouton ne fonctionne pas, copie et colle ce lien dans ton navigateur :",
"ignoreNote": "Si tu n'as pas demandé cet e-mail, tu peux l'ignorer en toute sécurité."
},
"welcome": {
"subject": "Bienvenue sur Nomad Karaoke !",
"welcomeGreeting": "Bienvenue sur Nomad Karaoke !",
"turnAnySong": "Transforme n'importe quelle chanson en vidéo karaoké professionnelle en quelques minutes.",
"freeCreditsLabel": "Crédits gratuits",
"freeCreditsNote": "Chaque crédit crée une vidéo karaoké professionnelle",
"howItWorks": "Voici comment ça marche :",
"step1Title": "1. Recherche une chanson",
"step1Desc": "Entre l'artiste et le titre, et nous trouverons un audio de haute qualité.",
"step2Title": "2. Notre système fait sa magie",
"step2Desc": "Nous séparons les voix, transcrivons les paroles et synchronisons tout parfaitement.",
"step3Title": "3. Révise et personnalise",
"step3Desc": "Ajuste les paroles si besoin, choisis ton instrumental.",
"step4Title": "4. Obtiens ta vidéo",
"step4Desc": "Télécharge ta vidéo karaoké en 4K ou mets-la en ligne directement sur YouTube.",
"feedbackBonus": "Termine 2 vidéos et gagne 2 crédits gratuits supplémentaires en partageant tes commentaires !",
"getStartedButton": "Commencer"
},
"creditsAdded": {
"subject": "{credits} crédits ajoutés à ton compte Nomad Karaoke",
"greatNews": "Bonne nouvelle !",
"creditsAddedMessage": "{credits} crédits ont été ajoutés à ton compte.",
"yourBalance": "Ton solde :",
"credits": "crédits",
"eachCreditLets": "Chaque crédit te permet de créer une vidéo karaoké professionnelle avec :",
"featureVocalSeparation": "Séparation voix/instrumental par IA",
"featureLyrics": "Paroles synchronisées au mot près",
"feature4k": "Sortie vidéo 4K",
"featureYoutube": "Mise en ligne YouTube",
"createButton": "Créer un karaoké maintenant"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code} : {artist} - {title} (Ta vidéo karaoké est prête !)",
"subject": "{artist} - {title} (Ta vidéo karaoké est prête !)",
"subjectFallback": "Ta vidéo karaoké est prête !"
},
"youtubeUpload": {
"subjectWithBrand": "{brand_code} : {artist} - {title} (Mise en ligne YouTube prête !)",
"subject": "{artist} - {title} (Mise en ligne YouTube prête !)",
"subjectFallback": "Ta mise en ligne YouTube est prête !"
},
"actionReminder": {
"lyricsSubject": "Action requise : Révise les paroles pour {artist} - {title}",
"lyricsSubjectFallback": "Action requise : Révise les paroles",
"instrumentalSubject": "Action requise : Sélectionne l'instrumental pour {artist} - {title}",
"instrumentalSubjectFallback": "Action requise : Sélectionne l'instrumental",
"audioEditSubject": "Action requise pour {artist} - {title}",
"audioEditSubjectFallback": "Action requise",
"alertHeading": "Ta vidéo karaoké a besoin de toi !"
},
"reviewReminder": {
"subject": "Rappel : Ta vidéo karaoké attend d'être révisée — {artist} - {title}",
"subjectFallback": "Rappel : Ta vidéo karaoké attend d'être révisée",
"alertHeading": "Ta vidéo karaoké t'attend !",
"reminderIntro": "Juste un petit rappel que ta vidéo karaoké{song_name} est prête pour la révision.",
"reviewButton": "Réviser ta vidéo",
"reviewInstructions": "Pendant la révision, tu peux vérifier que les paroles sont correctes et choisir ta piste instrumentale préférée. Ça ne prend généralement que quelques minutes !",
"helpOffer": "Si tu as des difficultés avec le processus de révision, réponds simplement à cet e-mail et je serai heureux de t'aider.",
"expiryWarning": "Attention : si la révision n'est pas terminée dans les prochaines 24 heures, la tâche expirera automatiquement et ton crédit sera remboursé."
},
"reviewExpired": {
"subject": "Ta vidéo karaoké a expiré — {artist} - {title}",
"subjectFallback": "Ta vidéo karaoké a expiré",
"cancelNotice": "Ta vidéo karaoké{song_name} a été automatiquement annulée car la révision n'a pas été terminée dans les 48 heures.",
"refundNotice": "Ne t'inquiète pas — ton crédit a été remboursé ! Ton solde actuel est de {credits_balance} {credits_word}.",
"creditSingular": "crédit",
"creditPlural": "crédits",
"createNewPrompt": "Tu peux créer une nouvelle vidéo karaoké à tout moment en utilisant tes crédits :",
"createButton": "Créer une nouvelle vidéo",
"helpOffer": "Si tu as eu des difficultés avec le processus de révision ou si tu as besoin d'aide, réponds simplement à cet e-mail — j'adorerais t'aider !"
},
"creditDenied": {
"subject": "À propos de tes crédits gratuits Nomad Karaoke",
"greeting": "Salut,",
"thankYou": "Merci de t'être inscrit sur Nomad Karaoke !",
"deniedMessage": "Malheureusement, nous n'avons pas pu t'accorder tes {credit_type} gratuits cette fois-ci. Notre système a détecté des schémas suggérant que ce n'est peut-être pas ton premier compte chez nous, et chaque tâche de génération de karaoké nous coûte de l'argent réel en frais de cloud et d'API.",
"mistakeNote": "Nous comprenons tout à fait si c'est une erreur ! Si tu es un véritable nouvel utilisateur, réponds simplement à cet e-mail et fais-le savoir à Andrew (le fondateur). Il a créé ce service et sera heureux de t'accorder quelques crédits gratuits pour l'essayer — il te demande juste de lui faire un retour honnête sur ton expérience en échange.",
"buyPrompt": "Si tu souhaites commencer tout de suite, tu peux aussi acheter des crédits :",
"buyButton": "Acheter des crédits",
"costNote": "Nous maintenons les coûts bas pour pouvoir offrir le service à un prix abordable, ce qui signifie que nous devons faire attention aux abus de crédits gratuits. Merci de ta compréhension !",
"welcomeCredits": "crédits de bienvenue",
"feedbackCredits": "crédits bonus de commentaires"
},
"madeForYouConfirmation": {
"subject": "Commande confirmée : {artist} - {title} | Nomad Karaoke",
"thankYou": "Merci pour ta commande !",
"orderDetails": "Détails de la commande",
"orderId": "ID de commande :",
"artist": "Artiste :",
"title": "Titre :",
"yourNotes": "Tes notes :",
"deliveryTime": "Notre équipe créera ta vidéo karaoké personnalisée dans les {hours} heures.",
"deliveryNotice": "Tu recevras un e-mail avec les liens de téléchargement dès que ta vidéo sera prête.",
"noAction": "Aucune action requise — détends-toi et nous nous occupons de tout !"
},
"shared": {
"footerHelp": "Si quelque chose n'est pas parfait, réponds simplement à cet e-mail et je le corrigerai !"
},
"templates": {
"jobCompletion": {
"greeting": "Salut {name},",
"thanks": "Merci pour ta commande !",
"youtubeLink": "Voici le lien de la vidéo karaoké publiée sur YouTube :",
"dropboxIntro": "Voici le dossier Dropbox avec tous les fichiers terminés et les fichiers sources, y compris :",
"fileList": "- \"(Final Karaoke Lossless).mkv\" : vidéo karaoké combinée en 4K H264 avec audio FLAC sans perte\n- \"(Final Karaoke).mp4\" : vidéo karaoké combinée avec écran titre/fin en 4K H264/AAC\n- \"(Final Karaoke 720p).mp4\" : vidéo karaoké combinée en 720p H264/AAC (fichier plus petit pour les anciens systèmes)\n- \"(With Vocals).mp4\" : vidéo pour chanter en 4K H264/AAC avec les voix originales\n- \"(Karaoke).mov\" : sortie vidéo karaoké de MidiCo (sans écran titre/fin)\n- \"(Title).mov\"/\"(End).mov\" : vidéos de l'écran titre et de l'écran de fin\n- \"(Final Karaoke CDG).zip\" : format CDG+MP3 pour les systèmes karaoké anciens/commerciaux\n- \"(Final Karaoke TXT).zip\" : format TXT+MP3 pour Power Karaoke\n- stems/*.flac : diverses pistes audio séparées instrumentales et vocales au format sans perte\n- lyrics/*.txt : paroles de la chanson de diverses sources au format texte brut",
"fixOffer": "Fais-moi savoir si quelque chose n'est pas parfait et je le modifierai/corrigerai avec plaisir, ou si tu en as besoin dans un autre format, je peux probablement le convertir pour toi !",
"feedbackRequest": "Si tu as un moment, j'apprécierais vraiment tes commentaires (ça prend 2 minutes) :",
"signOff": "Merci encore et passe une excellente journée !\n-Andrew",
"youtubeQueued": "Ta mise en ligne YouTube est en file d'attente et sera traitée automatiquement. Tu recevras un e-mail de suivi avec le lien sous peu."
},
"actionLyrics": {
"greeting": "Salut {name},",
"ready": "Ta vidéo karaoké pour \"{artist} - {title}\" est prête pour la révision !",
"instructions": "Notre système a transcrit et synchronisé les paroles, mais elles peuvent nécessiter quelques corrections. Tu pourras également sélectionner ta piste instrumentale préférée (avec ou sans chœurs).",
"reviewPrompt": "Révise tes paroles et sélectionne un instrumental :",
"duration": "Cela ne prend généralement que quelques minutes.",
"signOff": "Merci !\n-Andrew"
},
"actionInstrumental": {
"greeting": "Salut {name},",
"almostDone": "Ta vidéo karaoké pour \"{artist} - {title}\" est presque terminée !",
"instructions": "Nous avons séparé l'audio en différentes versions. Choisis la piste instrumentale que tu souhaites utiliser pour la vidéo finale.",
"selectPrompt": "Sélectionne ton instrumental ici :",
"signOff": "Merci !\n-Andrew"
},
"youtubeComplete": {
"greeting": "Salut {name},",
"greatNews": "Bonne nouvelle ! Ta vidéo karaoké pour \"{artist} - {title}\" a été mise en ligne sur YouTube :",
"delayNote": "Cette mise en ligne a été brièvement retardée pendant que nos systèmes traitaient d'autres mises en ligne, mais tout est prêt maintenant.",
"signOff": "Merci !\n-Andrew"
}
}
}
}
+338
View File
@@ -0,0 +1,338 @@
{
"auth": {
"unknownService": "שירות לא ידוע: {service}",
"invalidCredentials": "השירותים הבאים דורשים אישור מחדש: {services}",
"validCredentials": "כל האישורים המבוקשים תקינים",
"youtubeAuthInstructions": "היכנסו לכתובת {verification_url} והזינו את הקוד: {user_code}",
"youtubeAuthStartFailed": "הפעלת אימות מכשיר ב-YouTube נכשלה: {error}",
"gdriveLinkInstructions": "היכנסו לכתובת {verification_url} והזינו את הקוד: {user_code}",
"gdriveAuthStartFailed": "הפעלת אימות מכשיר ב-Google Drive נכשלה: {error}",
"discordAlertNotConfigured": "Webhook של התראות Discord לא מוגדר"
},
"jobs": {
"created": "המשימה נוצרה בהצלחה. העיבוד התחיל.",
"authError": "שגיאת אימות: אין זהות משתמש זמינה",
"noDefaultTheme": "לא הוגדרה ערכת נושא כברירת מחדל. צרו קשר עם התמיכה או ציינו theme_id.",
"notFound": "המשימה לא נמצאה",
"noPermissionAccess": "אין לך הרשאה לגשת למשימה זו",
"noPermissionEdit": "אין לך הרשאה לערוך משימה זו",
"noPermissionDelete": "אין לך הרשאה למחוק משימה זו",
"noPermissionModify": "אין לך הרשאה לשנות משימה זו",
"notCompleted": "ניתן לערוך רק משימות שהושלמו. סטטוס נוכחי: {status}",
"alreadyBeingEdited": "משימה זו כבר נמצאת בעריכה (התוצרים הקודמים כבר נמחקו)",
"cleanupFailed": "הניקוי נכשל עבור {services}. המשימה לא שונתה. נסו שוב או צרו קשר עם התמיכה.",
"reopened": "הרצועה נפתחה מחדש לעריכה. התוצרים הקודמים הוסרו.",
"invalidDatetimeFormat": "פורמט {field} לא חוקי: {value}",
"listError": "שגיאה בטעינת רשימת המשימות: {error}",
"deleteError": "שגיאה במחיקת המשימה {job_id}: {error}",
"deletionPreview": "הוסיפו &confirm=true כדי לבצע את המחיקה",
"deletionRequiresFilters": "נדרש לפחות מסנן אחד (environment, client_id, status, created_before)",
"bulkDeleteError": "שגיאה במחיקה מרוכזת של משימות: {error}",
"reviewNotReady": "המשימה אינה מוכנה לבדיקה (סטטוס נוכחי: {status})",
"correctionsUnavailable": "נתוני התיקונים אינם זמינים",
"audioUnavailable": "האודיו אינו זמין לבדיקה",
"reviewCannotStart": "לא ניתן להתחיל בבדיקה",
"jobNotInReviewState": "המשימה אינה במצב בדיקה (סטטוס נוכחי: {status})",
"correctionsProcessing": "התיקונים נשמרו. קראו ל- /complete-review כשתסיימו.",
"editLogSaveFailed": "שגיאה בשמירת יומן העריכה עבור המשימה {job_id}: {error}",
"stemsMissing": "למשימה חסרים ערוצים נדרשים (instrumental_clean ו/או backing_vocals)",
"customInstrumentalFailed": "שגיאה ביצירת פלייבק מותאם אישית עבור המשימה {job_id}: {error}",
"audioProcessingFailed": "עיבוד קובץ האודיו נכשל: {error}",
"durationMismatch": "אי התאמה באורך: הקובץ שהועלה הוא {upload_duration} שניות אך האודיו המקורי הוא {original_duration} שניות. הפלייבק חייב להיות בדיוק {original_duration} שניות (±0.5 שניות).",
"reviewNotInState": "המשימה אינה במצב בדיקה (סטטוס נוכחי: {status})",
"noLyricsDetected": "לא ניתן להשלים את הבדיקה: לא זוהו מילים באודיו. זה יכול לקרות כאשר באודיו שהוזן אין שירה (למשל רצועת קריוקי או פלייבק). אפשר לחזור ולהדביק מילים ידנית באמצעות 'Replace All', או לבטל את המשימה ולנסות שוב עם קובץ אודיו שמכיל שירה.",
"reviewCompleteStartRendering": "הבדיקה הושלמה. עיבוד הווידאו התחיל.",
"reviewCompleteError": "שגיאה בהשלמת הבדיקה עבור המשימה {job_id}: {error}",
"instrumentalSelectionRequired": "נדרש instrumental_selection. חייב להיות 'clean' או 'with_backing'.",
"invalidInstrumentalSelection": "בחירת instrumental_selection לא חוקית. חייב להיות אחד מ: {valid_selections}",
"instrumentalSelected": "הפלייבק נבחר. יצירת הווידאו התחילה.",
"instrumentalSelectionError": "שגיאה בבחירת פלייבק עבור המשימה {job_id}: {error}",
"downloadUrlsError": "שגיאה בקבלת כתובות ההורדה: {error}"
},
"review": {
"jobNotFound": "המשימה לא נמצאה",
"reviewNotReady": "המשימה אינה מוכנה לבדיקה (סטטוס נוכחי: {status})",
"correctionsNotFound": "נתוני התיקונים לא נמצאו. ייתכן שעיבוד המילים טרם הושלם.",
"correctionsLoadFailed": "שגיאה בטעינת התיקונים: {error}",
"audioNotFound": "קובץ האודיו לא נמצא",
"audioServeError": "שגיאה בהגשת האודיו: {error}",
"instrumentalSelectionRequired": "נדרש instrumental_selection. חייב להיות 'clean' או 'with_backing'.",
"invalidInstrumentalSelection": "בחירת instrumental_selection לא חוקית. חייב להיות אחד מ: {valid_selections}",
"reviewCompletedError": "שגיאה בהשלמת הבדיקה: {error}",
"handlersUpdateNotImplemented": "עדכוני Handlers טרם יושמו",
"lyricsAddError": "הוספת המילים נכשלה: {error}",
"lyricsAddInvalidRequest": "בקשה לא חוקית להוספת מילים: {error}",
"lyricsSearchError": "חיפוש המילים נכשל: {error}",
"lyricsSearchInvalidRequest": "בקשה לא חוקית לחיפוש מילים: {error}",
"lyricsSearchNoResults": "לא נמצאו מילים תואמות מאף ספק",
"previewVideoGenerationError": "יצירת סרטון התצוגה המקדימה נכשלה: {error}",
"previewVideoNotFound": "סרטון התצוגה המקדימה לא נמצא",
"previewVideoStreamError": "שגיאה בהזרמת סרטון התצוגה המקדימה: {error}",
"annotationSaveError": "שגיאה בשמירת ההערות: {error}",
"waveformGenerationError": "שגיאה ביצירת נתוני גל הקול: {error}",
"waveformNoAudio": "אין אודיו זמין עבור גל הקול",
"sessionSaveError": "נדרשים נתוני תיקון"
},
"audioSearch": {
"notEnabled": "חיפוש אודיו אינו מופעל עבור חשבון זה",
"disabled": "חיפוש אודיו אינו זמין",
"downloadError": "ההורדה נכשלה עבור המשימה {job_id}: {error}",
"jobNotFound": "המשימה {job_id} לא נמצאה",
"noSearchResults": "אין תוצאות חיפוש זמינות",
"invalidSelectionIndex": "אינדקס בחירה לא חוקי {selection_index}. טווח חוקי: 0-{max}",
"selectionError": "שגיאה במהלך בחירת האודיו עבור המשימה {job_id}: {error}",
"youtubeDownloadError": "ההורדה מ-YouTube נכשלה: {error}",
"torrentDownloadError": "לא ניתן להוריד מ-{source} ללא שירות flacfetch מרוחק. הגדירו את FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "אין source_id או remote_search_id זמינים להורדה מ-{source}",
"remoteDownloadCompleteNoPath": "ההורדה המרוחקת הושלמה אך לא הוחזר נתיב קובץ",
"spotifyDownloadError": "לא ניתן להוריד מ-Spotify ללא שירות flacfetch מרוחק. הגדירו את FLACFETCH_API_URL.",
"genericDownloadError": "סוג מקור לא ידוע: {source}, מנסה הורדה כללית",
"jobNotFoundDuringDownload": "המשימה {job_id} לא נמצאה במהלך ההורדה ברקע",
"selectAudioError": "שגיאה בבחירת אודיו עבור המשימה {job_id}: {error}",
"searchAudioError": "שגיאה בחיפוש אודיו: {error}",
"searchCreatedSuccessfully": "המשימה נוצרה. מחפש אודיו...",
"autoDownloadStarted": "התוצאה הטובה ביותר נבחרה אוטומטית. ההורדה מתחילה..."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
"magicLinkSent": "אם כתובת דוא\"ל זו רשומה, תקבלו קישור התחברות בקרוב.",
"emailServiceNotConfigured": "שירות הדוא\"ל אינו זמין. צרו קשר עם התמיכה.",
"emailDomainNotAllowed": "דומיין הדוא\"ל אינו מורשה עבור חשבון זה",
"invalidToken": "אסימון לא חוקי",
"verifyError": "האימות נכשל: {message}",
"magicLinkSuccess": "התחברתם בהצלחה",
"logoutSuccess": "התנתקתם בהצלחה",
"userNotFound": "המשתמש לא נמצא",
"creditPackagesError": "שגיאה בטעינת חבילות הקרדיטים: {error}",
"stripeSendError": "שגיאה בשליחת קישור התשלום של Stripe: {error}",
"stripeWebhookProcessingError": "שגיאה בעיבוד ה-webhook של Stripe: {error}",
"feedbackSaveError": "שגיאה בשמירת המשוב: {error}",
"feedbackNotEligible": "המשתמש אינו זכאי למשוב"
},
"fileUpload": {
"invalidTheme": "ערכת הנושא לא נמצאה: {theme_id}. השתמשו ב- GET /api/themes כדי להציג את ערכות הנושא הזמינות.",
"uploadSuccess": "הקובץ הועלה בהצלחה. העיבוד התחיל.",
"uploadError": "שגיאה בהעלאת הקובץ: {error}",
"urlDownloadError": "שגיאה בהורדה מהכתובת: {error}",
"invalidContentType": "סוג תוכן לא חוקי: {content_type}",
"fileSizeError": "הקובץ גדול מדי: {size}. מקסימום: {max_size}",
"invalidFileType": "סוג קובץ לא חוקי: {file_type}",
"multipleAudioFilesNotAllowed": "ניתן להעלות רק קובץ אודיו אחד",
"noAudioFileProvided": "לא סופק קובץ אודיו",
"urlCreationSuccess": "המשימה נוצרה. כתובות ההעלאה נוצרו.",
"urlCreationError": "שגיאה ביצירת משימה עם כתובות העלאה: {error}",
"uploadsCompleteSuccess": "ההעלאות הושלמו. העיבוד התחיל.",
"uploadsCompleteError": "שגיאה בהשלמת ההעלאות: {error}",
"noUploadedFiles": "לא צוינו קבצים שהועלו",
"styleUploadUrlsSuccess": "כתובות העלאת הסגנון נוצרו.",
"styleUploadsCompleteSuccess": "קבצי הסגנון עודכנו. העיבוד התחיל מחדש.",
"styleUploadsCompleteError": "שגיאה בהשלמת העלאות הסגנון: {error}"
},
"catalog": {
"rateLimitExceeded": "חריגה ממגבלת הבקשות. מקסימום {max_requests} בקשות קטלוג בדקה.",
"catalogSearchError": "שגיאה בחיפוש בקטלוג: {error}",
"communityCheckError": "שגיאה בבדיקת גרסאות הקהילה: {error}"
},
"themes": {
"themesLoadError": "טעינת ערכות הנושא נכשלה",
"themeNotFound": "ערכת הנושא לא נמצאה: {theme_id}",
"themeLoadError": "טעינת ערכת הנושא נכשלה",
"previewNotAvailable": "אין תצוגה מקדימה זמינה עבור ערכת הנושא: {theme_id}",
"previewLoadError": "טעינת התצוגה המקדימה של ערכת הנושא נכשלה",
"youtubeDescriptionNotFound": "ערכת הנושא לא נמצאה: {theme_id}",
"youtubeDescriptionLoadError": "טעינת התיאור ל-YouTube נכשלה"
},
"tenant": {
"assetNotFound": "הנכס לא נמצא"
},
"push": {
"disabled": "התראות פוש אינן מופעלות",
"userEmailNotAvailable": "דוא\"ל המשתמש אינו זמין",
"missingEncryptionKeys": "חסרים מפתחות נדרשים (p256dh, auth)",
"subscriptionSaveFailed": "שמירת המינוי נכשלה",
"subscriptionRegistered": "מינוי הפוש נרשם בהצלחה",
"subscriptionNotFound": "המינוי הוסר (או לא נמצא)",
"subscriptionRemoved": "מינוי הפוש הוסר בהצלחה",
"testNotificationSent": "התראת ניסיון נשלחה ל-{sent_count} מכשיר(ים)"
},
"pushNotifications": {
"reviewLyricsTitle": "בדיקת מילים",
"reviewLyricsBody": "\"{title}\" מאת {artist} דורש בדיקת מילים",
"selectInstrumentalTitle": "בחירת פלייבק",
"selectInstrumentalBody": "\"{title}\" מאת {artist} דורש בחירת פלייבק",
"videoReadyTitle": "הווידאו מוכן!",
"videoReadyBody": "סרטון הקריוקי שלכם עבור \"{title}\" מאת {artist} מוכן להורדה"
},
"admin": {
"invalidDomainFormat": "פורמט דומיין לא חוקי",
"domainAddedToBl": "הדומיין '{domain}' נוסף לרשימת החסימה של דומיינים חד-פעמיים",
"domainNotFoundInBl": "הדומיין לא נמצא ברשימת החסימה",
"domainRemovedFromBl": "הדומיין '{domain}' הוסר מרשימת החסימה של דומיינים חד-פעמיים",
"domainAddedToAllowlist": "הדומיין '{domain}' נוסף לרשימת ההיתרים",
"domainNotFoundInAllowlist": "הדומיין לא נמצא ברשימת ההיתרים",
"domainRemovedFromAllowlist": "הדומיין '{domain}' הוסר מרשימת ההיתרים",
"syncComplete": "סונכרנו {external_count} דומיינים חיצוניים ({added} נוספו, {removed} הוסרו)",
"invalidEmailFormat": "פורמט דוא\"ל לא חוקי",
"emailAddedToBl": "הדוא\"ל '{email}' נוסף לרשימת כתובות הדוא\"ל החסומות",
"emailNotFoundInBl": "הדוא\"ל לא נמצא ברשימת החסימה",
"emailRemovedFromBl": "הדוא\"ל '{email}' הוסר מרשימת כתובות הדוא\"ל החסומות",
"invalidIPAddress": "כתובת IP לא חוקית",
"ipAddedToBl": "ה-IP '{ip_address}' נוסף לרשימת ה-IP החסומים",
"ipNotFoundInBl": "ה-IP לא נמצא ברשימת החסימה",
"ipRemovedFromBl": "ה-IP '{ip_address}' הוסר מרשימת ה-IP החסומים",
"youtubeUploadNotFound": "ההעלאה לא נמצאה או שאינה במצב שניתן לנסות שוב עבור המשימה {job_id}",
"youtubeUploadQueuedForRetry": "העלאה ל-YouTube עבור המשימה {job_id} הוכנסה לתור לניסיון חוזר",
"youtubeQueueProcessingStarted": "עיבוד תור YouTube התחיל ברקע"
},
"rateLimits": {
"configNotFound": "הגדרת מגבלת הבקשות לא נמצאה: {config_id}",
"configUpdateError": "שגיאה בעדכון הגדרת מגבלת הבקשות: {error}"
},
"errors": {
"insufficientCredits": "אין מספיק קרדיטים לפעולה זו",
"insufficientCreditsBuyUrl": "/#pricing"
},
"emails": {
"magicLink": {
"subject": "התחברות אל {brand_name}",
"greeting": "שלום,",
"signInPrompt": "לחצו על הכפתור למטה כדי להתחבר אל {brand_name}:",
"signInButton": "התחברות",
"expiryWarning": "קישור זה יפוג בעוד 15 דקות וניתן להשתמש בו פעם אחת בלבד.",
"fallbackLink": "אם הכפתור לא עובד, העתיקו והדביקו את הקישור הזה לדפדפן שלכם:",
"ignoreNote": "אם לא ביקשתם את האימייל הזה, אתם יכולים להתעלם ממנו בבטחה."
},
"welcome": {
"subject": "ברוכים הבאים אל Nomad Karaoke!",
"welcomeGreeting": "ברוכים הבאים אל Nomad Karaoke!",
"turnAnySong": "הפכו כל שיר לסרטון קריוקי מקצועי תוך דקות.",
"freeCreditsLabel": "קרדיטים בחינם",
"freeCreditsNote": "כל קרדיט יוצר סרטון קריוקי מקצועי אחד",
"howItWorks": "כך זה עובד:",
"step1Title": "1. חפשו שיר",
"step1Desc": "הזינו את שם האמן והשיר, ואנחנו נמצא אודיו באיכות גבוהה.",
"step2Title": "2. המערכת שלנו עושה את הקסם",
"step2Desc": "אנחנו מפרידים את השירה, מתמללים את המילים ומסנכרנים הכל בצורה מושלמת.",
"step3Title": "3. סקירה והתאמה אישית",
"step3Desc": "תקנו את המילים במידת הצורך, ובחרו את הפלייבק שלכם.",
"step4Title": "4. קבלו את הווידאו שלכם",
"step4Desc": "הורידו את סרטון הקריוקי שלכם ב-4K או העלו ישירות ל-YouTube.",
"feedbackBonus": "השלימו 2 סרטונים והרוויחו עוד 2 קרדיטים בחינם על ידי שיתוף המשוב שלכם!",
"getStartedButton": "בואו נתחיל"
},
"creditsAdded": {
"subject": "{credits} קרדיטים נוספו לחשבון ה-Nomad Karaoke שלכם",
"greatNews": "חדשות מעולות!",
"creditsAddedMessage": "{credits} קרדיטים נוספו לחשבון שלכם.",
"yourBalance": "היתרה שלכם:",
"credits": "קרדיטים",
"eachCreditLets": "כל קרדיט מאפשר לכם ליצור סרטון קריוקי מקצועי אחד עם:",
"featureVocalSeparation": "הפרדת שירה/פלייבק מבוססת בינה מלאכותית",
"featureLyrics": "מילים מסונכרנות עם תזמון ברמת המילה",
"feature4k": "פלט וידאו ב-4K",
"featureYoutube": "העלאה ל-YouTube",
"createButton": "צרו קריוקי עכשיו"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (סרטון הקריוקי שלכם מוכן!)",
"subject": "{artist} - {title} (סרטון הקריוקי שלכם מוכן!)",
"subjectFallback": "סרטון הקריוקי שלכם מוכן!"
},
"youtubeUpload": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (ההעלאה ל-YouTube מוכנה!)",
"subject": "{artist} - {title} (ההעלאה ל-YouTube מוכנה!)",
"subjectFallback": "ההעלאה שלכם ל-YouTube מוכנה!"
},
"actionReminder": {
"lyricsSubject": "נדרשת פעולה: בדקו את המילים עבור {artist} - {title}",
"lyricsSubjectFallback": "נדרשת פעולה: בדקו את המילים",
"instrumentalSubject": "נדרשת פעולה: בחרו פלייבק עבור {artist} - {title}",
"instrumentalSubjectFallback": "נדרשת פעולה: בחרו פלייבק",
"audioEditSubject": "נדרשת פעולה עבור {artist} - {title}",
"audioEditSubjectFallback": "נדרשת פעולה",
"alertHeading": "סרטון הקריוקי שלכם זקוק להתייחסותכם!"
},
"reviewReminder": {
"subject": "תזכורת: סרטון הקריוקי שלכם ממתין לבדיקה — {artist} - {title}",
"subjectFallback": "תזכורת: סרטון הקריוקי שלכם ממתין לבדיקה",
"alertHeading": "סרטון הקריוקי שלכם מחכה לכם!",
"reminderIntro": "רק תזכורת ידידותית שסרטון הקריוקי שלכם{song_name} מוכן לבדיקה.",
"reviewButton": "בדקו את הווידאו שלכם",
"reviewInstructions": "במהלך הבדיקה, תוכלו לוודא שהמילים נכונות ולבחור את רצועת הפלייבק המועדפת עליכם. זה בדרך כלל לוקח רק כמה דקות!",
"helpOffer": "אם אתם נתקלים בבעיה כלשהי בתהליך הבדיקה, פשוט השיבו לאימייל הזה ואשמח לעזור לכם.",
"expiryWarning": "שימו לב: אם הבדיקה לא תושלם ב-24 השעות הקרובות, המשימה תפוג אוטומטית והקרדיט שלכם יוחזר."
},
"reviewExpired": {
"subject": "סרטון הקריוקי שלכם פג תוקף — {artist} - {title}",
"subjectFallback": "סרטון הקריוקי שלכם פג תוקף",
"cancelNotice": "סרטון הקריוקי שלכם{song_name} בוטל אוטומטית מכיוון שהבדיקה לא הושלמה תוך 48 שעות.",
"refundNotice": "אל דאגה — הקרדיט שלכם הוחזר! היתרה הנוכחית שלכם היא {credits_balance} {credits_word}.",
"creditSingular": "קרדיט",
"creditPlural": "קרדיטים",
"createNewPrompt": "אתם יכולים ליצור סרטון קריוקי חדש בכל עת באמצעות הקרדיטים שלכם:",
"createButton": "צרו וידאו חדש",
"helpOffer": "אם נתקלתם בבעיה כלשהי בתהליך הבדיקה או שאתם זקוקים לעזרה, פשוט השיבו לאימייל הזה — אשמח לעזור!"
},
"creditDenied": {
"subject": "בנוגע לקרדיטים החינמיים שלכם ב-Nomad Karaoke",
"greeting": "שלום,",
"thankYou": "תודה שנרשמתם ל-Nomad Karaoke!",
"deniedMessage": "לרוע המזל, לא הצלחנו להעניק לכם את ה-{credit_type} החינמיים הפעם. המערכת שלנו זיהתה דפוסים המצביעים על כך שייתכן שזהו אינו החשבון הראשון שלכם אצלנו, וכל משימת יצירת קריוקי עולה לנו כסף אמיתי בעלויות מחשוב ענן ו-API.",
"mistakeNote": "אנחנו מבינים לגמרי אם זו טעות! אם אתם משתמשים חדשים אמיתיים, אנא השיבו לאימייל הזה ועדכנו את אנדרו (המייסד). הוא בנה את השירות הזה וישמח להעניק לכם כמה קרדיטים בחינם כדי לנסות אותו — הוא רק מבקש שתספקו משוב כנה על החוויה בתמורה.",
"buyPrompt": "אם תרצו להתחיל מיד, תוכלו גם לרכוש קרדיטים:",
"buyButton": "רכשו קרדיטים",
"costNote": "אנחנו שומרים על עלויות נמוכות כדי שנוכל להציע את השירות במחיר משתלם, מה שאומר שאנחנו צריכים להיזהר מניצול לרעה של קרדיטים בחינם. תודה על ההבנה!",
"welcomeCredits": "קרדיטים של ברוכים הבאים",
"feedbackCredits": "קרדיטים כבונוס על משוב"
},
"madeForYouConfirmation": {
"subject": "ההזמנה אושרה: {artist} - {title} | Nomad Karaoke",
"thankYou": "תודה על ההזמנה שלכם!",
"orderDetails": "פרטי ההזמנה",
"orderId": "מספר הזמנה:",
"artist": "אמן:",
"title": "שם השיר:",
"yourNotes": "ההערות שלכם:",
"deliveryTime": "הצוות שלנו ייצור את סרטון הקריוקי המותאם אישית שלכם תוך {hours} שעות.",
"deliveryNotice": "תקבלו אימייל עם קישורי הורדה ברגע שהווידאו שלכם יהיה מוכן.",
"noAction": "אין צורך בשום פעולה — שבו בנחת ואנחנו נדאג להכל!"
},
"shared": {
"footerHelp": "אם משהו לא מושלם, פשוט השיבו לאימייל הזה ואני אתקן את זה!"
},
"templates": {
"jobCompletion": {
"greeting": "שלום {name},",
"thanks": "תודה על ההזמנה שלכם!",
"youtubeLink": "הנה הקישור לסרטון הקריוקי שפורסם ב-YouTube:",
"dropboxIntro": "הנה תיקיית ה-Dropbox עם כל הקבצים המוכנים וקובצי המקור, כולל:",
"fileList": "- \"(Final Karaoke Lossless).mkv\": סרטון קריוקי משולב ב-4K H264 עם אודיו FLAC ללא אובדן נתונים\n- \"(Final Karaoke).mp4\": סרטון קריוקי משולב עם מסך פתיחה/סיום ב-4K H264/AAC\n- \"(Final Karaoke 720p).mp4\": סרטון קריוקי משולב ב-720p H264/AAC (קובץ קטן יותר למערכות ישנות)\n- \"(With Vocals).mp4\": סרטון לשירה יחד ב-4K H264/AAC עם השירה המקורית\n- \"(Karaoke).mov\": פלט סרטון קריוקי מ-MidiCo (ללא מסך פתיחה/סיום)\n- \"(Title).mov\"/\"(End).mov\": סרטוני מסך פתיחה וסיום\n- \"(Final Karaoke CDG).zip\": פורמט CDG+MP3 למערכות קריוקי ישנות/מסחריות\n- \"(Final Karaoke TXT).zip\": פורמט TXT+MP3 עבור Power Karaoke\n- stems/*.flac: ערוצי אודיו שונים של שירה ופלייבק בפורמט ללא אובדן נתונים\n- lyrics/*.txt: מילות השיר ממקורות שונים בפורמט טקסט רגיל",
"fixOffer": "ספרו לי אם משהו לא מושלם ואשמח לשנות / לתקן, או אם אתם צריכים את זה בפורמט אחר אני כנראה יכול להמיר את זה עבורכם!",
"feedbackRequest": "אם יש לכם רגע, אשמח מאוד לקבל את המשוב שלכם (לוקח 2 דקות):",
"signOff": "תודה שוב ושיהיה יום נהדר!\n-אנדרו",
"youtubeQueued": "ההעלאה שלכם ל-YouTube נמצאת בתור ותעובד אוטומטית. תקבלו אימייל המשך עם הקישור בקרוב."
},
"actionLyrics": {
"greeting": "שלום {name},",
"ready": "סרטון הקריוקי שלכם עבור \"{artist} - {title}\" מוכן לבדיקה!",
"instructions": "המערכת שלנו תמללה וסנכרנה את המילים, אך ייתכן שהן זקוקות לכמה תיקונים. תוכלו גם לבחור את רצועת הפלייבק המועדפת עליכם (עם או בלי קולות רקע).",
"reviewPrompt": "אנא בדקו את המילים שלכם ובחרו פלייבק:",
"duration": "זה בדרך כלל לוקח רק כמה דקות.",
"signOff": "תודה!\n-אנדרו"
},
"actionInstrumental": {
"greeting": "שלום {name},",
"almostDone": "סרטון הקריוקי שלכם עבור \"{artist} - {title}\" כמעט מוכן!",
"instructions": "הפרדנו את האודיו לגרסאות שונות. אנא בחרו באיזו רצועת פלייבק תרצו להשתמש עבור הווידאו הסופי.",
"selectPrompt": "בחרו את הפלייבק שלכם כאן:",
"signOff": "תודה!\n-אנדרו"
},
"youtubeComplete": {
"greeting": "שלום {name},",
"greatNews": "חדשות מעולות! סרטון הקריוקי שלכם עבור \"{artist} - {title}\" הועלה ל-YouTube:",
"delayNote": "העלאה זו עוכבה לזמן קצר בזמן שהמערכות שלנו עיבדו העלאות אחרות, אבל עכשיו הכל מוכן.",
"signOff": "תודה!\n-אנדרו"
}
}
}
}
+338
View File
@@ -0,0 +1,338 @@
{
"auth": {
"unknownService": "अज्ञात सर्विस: {service}",
"invalidCredentials": "निम्नलिखित सर्विसेज़ को फिर से ऑथराइज़ करने की ज़रूरत है: {services}",
"validCredentials": "सभी अनुरोधित क्रेडेंशियल्स मान्य हैं",
"youtubeAuthInstructions": "{verification_url} पर जाओ और कोड डालो: {user_code}",
"youtubeAuthStartFailed": "YouTube डिवाइस ऑथ शुरू करने में विफल: {error}",
"gdriveLinkInstructions": "{verification_url} पर जाओ और कोड डालो: {user_code}",
"gdriveAuthStartFailed": "Google Drive डिवाइस ऑथ शुरू करने में विफल: {error}",
"discordAlertNotConfigured": "Discord अलर्ट वेबहुक कॉन्फ़िगर नहीं किया गया है"
},
"jobs": {
"created": "जॉब सफलतापूर्वक बन गई। प्रोसेसिंग शुरू हो गई है।",
"authError": "ऑथेंटिकेशन त्रुटि: कोई यूज़र पहचान उपलब्ध नहीं है",
"noDefaultTheme": "कोई डिफ़ॉल्ट थीम कॉन्फ़िगर नहीं की गई है। कृपया सपोर्ट से संपर्क करो या theme_id निर्दिष्ट करो।",
"notFound": "जॉब नहीं मिली",
"noPermissionAccess": "तुम्हें इस जॉब को एक्सेस करने की अनुमति नहीं है",
"noPermissionEdit": "तुम्हें इस जॉब को एडिट करने की अनुमति नहीं है",
"noPermissionDelete": "तुम्हें इस जॉब को डिलीट करने की अनुमति नहीं है",
"noPermissionModify": "तुम्हें इस जॉब को मॉडिफाई करने की अनुमति नहीं है",
"notCompleted": "केवल पूरी हो चुकी जॉब्स को ही एडिट किया जा सकता है। वर्तमान स्थिति: {status}",
"alreadyBeingEdited": "यह जॉब पहले से ही एडिट की जा रही है (आउटपुट पहले ही डिलीट कर दिए गए थे)",
"cleanupFailed": "{services} के लिए क्लीनअप विफल रहा। जॉब मॉडिफाई नहीं हुई। कृपया फिर से कोशिश करो या सपोर्ट से संपर्क करो।",
"reopened": "ट्रैक को एडिटिंग के लिए फिर से खोल दिया गया है। पिछले आउटपुट हटा दिए गए हैं।",
"invalidDatetimeFormat": "अमान्य {field} फ़ॉर्मैट: {value}",
"listError": "जॉब्स की सूची बनाने में त्रुटि: {error}",
"deleteError": "जॉब {job_id} को डिलीट करने में त्रुटि: {error}",
"deletionPreview": "डिलीट करने के लिए &confirm=true जोड़ो",
"deletionRequiresFilters": "कम से कम एक फ़िल्टर (environment, client_id, status, created_before) आवश्यक है",
"bulkDeleteError": "जॉब्स को एक साथ डिलीट करने में त्रुटि: {error}",
"reviewNotReady": "जॉब रिव्यू के लिए तैयार नहीं है (वर्तमान स्थिति: {status})",
"correctionsUnavailable": "करेक्शन डेटा उपलब्ध नहीं है",
"audioUnavailable": "रिव्यू के लिए ऑडियो उपलब्ध नहीं है",
"reviewCannotStart": "रिव्यू शुरू नहीं किया जा सकता",
"jobNotInReviewState": "जॉब रिव्यू स्थिति में नहीं है (वर्तमान स्थिति: {status})",
"correctionsProcessing": "करेक्शन सेव हो गए। पूरा होने पर /complete-review को कॉल करो।",
"editLogSaveFailed": "जॉब {job_id} के लिए एडिट लॉग सेव करने में त्रुटि: {error}",
"stemsMissing": "जॉब में आवश्यक स्टेम्स (instrumental_clean और/या backing_vocals) गायब हैं",
"customInstrumentalFailed": "जॉब {job_id} के लिए कस्टम इंस्ट्रुमेंटल बनाने में त्रुटि: {error}",
"audioProcessingFailed": "ऑडियो फ़ाइल को प्रोसेस करने में विफल: {error}",
"durationMismatch": "अवधि बेमेल: अपलोड की गई फ़ाइल {upload_duration}s की है लेकिन मूल ऑडियो {original_duration}s का है। इंस्ट्रुमेंटल बिल्कुल {original_duration}s (±0.5s) का होना चाहिए।",
"reviewNotInState": "जॉब रिव्यू स्थिति में नहीं है (वर्तमान स्थिति: {status})",
"noLyricsDetected": "रिव्यू पूरा नहीं किया जा सकता: ऑडियो में कोई लिरिक्स नहीं मिले। ऐसा तब हो सकता है जब इनपुट ऑडियो में कोई वोकल्स न हों (जैसे कराओके ट्रैक या इंस्ट्रुमेंटल)। तुम वापस जाकर 'Replace All' का उपयोग करके मैन्युअल रूप से लिरिक्स पेस्ट कर सकते हो, या इस जॉब को रद्द करके वोकल्स वाली ऑडियो फ़ाइल के साथ फिर से कोशिश कर सकते हो।",
"reviewCompleteStartRendering": "रिव्यू पूरा हुआ। वीडियो रेंडरिंग शुरू हो गई है।",
"reviewCompleteError": "जॉब {job_id} का रिव्यू पूरा करने में त्रुटि: {error}",
"instrumentalSelectionRequired": "instrumental_selection आवश्यक है। यह 'clean' या 'with_backing' होना चाहिए।",
"invalidInstrumentalSelection": "अमान्य instrumental_selection। इनमें से एक होना चाहिए: {valid_selections}",
"instrumentalSelected": "इंस्ट्रुमेंटल चुना गया। वीडियो जनरेशन शुरू हो गया है।",
"instrumentalSelectionError": "जॉब {job_id} के लिए इंस्ट्रुमेंटल चुनने में त्रुटि: {error}",
"downloadUrlsError": "डाउनलोड URLs प्राप्त करने में त्रुटि: {error}"
},
"review": {
"jobNotFound": "जॉब नहीं मिली",
"reviewNotReady": "जॉब रिव्यू के लिए तैयार नहीं है (वर्तमान स्थिति: {status})",
"correctionsNotFound": "करेक्शन डेटा नहीं मिला। लिरिक्स प्रोसेसिंग शायद पूरी नहीं हुई है।",
"correctionsLoadFailed": "करेक्शन लोड करने में त्रुटि: {error}",
"audioNotFound": "ऑडियो फ़ाइल नहीं मिली",
"audioServeError": "ऑडियो सर्व करने में त्रुटि: {error}",
"instrumentalSelectionRequired": "instrumental_selection आवश्यक है। यह 'clean' या 'with_backing' होना चाहिए।",
"invalidInstrumentalSelection": "अमान्य instrumental_selection। इनमें से एक होना चाहिए: {valid_selections}",
"reviewCompletedError": "रिव्यू पूरा करने में त्रुटि: {error}",
"handlersUpdateNotImplemented": "हैंडलर अपडेट अभी लागू नहीं किए गए हैं",
"lyricsAddError": "लिरिक्स जोड़ने में विफल: {error}",
"lyricsAddInvalidRequest": "अमान्य लिरिक्स जोड़ने का अनुरोध: {error}",
"lyricsSearchError": "लिरिक्स खोजने में विफल: {error}",
"lyricsSearchInvalidRequest": "अमान्य लिरिक्स खोजने का अनुरोध: {error}",
"lyricsSearchNoResults": "किसी भी प्रोवाइडर से कोई मेल खाने वाले लिरिक्स नहीं मिले",
"previewVideoGenerationError": "प्रीव्यू वीडियो जनरेट करने में विफल: {error}",
"previewVideoNotFound": "प्रीव्यू वीडियो नहीं मिला",
"previewVideoStreamError": "प्रीव्यू वीडियो स्ट्रीम करने में त्रुटि: {error}",
"annotationSaveError": "एनोटेशन सेव करने में त्रुटि: {error}",
"waveformGenerationError": "वेवफ़ॉर्म डेटा जनरेट करने में त्रुटि: {error}",
"waveformNoAudio": "वेवफ़ॉर्म के लिए कोई ऑडियो उपलब्ध नहीं है",
"sessionSaveError": "करेक्शन डेटा आवश्यक है"
},
"audioSearch": {
"notEnabled": "इस टेनेंट के लिए ऑडियो सर्च सक्षम नहीं है",
"disabled": "ऑडियो सर्च उपलब्ध नहीं है",
"downloadError": "जॉब {job_id} के लिए डाउनलोड विफल: {error}",
"jobNotFound": "जॉब {job_id} नहीं मिली",
"noSearchResults": "कोई सर्च रिज़ल्ट उपलब्ध नहीं है",
"invalidSelectionIndex": "अमान्य सिलेक्शन इंडेक्स {selection_index}। मान्य रेंज: 0-{max}",
"selectionError": "जॉब {job_id} के लिए ऑडियो सिलेक्शन के दौरान त्रुटि: {error}",
"youtubeDownloadError": "YouTube डाउनलोड विफल: {error}",
"torrentDownloadError": "रिमोट flacfetch सर्विस के बिना {source} से डाउनलोड नहीं किया जा सकता। FLACFETCH_API_URL कॉन्फ़िगर करो।",
"remoteDownloadNoSearchId": "{source} डाउनलोड के लिए कोई source_id या remote_search_id उपलब्ध नहीं है",
"remoteDownloadCompleteNoPath": "रिमोट डाउनलोड पूरा हुआ लेकिन कोई फ़ाइल पाथ नहीं मिला",
"spotifyDownloadError": "रिमोट flacfetch सर्विस के बिना Spotify से डाउनलोड नहीं किया जा सकता। FLACFETCH_API_URL कॉन्फ़िगर करो।",
"genericDownloadError": "अज्ञात सोर्स प्रकार: {source}, जेनेरिक डाउनलोड का प्रयास किया जा रहा है",
"jobNotFoundDuringDownload": "बैकग्राउंड डाउनलोड के दौरान जॉब {job_id} नहीं मिली",
"selectAudioError": "जॉब {job_id} के लिए ऑडियो चुनने में त्रुटि: {error}",
"searchAudioError": "ऑडियो खोजने में त्रुटि: {error}",
"searchCreatedSuccessfully": "जॉब बन गई। ऑडियो खोजा जा रहा है...",
"autoDownloadStarted": "सबसे अच्छा रिज़ल्ट अपने आप चुन लिया गया। डाउनलोड शुरू हो रहा है..."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
"magicLinkSent": "अगर यह ईमेल रजिस्टर्ड है, तो तुम्हें जल्द ही एक साइन-इन लिंक मिल जाएगा।",
"emailServiceNotConfigured": "ईमेल सर्विस उपलब्ध नहीं है। कृपया सपोर्ट से संपर्क करो।",
"emailDomainNotAllowed": "इस टेनेंट के लिए ईमेल डोमेन की अनुमति नहीं है",
"invalidToken": "अमान्य टोकन",
"verifyError": "वेरिफिकेशन विफल: {message}",
"magicLinkSuccess": "सफलतापूर्वक साइन इन हो गया",
"logoutSuccess": "सफलतापूर्वक लॉग आउट हो गया",
"userNotFound": "यूज़र नहीं मिला",
"creditPackagesError": "क्रेडिट पैकेज लोड करने में त्रुटि: {error}",
"stripeSendError": "Stripe चेकआउट लिंक भेजने में त्रुटि: {error}",
"stripeWebhookProcessingError": "Stripe वेबहुक प्रोसेस करने में त्रुटि: {error}",
"feedbackSaveError": "फ़ीडबैक सेव करने में त्रुटि: {error}",
"feedbackNotEligible": "यूज़र फ़ीडबैक के लिए योग्य नहीं है"
},
"fileUpload": {
"invalidTheme": "थीम नहीं मिली: {theme_id}। उपलब्ध थीम्स की सूची के लिए GET /api/themes का उपयोग करो।",
"uploadSuccess": "फ़ाइल सफलतापूर्वक अपलोड हो गई। प्रोसेसिंग शुरू हो गई है।",
"uploadError": "फ़ाइल अपलोड करने में त्रुटि: {error}",
"urlDownloadError": "URL से डाउनलोड करने में त्रुटि: {error}",
"invalidContentType": "अमान्य कंटेंट प्रकार: {content_type}",
"fileSizeError": "फ़ाइल बहुत बड़ी है: {size}। अधिकतम: {max_size}",
"invalidFileType": "अमान्य फ़ाइल प्रकार: {file_type}",
"multipleAudioFilesNotAllowed": "केवल एक ऑडियो फ़ाइल अपलोड की जा सकती है",
"noAudioFileProvided": "कोई ऑडियो फ़ाइल नहीं दी गई",
"urlCreationSuccess": "जॉब बन गई। अपलोड URLs जनरेट हो गए।",
"urlCreationError": "अपलोड URLs के साथ जॉब बनाने में त्रुटि: {error}",
"uploadsCompleteSuccess": "अपलोड पूरे हुए। प्रोसेसिंग शुरू हो गई है।",
"uploadsCompleteError": "अपलोड पूरे करने में त्रुटि: {error}",
"noUploadedFiles": "कोई अपलोड की गई फ़ाइल निर्दिष्ट नहीं है",
"styleUploadUrlsSuccess": "स्टाइल अपलोड URLs जनरेट हो गए।",
"styleUploadsCompleteSuccess": "स्टाइल फ़ाइलें अपडेट हो गईं। प्रोसेसिंग फिर से शुरू हो गई है।",
"styleUploadsCompleteError": "स्टाइल अपलोड पूरे करने में त्रुटि: {error}"
},
"catalog": {
"rateLimitExceeded": "रेट लिमिट पार हो गई। प्रति मिनट अधिकतम {max_requests} कैटलॉग अनुरोध।",
"catalogSearchError": "कैटलॉग खोजने में त्रुटि: {error}",
"communityCheckError": "कम्युनिटी वर्ज़न चेक करने में त्रुटि: {error}"
},
"themes": {
"themesLoadError": "थीम्स लोड करने में विफल",
"themeNotFound": "थीम नहीं मिली: {theme_id}",
"themeLoadError": "थीम लोड करने में विफल",
"previewNotAvailable": "थीम के लिए कोई प्रीव्यू उपलब्ध नहीं है: {theme_id}",
"previewLoadError": "थीम प्रीव्यू लोड करने में विफल",
"youtubeDescriptionNotFound": "थीम नहीं मिली: {theme_id}",
"youtubeDescriptionLoadError": "YouTube डिस्क्रिप्शन लोड करने में विफल"
},
"tenant": {
"assetNotFound": "एसेट नहीं मिला"
},
"push": {
"disabled": "पुश नोटिफ़िकेशन सक्षम नहीं हैं",
"userEmailNotAvailable": "यूज़र ईमेल उपलब्ध नहीं है",
"missingEncryptionKeys": "आवश्यक कुंजियाँ (p256dh, auth) गायब हैं",
"subscriptionSaveFailed": "सब्सक्रिप्शन सेव करने में विफल",
"subscriptionRegistered": "पुश सब्सक्रिप्शन सफलतापूर्वक रजिस्टर हो गया",
"subscriptionNotFound": "सब्सक्रिप्शन हटा दिया गया (या नहीं मिला)",
"subscriptionRemoved": "पुश सब्सक्रिप्शन सफलतापूर्वक हटा दिया गया",
"testNotificationSent": "{sent_count} डिवाइस(ों) पर टेस्ट नोटिफ़िकेशन भेजा गया"
},
"pushNotifications": {
"reviewLyricsTitle": "लिरिक्स रिव्यू करो",
"reviewLyricsBody": "{artist} के \"{title}\" के लिए लिरिक्स रिव्यू की ज़रूरत है",
"selectInstrumentalTitle": "इंस्ट्रुमेंटल चुनो",
"selectInstrumentalBody": "{artist} के \"{title}\" के लिए इंस्ट्रुमेंटल चुनने की ज़रूरत है",
"videoReadyTitle": "वीडियो तैयार है!",
"videoReadyBody": "{artist} का तुम्हारा कराओके वीडियो \"{title}\" डाउनलोड के लिए तैयार है"
},
"admin": {
"invalidDomainFormat": "अमान्य डोमेन फ़ॉर्मैट",
"domainAddedToBl": "डोमेन '{domain}' को डिस्पोज़ेबल डोमेन ब्लॉकलिस्ट में जोड़ दिया गया",
"domainNotFoundInBl": "डोमेन ब्लॉकलिस्ट में नहीं मिला",
"domainRemovedFromBl": "डोमेन '{domain}' को डिस्पोज़ेबल डोमेन ब्लॉकलिस्ट से हटा दिया गया",
"domainAddedToAllowlist": "डोमेन '{domain}' को अलाउलिस्ट में जोड़ दिया गया",
"domainNotFoundInAllowlist": "डोमेन अलाउलिस्ट में नहीं मिला",
"domainRemovedFromAllowlist": "डोमेन '{domain}' को अलाउलिस्ट से हटा दिया गया",
"syncComplete": "{external_count} बाहरी डोमेन सिंक किए गए ({added} जोड़े गए, {removed} हटाए गए)",
"invalidEmailFormat": "अमान्य ईमेल फ़ॉर्मैट",
"emailAddedToBl": "ईमेल '{email}' को ब्लॉक किए गए ईमेल की सूची में जोड़ दिया गया",
"emailNotFoundInBl": "ईमेल ब्लॉकलिस्ट में नहीं मिला",
"emailRemovedFromBl": "ईमेल '{email}' को ब्लॉक किए गए ईमेल की सूची से हटा दिया गया",
"invalidIPAddress": "अमान्य IP एड्रेस",
"ipAddedToBl": "IP '{ip_address}' को ब्लॉक किए गए IPs की सूची में जोड़ दिया गया",
"ipNotFoundInBl": "IP ब्लॉकलिस्ट में नहीं मिला",
"ipRemovedFromBl": "IP '{ip_address}' को ब्लॉक किए गए IPs की सूची से हटा दिया गया",
"youtubeUploadNotFound": "जॉब {job_id} के लिए अपलोड नहीं मिला या फिर से कोशिश करने की स्थिति में नहीं है",
"youtubeUploadQueuedForRetry": "जॉब {job_id} के लिए YouTube अपलोड को फिर से कोशिश करने के लिए कतार में लगा दिया गया है",
"youtubeQueueProcessingStarted": "YouTube कतार की प्रोसेसिंग बैकग्राउंड में शुरू हो गई है"
},
"rateLimits": {
"configNotFound": "रेट लिमिट कॉन्फ़िग नहीं मिला: {config_id}",
"configUpdateError": "रेट लिमिट कॉन्फ़िग अपडेट करने में त्रुटि: {error}"
},
"errors": {
"insufficientCredits": "इस ऑपरेशन के लिए पर्याप्त क्रेडिट नहीं हैं",
"insufficientCreditsBuyUrl": "/#pricing"
},
"emails": {
"magicLink": {
"subject": "{brand_name} में साइन इन करो",
"greeting": "नमस्ते,",
"signInPrompt": "{brand_name} में साइन इन करने के लिए नीचे दिए गए बटन पर क्लिक करो:",
"signInButton": "साइन इन",
"expiryWarning": "यह लिंक 15 मिनट में एक्सपायर हो जाएगा और इसका उपयोग केवल एक बार किया जा सकता है।",
"fallbackLink": "अगर बटन काम नहीं करता है, तो इस लिंक को कॉपी करके अपने ब्राउज़र में पेस्ट करो:",
"ignoreNote": "अगर तुमने इस ईमेल का अनुरोध नहीं किया है, तो तुम इसे सुरक्षित रूप से अनदेखा कर सकते हो।"
},
"welcome": {
"subject": "Nomad Karaoke में तुम्हारा स्वागत है!",
"welcomeGreeting": "Nomad Karaoke में तुम्हारा स्वागत है!",
"turnAnySong": "किसी भी गाने को मिनटों में एक पेशेवर कराओके वीडियो में बदलो।",
"freeCreditsLabel": "मुफ़्त क्रेडिट",
"freeCreditsNote": "प्रत्येक क्रेडिट से एक पेशेवर कराओके वीडियो बनता है",
"howItWorks": "यह ऐसे काम करता है:",
"step1Title": "1. कोई गाना खोजो",
"step1Desc": "आर्टिस्ट और टाइटल डालो, और हम हाई-क्वालिटी ऑडियो ढूंढेंगे।",
"step2Title": "2. हमारा सिस्टम अपना जादू चलाता है",
"step2Desc": "हम वोकल्स को अलग करते हैं, लिरिक्स को ट्रांसक्राइब करते हैं, और सब कुछ पूरी तरह से सिंक करते हैं।",
"step3Title": "3. रिव्यू और कस्टमाइज़ करो",
"step3Desc": "ज़रूरत पड़ने पर लिरिक्स को ठीक करो, अपना इंस्ट्रुमेंटल चुनो।",
"step4Title": "4. अपना वीडियो प्राप्त करो",
"step4Desc": "अपना 4K कराओके वीडियो डाउनलोड करो या सीधे YouTube पर अपलोड करो।",
"feedbackBonus": "2 वीडियो पूरे करो और अपना फ़ीडबैक शेयर करके 2 और मुफ़्त क्रेडिट कमाओ!",
"getStartedButton": "शुरू करो"
},
"creditsAdded": {
"subject": "तुम्हारे Nomad Karaoke अकाउंट में {credits} क्रेडिट जोड़ दिए गए हैं",
"greatNews": "बढ़िया खबर!",
"creditsAddedMessage": "तुम्हारे अकाउंट में {credits} क्रेडिट जोड़ दिए गए हैं।",
"yourBalance": "तुम्हारा बैलेंस:",
"credits": "क्रेडिट",
"eachCreditLets": "प्रत्येक क्रेडिट तुम्हें इसके साथ एक पेशेवर कराओके वीडियो बनाने देता है:",
"featureVocalSeparation": "AI-पावर्ड वोकल/इंस्ट्रुमेंटल सेपरेशन",
"featureLyrics": "वर्ड-लेवल टाइमिंग के साथ सिंक्रोनाइज़्ड लिरिक्स",
"feature4k": "4K वीडियो आउटपुट",
"featureYoutube": "YouTube अपलोड",
"createButton": "अभी कराओके बनाओ"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (तुम्हारा कराओके वीडियो तैयार है!)",
"subject": "{artist} - {title} (तुम्हारा कराओके वीडियो तैयार है!)",
"subjectFallback": "तुम्हारा कराओके वीडियो तैयार है!"
},
"youtubeUpload": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (YouTube अपलोड तैयार है!)",
"subject": "{artist} - {title} (YouTube अपलोड तैयार है!)",
"subjectFallback": "तुम्हारा YouTube अपलोड तैयार है!"
},
"actionReminder": {
"lyricsSubject": "कार्रवाई की ज़रूरत है: {artist} - {title} के लिए लिरिक्स रिव्यू करो",
"lyricsSubjectFallback": "कार्रवाई की ज़रूरत है: लिरिक्स रिव्यू करो",
"instrumentalSubject": "कार्रवाई की ज़रूरत है: {artist} - {title} के लिए इंस्ट्रुमेंटल चुनो",
"instrumentalSubjectFallback": "कार्रवाई की ज़रूरत है: इंस्ट्रुमेंटल चुनो",
"audioEditSubject": "{artist} - {title} के लिए कार्रवाई की ज़रूरत है",
"audioEditSubjectFallback": "कार्रवाई की ज़रूरत है",
"alertHeading": "तुम्हारे कराओके वीडियो के लिए तुम्हारे इनपुट की ज़रूरत है!"
},
"reviewReminder": {
"subject": "रिमाइंडर: तुम्हारा कराओके वीडियो रिव्यू का इंतज़ार कर रहा है — {artist} - {title}",
"subjectFallback": "रिमाइंडर: तुम्हारा कराओके वीडियो रिव्यू का इंतज़ार कर रहा है",
"alertHeading": "तुम्हारा कराओके वीडियो तुम्हारा इंतज़ार कर रहा है!",
"reminderIntro": "बस एक याद दिलाने के लिए कि तुम्हारा कराओके वीडियो{song_name} रिव्यू के लिए तैयार है।",
"reviewButton": "अपना वीडियो रिव्यू करो",
"reviewInstructions": "रिव्यू के दौरान, तुम चेक कर सकते हो कि लिरिक्स सही हैं और अपना पसंदीदा इंस्ट्रुमेंटल ट्रैक चुन सकते हो। इसमें आमतौर पर बस कुछ ही मिनट लगते हैं!",
"helpOffer": "अगर तुम्हें रिव्यू प्रोसेस में कोई परेशानी हो रही है, तो बस इस ईमेल का जवाब दो और मुझे तुम्हारी मदद करने में खुशी होगी।",
"expiryWarning": "कृपया ध्यान दें: अगर अगले 24 घंटों के भीतर रिव्यू पूरा नहीं होता है, तो जॉब अपने आप एक्सपायर हो जाएगी और तुम्हारा क्रेडिट रिफ़ंड कर दिया जाएगा।"
},
"reviewExpired": {
"subject": "तुम्हारा कराओके वीडियो एक्सपायर हो गया है — {artist} - {title}",
"subjectFallback": "तुम्हारा कराओके वीडियो एक्सपायर हो गया है",
"cancelNotice": "तुम्हारा कराओके वीडियो{song_name} अपने आप रद्द कर दिया गया है क्योंकि 48 घंटों के भीतर रिव्यू पूरा नहीं हुआ था।",
"refundNotice": "चिंता मत करो — तुम्हारा क्रेडिट रिफ़ंड कर दिया गया है! तुम्हारा वर्तमान बैलेंस {credits_balance} {credits_word} है।",
"creditSingular": "क्रेडिट",
"creditPlural": "क्रेडिट",
"createNewPrompt": "तुम अपने क्रेडिट का उपयोग करके कभी भी एक नया कराओके वीडियो बना सकते हो:",
"createButton": "नया वीडियो बनाओ",
"helpOffer": "अगर तुम्हें रिव्यू प्रोसेस में कोई परेशानी हुई या मदद की ज़रूरत है, तो बस इस ईमेल का जवाब दो — मुझे मदद करने में खुशी होगी!"
},
"creditDenied": {
"subject": "तुम्हारे Nomad Karaoke मुफ़्त क्रेडिट के बारे में",
"greeting": "नमस्ते,",
"thankYou": "Nomad Karaoke के लिए साइन अप करने के लिए धन्यवाद!",
"deniedMessage": "दुर्भाग्य से, हम इस बार तुम्हारा मुफ़्त {credit_type} नहीं दे पाए। हमारे सिस्टम ने ऐसे पैटर्न का पता लगाया है जो बताते हैं कि यह शायद हमारे साथ तुम्हारा पहला अकाउंट नहीं है, और प्रत्येक कराओके जनरेशन जॉब में हमें क्लाउड कंप्यूटिंग और API फ़ीस में असली पैसे खर्च करने पड़ते हैं।",
"mistakeNote": "अगर यह कोई गलती है तो हम पूरी तरह समझते हैं! अगर तुम एक वास्तविक नए यूज़र हो, तो कृपया बस इस ईमेल का जवाब दो और एंड्रयू (संस्थापक) को बताओ। उसने यह सर्विस बनाई है और इसे आज़माने के लिए तुम्हें कुछ मुफ़्त क्रेडिट देने में उसे खुशी होगी — वह बस यह चाहता है कि बदले में तुम अनुभव पर अपना ईमानदार फ़ीडबैक दो।",
"buyPrompt": "अगर तुम तुरंत शुरू करना चाहते हो, तो तुम क्रेडिट खरीद भी सकते हो:",
"buyButton": "क्रेडिट खरीदो",
"costNote": "हम लागत कम रखते हैं ताकि हम सर्विस को किफ़ायती रूप से पेश कर सकें, जिसका मतलब है कि हमें मुफ़्त क्रेडिट के दुरुपयोग के बारे में सावधान रहने की ज़रूरत है। समझने के लिए धन्यवाद!",
"welcomeCredits": "वेलकम क्रेडिट",
"feedbackCredits": "फ़ीडबैक बोनस क्रेडिट"
},
"madeForYouConfirmation": {
"subject": "ऑर्डर कन्फ़र्म हुआ: {artist} - {title} | Nomad Karaoke",
"thankYou": "तुम्हारे ऑर्डर के लिए धन्यवाद!",
"orderDetails": "ऑर्डर का विवरण",
"orderId": "ऑर्डर ID:",
"artist": "आर्टिस्ट:",
"title": "टाइटल:",
"yourNotes": "तुम्हारे नोट्स:",
"deliveryTime": "हमारी टीम {hours} घंटों के भीतर तुम्हारा कस्टम कराओके वीडियो बनाएगी।",
"deliveryNotice": "जैसे ही तुम्हारा वीडियो तैयार होगा, तुम्हें डाउनलोड लिंक के साथ एक ईमेल मिलेगा।",
"noAction": "कोई कार्रवाई करने की ज़रूरत नहीं है — आराम से बैठो और हम सब कुछ संभाल लेंगे!"
},
"shared": {
"footerHelp": "अगर कुछ भी सही नहीं है, तो बस इस ईमेल का जवाब दो और मैं इसे ठीक कर दूंगा!"
},
"templates": {
"jobCompletion": {
"greeting": "नमस्ते {name},",
"thanks": "तुम्हारे ऑर्डर के लिए धन्यवाद!",
"youtubeLink": "यहाँ YouTube पर पब्लिश किए गए कराओके वीडियो का लिंक है:",
"dropboxIntro": "यहाँ सभी तैयार फ़ाइलों और सोर्स फ़ाइलों के साथ Dropbox फ़ोल्डर है, जिसमें शामिल हैं:",
"fileList": "- \"(Final Karaoke Lossless).mkv\": 4K H264 में लॉसलेस FLAC ऑडियो के साथ कंबाइंड कराओके वीडियो\n- \"(Final Karaoke).mp4\": 4K H264/AAC में टाइटल/एंड स्क्रीन के साथ कंबाइंड कराओके वीडियो\n- \"(Final Karaoke 720p).mp4\": 720p H264/AAC में कंबाइंड कराओके वीडियो (पुराने सिस्टम के लिए छोटी फ़ाइल)\n- \"(With Vocals).mp4\": 4K H264/AAC में ओरिजिनल वोकल्स के साथ सिंग अलॉन्ग वीडियो\n- \"(Karaoke).mov\": MidiCo से कराओके वीडियो आउटपुट (कोई टाइटल/एंड स्क्रीन नहीं)\n- \"(Title).mov\"/\"(End).mov\": टाइटल कार्ड और एंड स्क्रीन वीडियो\n- \"(Final Karaoke CDG).zip\": पुराने/कमर्शियल कराओके सिस्टम के लिए CDG+MP3 फ़ॉर्मैट\n- \"(Final Karaoke TXT).zip\": Power Karaoke के लिए TXT+MP3 फ़ॉर्मैट\n- stems/*.flac: लॉसलेस फ़ॉर्मैट में विभिन्न अलग किए गए इंस्ट्रुमेंटल और वोकल ऑडियो स्टेम्स\n- lyrics/*.txt प्लेन टेक्स्ट फ़ॉर्मैट में विभिन्न स्रोतों से गाने के लिरिक्स",
"fixOffer": "मुझे बताओ अगर कुछ भी सही नहीं है और मैं खुशी-खुशी उसे बदल / ठीक कर दूंगा, या अगर तुम्हें यह किसी अन्य फ़ॉर्मैट में चाहिए तो मैं शायद इसे तुम्हारे लिए कन्वर्ट कर सकता हूँ!",
"feedbackRequest": "अगर तुम्हारे पास थोड़ा समय है, तो मैं तुम्हारे फ़ीडबैक की बहुत सराहना करूँगा (2 मिनट लगते हैं):",
"signOff": "एक बार फिर धन्यवाद और तुम्हारा दिन शुभ हो!\n-एंड्रयू",
"youtubeQueued": "तुम्हारा YouTube अपलोड कतार में है और अपने आप प्रोसेस हो जाएगा। तुम्हें जल्द ही लिंक के साथ एक फ़ॉलो-अप ईमेल मिलेगा।"
},
"actionLyrics": {
"greeting": "नमस्ते {name},",
"ready": "\"{artist} - {title}\" के लिए तुम्हारा कराओके वीडियो रिव्यू के लिए तैयार है!",
"instructions": "हमारे सिस्टम ने लिरिक्स को ट्रांसक्राइब और सिंक्रोनाइज़ कर दिया है, लेकिन उनमें कुछ सुधार की ज़रूरत हो सकती है। तुम अपना पसंदीदा इंस्ट्रुमेंटल ट्रैक (बैकिंग वोकल्स के साथ या बिना) भी चुन सकोगे।",
"reviewPrompt": "कृपया अपने लिरिक्स रिव्यू करो और एक इंस्ट्रुमेंटल चुनो:",
"duration": "इसमें आमतौर पर बस कुछ ही मिनट लगते हैं।",
"signOff": "धन्यवाद!\n-एंड्रयू"
},
"actionInstrumental": {
"greeting": "नमस्ते {name},",
"almostDone": "\"{artist} - {title}\" के लिए तुम्हारा कराओके वीडियो लगभग पूरा हो गया है!",
"instructions": "हमने ऑडियो को अलग-अलग वर्ज़न में अलग कर दिया है। कृपया चुनो कि तुम फ़ाइनल वीडियो के लिए कौन सा इंस्ट्रुमेंटल ट्रैक इस्तेमाल करना चाहोगे।",
"selectPrompt": "अपना इंस्ट्रुमेंटल यहाँ चुनो:",
"signOff": "धन्यवाद!\n-एंड्रयू"
},
"youtubeComplete": {
"greeting": "नमस्ते {name},",
"greatNews": "बढ़िया खबर! \"{artist} - {title}\" के लिए तुम्हारा कराओके वीडियो YouTube पर अपलोड कर दिया गया है:",
"delayNote": "इस अपलोड में थोड़ी देरी हुई क्योंकि हमारे सिस्टम अन्य अपलोड प्रोसेस कर रहे थे, लेकिन अब सब कुछ सेट है।",
"signOff": "धन्यवाद!\n-एंड्रयू"
}
}
}
}
+338
View File
@@ -0,0 +1,338 @@
{
"auth": {
"unknownService": "Nepoznata usluga: {service}",
"invalidCredentials": "Sljedeće usluge trebaju ponovnu autorizaciju: {services}",
"validCredentials": "Sve zatražene vjerodajnice su važeće",
"youtubeAuthInstructions": "Posjeti {verification_url} i unesi kod: {user_code}",
"youtubeAuthStartFailed": "Nije uspjelo pokretanje autorizacije YouTube uređaja: {error}",
"gdriveLinkInstructions": "Posjeti {verification_url} i unesi kod: {user_code}",
"gdriveAuthStartFailed": "Nije uspjelo pokretanje autorizacije Google Drive uređaja: {error}",
"discordAlertNotConfigured": "Discord webhook za upozorenja nije konfiguriran"
},
"jobs": {
"created": "Zadatak je uspješno kreiran. Obrada je započela.",
"authError": "Pogreška autentifikacije: identitet korisnika nije dostupan",
"noDefaultTheme": "Zadana tema nije konfigurirana. Javi se podršci ili navedi theme_id.",
"notFound": "Zadatak nije pronađen",
"noPermissionAccess": "Nemaš dopuštenje za pristup ovom zadatku",
"noPermissionEdit": "Nemaš dopuštenje za uređivanje ovog zadatka",
"noPermissionDelete": "Nemaš dopuštenje za brisanje ovog zadatka",
"noPermissionModify": "Nemaš dopuštenje za izmjenu ovog zadatka",
"notCompleted": "Samo završeni zadaci mogu se uređivati. Trenutni status: {status}",
"alreadyBeingEdited": "Ovaj zadatak se već uređuje (izlazi su već izbrisani)",
"cleanupFailed": "Čišćenje nije uspjelo za {services}. Zadatak nije izmijenjen. Pokušaj ponovno ili se javi podršci.",
"reopened": "Zapis je ponovno otvoren za uređivanje. Prethodni izlazi su uklonjeni.",
"invalidDatetimeFormat": "Nevažeći format za {field}: {value}",
"listError": "Pogreška pri dohvaćanju popisa zadataka: {error}",
"deleteError": "Pogreška pri brisanju zadatka {job_id}: {error}",
"deletionPreview": "Dodaj &confirm=true za izvršavanje brisanja",
"deletionRequiresFilters": "Potreban je barem jedan filter (environment, client_id, status, created_before)",
"bulkDeleteError": "Pogreška pri masovnom brisanju zadataka: {error}",
"reviewNotReady": "Zadatak nije spreman za pregled (trenutni status: {status})",
"correctionsUnavailable": "Podaci o ispravcima nisu dostupni",
"audioUnavailable": "Audio nije dostupan za pregled",
"reviewCannotStart": "Nije moguće započeti pregled",
"jobNotInReviewState": "Zadatak nije u stanju za pregled (trenutni status: {status})",
"correctionsProcessing": "Ispravci su spremljeni. Pozovi /complete-review kada završiš.",
"editLogSaveFailed": "Pogreška pri spremanju dnevnika uređivanja za zadatak {job_id}: {error}",
"stemsMissing": "Zadatku nedostaju potrebni stemovi (instrumental_clean i/ili backing_vocals)",
"customInstrumentalFailed": "Pogreška pri stvaranju prilagođenog instrumentala za zadatak {job_id}: {error}",
"audioProcessingFailed": "Obrada audio datoteke nije uspjela: {error}",
"durationMismatch": "Nepodudaranje trajanja: prenesena datoteka traje {upload_duration}s, ali originalni audio traje {original_duration}s. Instrumental mora trajati točno {original_duration}s (±0.5s).",
"reviewNotInState": "Zadatak nije u stanju za pregled (trenutni status: {status})",
"noLyricsDetected": "Nije moguće dovršiti pregled: u zvuku nije otkriven tekst. To se može dogoditi kada ulazni zvuk nema vokale (npr. karaoke zapis ili instrumental). Možeš se vratiti i ručno zalijepiti tekst koristeći 'Replace All', ili otkazati ovaj zadatak i pokušati ponovno s audio datotekom koja sadrži vokale.",
"reviewCompleteStartRendering": "Pregled je završen. Započelo je renderiranje videa.",
"reviewCompleteError": "Pogreška pri dovršavanju pregleda za zadatak {job_id}: {error}",
"instrumentalSelectionRequired": "instrumental_selection je obavezan. Mora biti 'clean' ili 'with_backing'.",
"invalidInstrumentalSelection": "Nevažeći instrumental_selection. Mora biti jedno od: {valid_selections}",
"instrumentalSelected": "Instrumental je odabran. Generiranje videa je započelo.",
"instrumentalSelectionError": "Pogreška pri odabiru instrumentala za zadatak {job_id}: {error}",
"downloadUrlsError": "Pogreška pri dohvaćanju URL-ova za preuzimanje: {error}"
},
"review": {
"jobNotFound": "Zadatak nije pronađen",
"reviewNotReady": "Zadatak nije spreman za pregled (trenutni status: {status})",
"correctionsNotFound": "Podaci o ispravcima nisu pronađeni. Obrada teksta možda nije dovršena.",
"correctionsLoadFailed": "Pogreška pri učitavanju ispravaka: {error}",
"audioNotFound": "Audio datoteka nije pronađena",
"audioServeError": "Pogreška pri posluživanju zvuka: {error}",
"instrumentalSelectionRequired": "instrumental_selection je obavezan. Mora biti 'clean' ili 'with_backing'.",
"invalidInstrumentalSelection": "Nevažeći instrumental_selection. Mora biti jedno od: {valid_selections}",
"reviewCompletedError": "Pogreška pri dovršavanju pregleda: {error}",
"handlersUpdateNotImplemented": "Ažuriranja handlera još nisu implementirana",
"lyricsAddError": "Dodavanje teksta nije uspjelo: {error}",
"lyricsAddInvalidRequest": "Nevažeći zahtjev za dodavanje teksta: {error}",
"lyricsSearchError": "Pretraživanje teksta nije uspjelo: {error}",
"lyricsSearchInvalidRequest": "Nevažeći zahtjev za pretraživanje teksta: {error}",
"lyricsSearchNoResults": "Nisu pronađeni odgovarajući tekstovi ni kod jednog pružatelja",
"previewVideoGenerationError": "Generiranje pregleda videa nije uspjelo: {error}",
"previewVideoNotFound": "Pregled videa nije pronađen",
"previewVideoStreamError": "Pogreška pri streamanju pregleda videa: {error}",
"annotationSaveError": "Pogreška pri spremanju bilješki: {error}",
"waveformGenerationError": "Pogreška pri generiranju podataka valnog oblika: {error}",
"waveformNoAudio": "Nema dostupnog zvuka za valni oblik",
"sessionSaveError": "Podaci o ispravcima su obavezni"
},
"audioSearch": {
"notEnabled": "Pretraživanje zvuka nije omogućeno za ovog zakupca",
"disabled": "Pretraživanje zvuka nije dostupno",
"downloadError": "Preuzimanje nije uspjelo za zadatak {job_id}: {error}",
"jobNotFound": "Zadatak {job_id} nije pronađen",
"noSearchResults": "Nema dostupnih rezultata pretraživanja",
"invalidSelectionIndex": "Nevažeći indeks odabira {selection_index}. Važeći raspon: 0-{max}",
"selectionError": "Pogreška tijekom odabira zvuka za zadatak {job_id}: {error}",
"youtubeDownloadError": "Preuzimanje s YouTubea nije uspjelo: {error}",
"torrentDownloadError": "Nije moguće preuzeti s {source} bez udaljene flacfetch usluge. Konfiguriraj FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Nema dostupnog source_id ili remote_search_id za preuzimanje s {source}",
"remoteDownloadCompleteNoPath": "Udaljeno preuzimanje je završeno, ali putanja datoteke nije vraćena",
"spotifyDownloadError": "Nije moguće preuzeti sa Spotifyja bez udaljene flacfetch usluge. Konfiguriraj FLACFETCH_API_URL.",
"genericDownloadError": "Nepoznata vrsta izvora: {source}, pokušavam generičko preuzimanje",
"jobNotFoundDuringDownload": "Zadatak {job_id} nije pronađen tijekom preuzimanja u pozadini",
"selectAudioError": "Pogreška pri odabiru zvuka za zadatak {job_id}: {error}",
"searchAudioError": "Pogreška pri pretraživanju zvuka: {error}",
"searchCreatedSuccessfully": "Zadatak je kreiran. Pretražujem zvuk...",
"autoDownloadStarted": "Najbolji rezultat je automatski odabran. Preuzimanje započinje..."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
"magicLinkSent": "Ako je ova e-mail adresa registrirana, uskoro ćeš dobiti poveznicu za prijavu.",
"emailServiceNotConfigured": "Usluga e-pošte nije dostupna. Javi se podršci.",
"emailDomainNotAllowed": "Domena e-pošte nije dopuštena za ovog zakupca",
"invalidToken": "Nevažeći token",
"verifyError": "Provjera nije uspjela: {message}",
"magicLinkSuccess": "Uspješna prijava",
"logoutSuccess": "Uspješna odjava",
"userNotFound": "Korisnik nije pronađen",
"creditPackagesError": "Pogreška pri učitavanju paketa kredita: {error}",
"stripeSendError": "Pogreška pri slanju Stripe poveznice za naplatu: {error}",
"stripeWebhookProcessingError": "Pogreška pri obradi Stripe webhooka: {error}",
"feedbackSaveError": "Pogreška pri spremanju povratnih informacija: {error}",
"feedbackNotEligible": "Korisnik ne ispunjava uvjete za povratne informacije"
},
"fileUpload": {
"invalidTheme": "Tema nije pronađena: {theme_id}. Koristi GET /api/themes za popis dostupnih tema.",
"uploadSuccess": "Datoteka je uspješno prenesena. Obrada je započela.",
"uploadError": "Pogreška pri prijenosu datoteke: {error}",
"urlDownloadError": "Pogreška pri preuzimanju s URL-a: {error}",
"invalidContentType": "Nevažeća vrsta sadržaja: {content_type}",
"fileSizeError": "Datoteka je prevelika: {size}. Maksimalno: {max_size}",
"invalidFileType": "Nevažeća vrsta datoteke: {file_type}",
"multipleAudioFilesNotAllowed": "Samo jedna audio datoteka može biti prenesena",
"noAudioFileProvided": "Nije navedena audio datoteka",
"urlCreationSuccess": "Zadatak je kreiran. URL-ovi za prijenos su generirani.",
"urlCreationError": "Pogreška pri kreiranju zadatka s URL-ovima za prijenos: {error}",
"uploadsCompleteSuccess": "Prijenosi su završeni. Obrada je započela.",
"uploadsCompleteError": "Pogreška pri dovršavanju prijenosa: {error}",
"noUploadedFiles": "Nisu navedene prenesene datoteke",
"styleUploadUrlsSuccess": "URL-ovi za prijenos stila su generirani.",
"styleUploadsCompleteSuccess": "Datoteke stila su ažurirane. Obrada je ponovno pokrenuta.",
"styleUploadsCompleteError": "Pogreška pri dovršavanju prijenosa stila: {error}"
},
"catalog": {
"rateLimitExceeded": "Premašeno ograničenje učestalosti. Maksimalno {max_requests} zahtjeva za katalog u minuti.",
"catalogSearchError": "Pogreška pri pretraživanju kataloga: {error}",
"communityCheckError": "Pogreška pri provjeri verzija zajednice: {error}"
},
"themes": {
"themesLoadError": "Učitavanje tema nije uspjelo",
"themeNotFound": "Tema nije pronađena: {theme_id}",
"themeLoadError": "Učitavanje teme nije uspjelo",
"previewNotAvailable": "Pregled nije dostupan za temu: {theme_id}",
"previewLoadError": "Učitavanje pregleda teme nije uspjelo",
"youtubeDescriptionNotFound": "Tema nije pronađena: {theme_id}",
"youtubeDescriptionLoadError": "Učitavanje YouTube opisa nije uspjelo"
},
"tenant": {
"assetNotFound": "Resurs nije pronađen"
},
"push": {
"disabled": "Push obavijesti nisu omogućene",
"userEmailNotAvailable": "E-mail korisnika nije dostupan",
"missingEncryptionKeys": "Nedostaju potrebni ključevi (p256dh, auth)",
"subscriptionSaveFailed": "Spremanje pretplate nije uspjelo",
"subscriptionRegistered": "Push pretplata je uspješno registrirana",
"subscriptionNotFound": "Pretplata je uklonjena (ili nije pronađena)",
"subscriptionRemoved": "Push pretplata je uspješno uklonjena",
"testNotificationSent": "Testna obavijest poslana na {sent_count} uređaj(a)"
},
"pushNotifications": {
"reviewLyricsTitle": "Pregledaj tekst",
"reviewLyricsBody": "\"{title}\" od {artist} treba pregled teksta",
"selectInstrumentalTitle": "Odaberi instrumental",
"selectInstrumentalBody": "\"{title}\" od {artist} treba odabir instrumentala",
"videoReadyTitle": "Video je spreman!",
"videoReadyBody": "Tvoj karaoke video za \"{title}\" od {artist} je spreman za preuzimanje"
},
"admin": {
"invalidDomainFormat": "Nevažeći format domene",
"domainAddedToBl": "Domena '{domain}' dodana je na popis blokiranih domena za jednokratnu upotrebu",
"domainNotFoundInBl": "Domena nije pronađena na popisu blokiranih",
"domainRemovedFromBl": "Domena '{domain}' uklonjena je s popisa blokiranih domena za jednokratnu upotrebu",
"domainAddedToAllowlist": "Domena '{domain}' dodana je na popis dopuštenih",
"domainNotFoundInAllowlist": "Domena nije pronađena na popisu dopuštenih",
"domainRemovedFromAllowlist": "Domena '{domain}' uklonjena je s popisa dopuštenih",
"syncComplete": "Sinkronizirano {external_count} vanjskih domena ({added} dodano, {removed} uklonjeno)",
"invalidEmailFormat": "Nevažeći format e-pošte",
"emailAddedToBl": "E-mail '{email}' dodan je na popis blokiranih e-mailova",
"emailNotFoundInBl": "E-mail nije pronađen na popisu blokiranih",
"emailRemovedFromBl": "E-mail '{email}' uklonjen je s popisa blokiranih e-mailova",
"invalidIPAddress": "Nevažeća IP adresa",
"ipAddedToBl": "IP '{ip_address}' dodan je na popis blokiranih IP-ova",
"ipNotFoundInBl": "IP nije pronađen na popisu blokiranih",
"ipRemovedFromBl": "IP '{ip_address}' uklonjen je s popisa blokiranih IP-ova",
"youtubeUploadNotFound": "Prijenos nije pronađen ili nije u stanju za ponovni pokušaj za zadatak {job_id}",
"youtubeUploadQueuedForRetry": "YouTube prijenos za zadatak {job_id} stavljen je u red čekanja za ponovni pokušaj",
"youtubeQueueProcessingStarted": "Obrada YouTube reda čekanja započela je u pozadini"
},
"rateLimits": {
"configNotFound": "Konfiguracija ograničenja učestalosti nije pronađena: {config_id}",
"configUpdateError": "Pogreška pri ažuriranju konfiguracije ograničenja učestalosti: {error}"
},
"errors": {
"insufficientCredits": "Nedovoljno kredita za ovu operaciju",
"insufficientCreditsBuyUrl": "/#pricing"
},
"emails": {
"magicLink": {
"subject": "Prijavi se u {brand_name}",
"greeting": "Bok,",
"signInPrompt": "Klikni na gumb ispod za prijavu u {brand_name}:",
"signInButton": "Prijavi se",
"expiryWarning": "Ova poveznica istječe za 15 minuta i može se iskoristiti samo jednom.",
"fallbackLink": "Ako gumb ne radi, kopiraj i zalijepi ovu poveznicu u svoj preglednik:",
"ignoreNote": "Ako nisi zatražio/la ovaj e-mail, slobodno ga ignoriraj."
},
"welcome": {
"subject": "Dobrodošao/la u Nomad Karaoke!",
"welcomeGreeting": "Dobrodošao/la u Nomad Karaoke!",
"turnAnySong": "Pretvori bilo koju pjesmu u profesionalni karaoke video u nekoliko minuta.",
"freeCreditsLabel": "Besplatni krediti",
"freeCreditsNote": "Svaki kredit stvara jedan profesionalni karaoke video",
"howItWorks": "Evo kako to funkcionira:",
"step1Title": "1. Potraži pjesmu",
"step1Desc": "Unesi izvođača i naslov, a mi ćemo pronaći zvuk visoke kvalitete.",
"step2Title": "2. Naš sustav radi svoju čaroliju",
"step2Desc": "Odvajamo vokale, transkribiramo tekst i sve savršeno sinkroniziramo.",
"step3Title": "3. Pregledaj i prilagodi",
"step3Desc": "Fino podesi tekst ako je potrebno, odaberi svoj instrumental.",
"step4Title": "4. Preuzmi svoj video",
"step4Desc": "Preuzmi svoj 4K karaoke video ili ga prenesi izravno na YouTube.",
"feedbackBonus": "Dovrši 2 videa i zaradi još 2 besplatna kredita dijeljenjem svojih povratnih informacija!",
"getStartedButton": "Započni"
},
"creditsAdded": {
"subject": "{credits} kredita dodano je na tvoj Nomad Karaoke račun",
"greatNews": "Sjajne vijesti!",
"creditsAddedMessage": "{credits} kredita dodano je na tvoj račun.",
"yourBalance": "Tvoje stanje:",
"credits": "kredita",
"eachCreditLets": "Svaki kredit ti omogućuje stvaranje jednog profesionalnog karaoke videa s:",
"featureVocalSeparation": "AI odvajanjem vokala/instrumentala",
"featureLyrics": "Sinkroniziranim tekstom s tempiranjem na razini riječi",
"feature4k": "4K video izlazom",
"featureYoutube": "YouTube prijenosom",
"createButton": "Kreiraj karaoke sada"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (Tvoj karaoke video je spreman!)",
"subject": "{artist} - {title} (Tvoj karaoke video je spreman!)",
"subjectFallback": "Tvoj karaoke video je spreman!"
},
"youtubeUpload": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (YouTube prijenos je spreman!)",
"subject": "{artist} - {title} (YouTube prijenos je spreman!)",
"subjectFallback": "Tvoj YouTube prijenos je spreman!"
},
"actionReminder": {
"lyricsSubject": "Potrebna akcija: Pregledaj tekst za {artist} - {title}",
"lyricsSubjectFallback": "Potrebna akcija: Pregledaj tekst",
"instrumentalSubject": "Potrebna akcija: Odaberi instrumental za {artist} - {title}",
"instrumentalSubjectFallback": "Potrebna akcija: Odaberi instrumental",
"audioEditSubject": "Potrebna akcija za {artist} - {title}",
"audioEditSubjectFallback": "Potrebna akcija",
"alertHeading": "Tvoj karaoke video treba tvoju pažnju!"
},
"reviewReminder": {
"subject": "Podsjetnik: Tvoj karaoke video čeka na pregled — {artist} - {title}",
"subjectFallback": "Podsjetnik: Tvoj karaoke video čeka na pregled",
"alertHeading": "Tvoj karaoke video te čeka!",
"reminderIntro": "Samo prijateljski podsjetnik da je tvoj karaoke video{song_name} spreman za pregled.",
"reviewButton": "Pregledaj svoj video",
"reviewInstructions": "Tijekom pregleda možeš provjeriti je li tekst točan i odabrati željeni instrumentalni zapis. To obično traje samo nekoliko minuta!",
"helpOffer": "Ako imaš bilo kakvih problema s postupkom pregleda, samo odgovori na ovaj e-mail i rado ću ti pomoći.",
"expiryWarning": "Napomena: ako pregled ne bude dovršen u naredna 24 sata, zadatak će automatski isteći i tvoj kredit će biti vraćen."
},
"reviewExpired": {
"subject": "Tvoj karaoke video je istekao — {artist} - {title}",
"subjectFallback": "Tvoj karaoke video je istekao",
"cancelNotice": "Tvoj karaoke video{song_name} je automatski otkazan jer pregled nije dovršen u roku od 48 sati.",
"refundNotice": "Ne brini — tvoj kredit je vraćen! Tvoje trenutno stanje je {credits_balance} {credits_word}.",
"creditSingular": "kredit",
"creditPlural": "kredita",
"createNewPrompt": "Možeš kreirati novi karaoke video u bilo kojem trenutku koristeći svoje kredite:",
"createButton": "Kreiraj novi video",
"helpOffer": "Ako si imao/la bilo kakvih problema s postupkom pregleda ili trebaš pomoć, samo odgovori na ovaj e-mail — rado ću pomoći!"
},
"creditDenied": {
"subject": "O tvojim Nomad Karaoke besplatnim kreditima",
"greeting": "Bok,",
"thankYou": "Hvala na prijavi na Nomad Karaoke!",
"deniedMessage": "Nažalost, ovaj put ti nismo mogli dodijeliti tvoje besplatne {credit_type}. Naš sustav je otkrio obrasce koji sugeriraju da ovo možda nije tvoj prvi račun kod nas, a svaki zadatak generiranja karaoka košta nas stvarni novac u računalstvu u oblaku i API naknadama.",
"mistakeNote": "Potpuno razumijemo ako je ovo pogreška! Ako si zaista novi korisnik, samo odgovori na ovaj e-mail i javi Andrewu (osnivaču). On je izgradio ovu uslugu i rado će ti dodijeliti nekoliko besplatnih kredita da je isprobaš — samo traži da zauzvrat pružiš iskrene povratne informacije o iskustvu.",
"buyPrompt": "Ako želiš odmah započeti, možeš i kupiti kredite:",
"buyButton": "Kupi kredite",
"costNote": "Držimo troškove niskima kako bismo uslugu mogli nuditi po pristupačnoj cijeni, što znači da moramo paziti na zloupotrebu besplatnih kredita. Hvala na razumijevanju!",
"welcomeCredits": "kredite dobrodošlice",
"feedbackCredits": "bonus kredite za povratne informacije"
},
"madeForYouConfirmation": {
"subject": "Narudžba potvrđena: {artist} - {title} | Nomad Karaoke",
"thankYou": "Hvala ti na tvojoj narudžbi!",
"orderDetails": "Detalji narudžbe",
"orderId": "ID narudžbe:",
"artist": "Izvođač:",
"title": "Naslov:",
"yourNotes": "Tvoje bilješke:",
"deliveryTime": "Naš tim će kreirati tvoj prilagođeni karaoke video unutar {hours} sati.",
"deliveryNotice": "Primit ćeš e-mail s poveznicama za preuzimanje čim tvoj video bude spreman.",
"noAction": "Nije potrebna nikakva akcija — opusti se i mi ćemo se pobrinuti za sve!"
},
"shared": {
"footerHelp": "Ako nešto nije savršeno, samo odgovori na ovaj e-mail i ja ću to popraviti!"
},
"templates": {
"jobCompletion": {
"greeting": "Bok {name},",
"thanks": "Hvala na tvojoj narudžbi!",
"youtubeLink": "Evo poveznice za karaoke video objavljen na YouTubeu:",
"dropboxIntro": "Evo Dropbox mape sa svim završenim i izvornim datotekama, uključujući:",
"fileList": "- \"(Final Karaoke Lossless).mkv\": kombinirani karaoke video u 4K H264 s FLAC zvukom bez gubitaka\n- \"(Final Karaoke).mp4\": kombinirani karaoke video s naslovnim/završnim zaslonom u 4K H264/AAC\n- \"(Final Karaoke 720p).mp4\": kombinirani karaoke video u 720p H264/AAC (manja datoteka za starije sustave)\n- \"(With Vocals).mp4\": video za pjevanje u 4K H264/AAC s originalnim vokalima\n- \"(Karaoke).mov\": izlazni karaoke video iz MidiCo (bez naslovnog/završnog zaslona)\n- \"(Title).mov\"/\"(End).mov\": videozapisi naslovne kartice i završnog zaslona\n- \"(Final Karaoke CDG).zip\": CDG+MP3 format za starije/komercijalne karaoke sustave\n- \"(Final Karaoke TXT).zip\": TXT+MP3 format za Power Karaoke\n- stems/*.flac: razni odvojeni instrumentalni i vokalni audio stemovi u formatu bez gubitaka\n- lyrics/*.txt: tekstovi pjesama iz raznih izvora u običnom tekstualnom formatu",
"fixOffer": "Javi mi ako nešto nije savršeno i rado ću to prilagoditi / popraviti, ili ako ti treba u nekom drugom formatu, vjerojatno to mogu pretvoriti za tebe!",
"feedbackRequest": "Ako imaš trenutak, zaista bih cijenio tvoje povratne informacije (traje 2 minute):",
"signOff": "Još jednom hvala i ugodan dan!\n-Andrew",
"youtubeQueued": "Tvoj YouTube prijenos je u redu čekanja i bit će automatski obrađen. Uskoro ćeš primiti naknadni e-mail s poveznicom."
},
"actionLyrics": {
"greeting": "Bok {name},",
"ready": "Tvoj karaoke video za \"{artist} - {title}\" je spreman za pregled!",
"instructions": "Naš sustav je transkribirao i sinkronizirao tekst, ali možda će trebati neke ispravke. Također ćeš moći odabrati željeni instrumentalni zapis (sa ili bez pratećih vokala).",
"reviewPrompt": "Molim te pregledaj svoj tekst i odaberi instrumental:",
"duration": "Ovo obično traje samo nekoliko minuta.",
"signOff": "Hvala!\n-Andrew"
},
"actionInstrumental": {
"greeting": "Bok {name},",
"almostDone": "Tvoj karaoke video za \"{artist} - {title}\" je skoro gotov!",
"instructions": "Odvojili smo zvuk u različite verzije. Molim te odaberi koji instrumentalni zapis želiš koristiti za konačni video.",
"selectPrompt": "Odaberi svoj instrumental ovdje:",
"signOff": "Hvala!\n-Andrew"
},
"youtubeComplete": {
"greeting": "Bok {name},",
"greatNews": "Sjajne vijesti! Tvoj karaoke video za \"{artist} - {title}\" je prenesen na YouTube:",
"delayNote": "Ovaj prijenos je bio nakratko odgođen dok su naši sustavi obrađivali druge prijenose, ali sada je sve spremno.",
"signOff": "Hvala!\n-Andrew"
}
}
}
}
+338
View File
@@ -0,0 +1,338 @@
{
"auth": {
"unknownService": "Ismeretlen szolgáltatás: {service}",
"invalidCredentials": "A következő szolgáltatások újraengedélyezést igényelnek: {services}",
"validCredentials": "Minden kért hitelesítő adat érvényes",
"youtubeAuthInstructions": "Látogass el a {verification_url} oldalra, és írd be a kódot: {user_code}",
"youtubeAuthStartFailed": "Nem sikerült elindítani a YouTube eszköz hitelesítését: {error}",
"gdriveLinkInstructions": "Látogass el a {verification_url} oldalra, és írd be a kódot: {user_code}",
"gdriveAuthStartFailed": "Nem sikerült elindítani a Google Drive eszköz hitelesítését: {error}",
"discordAlertNotConfigured": "A Discord riasztási webhook nincs konfigurálva"
},
"jobs": {
"created": "Feladat sikeresen létrehozva. A feldolgozás megkezdődött.",
"authError": "Hitelesítési hiba: nem áll rendelkezésre felhasználói identitás",
"noDefaultTheme": "Nincs alapértelmezett téma konfigurálva. Kérlek, lépj kapcsolatba az ügyfélszolgálattal, vagy adj meg egy theme_id-t.",
"notFound": "A feladat nem található",
"noPermissionAccess": "Nincs jogosultságod a feladat eléréséhez",
"noPermissionEdit": "Nincs jogosultságod a feladat szerkesztéséhez",
"noPermissionDelete": "Nincs jogosultságod a feladat törléséhez",
"noPermissionModify": "Nincs jogosultságod a feladat módosításához",
"notCompleted": "Csak befejezett feladatok szerkeszthetők. Jelenlegi állapot: {status}",
"alreadyBeingEdited": "Ezt a feladatot már szerkesztik (a kimenetek már törölve lettek)",
"cleanupFailed": "A tisztítás sikertelen a következőknél: {services}. A feladat nem módosult. Kérlek, próbáld újra, vagy lépj kapcsolatba az ügyfélszolgálattal.",
"reopened": "A sáv újra megnyitva szerkesztésre. A korábbi kimenetek el lettek távolítva.",
"invalidDatetimeFormat": "Érvénytelen {field} formátum: {value}",
"listError": "Hiba a feladatok listázásakor: {error}",
"deleteError": "Hiba a(z) {job_id} feladat törlésekor: {error}",
"deletionPreview": "Add hozzá a &confirm=true paramétert a törlés végrehajtásához",
"deletionRequiresFilters": "Legalább egy szűrő (environment, client_id, status, created_before) megadása kötelező",
"bulkDeleteError": "Hiba a feladatok tömeges törlésekor: {error}",
"reviewNotReady": "A feladat még nem áll készen az ellenőrzésre (jelenlegi állapot: {status})",
"correctionsUnavailable": "A javítási adatok nem állnak rendelkezésre",
"audioUnavailable": "A hang nem áll rendelkezésre az ellenőrzéshez",
"reviewCannotStart": "Az ellenőrzés nem indítható el",
"jobNotInReviewState": "A feladat nincs ellenőrzési állapotban (jelenlegi állapot: {status})",
"correctionsProcessing": "Javítások mentve. Hívd meg a /complete-review végpontot, ha végeztél.",
"editLogSaveFailed": "Hiba a(z) {job_id} feladat szerkesztési naplójának mentésekor: {error}",
"stemsMissing": "A feladatból hiányoznak a szükséges sávok (instrumental_clean és/vagy backing_vocals)",
"customInstrumentalFailed": "Hiba a(z) {job_id} feladat egyéni instrumentális sávjának létrehozásakor: {error}",
"audioProcessingFailed": "Nem sikerült feldolgozni a hangfájlt: {error}",
"durationMismatch": "Időtartam eltérés: a feltöltött fájl {upload_duration}s, de az eredeti hang {original_duration}s. Az instrumentális sávnak pontosan {original_duration}s (±0.5s) hosszúnak kell lennie.",
"reviewNotInState": "A feladat nincs ellenőrzési állapotban (jelenlegi állapot: {status})",
"noLyricsDetected": "Nem lehet befejezni az ellenőrzést: nem észleltünk dalszöveget a hangban. Ez akkor fordulhat elő, ha a bemeneti hangban nincsenek énekhangok (pl. karaoke sáv vagy instrumentális). Visszamehetsz és manuálisan beillesztheted a dalszöveget a 'Replace All' használatával, vagy törölheted ezt a feladatot, és újra próbálkozhatsz egy olyan hangfájllal, amely tartalmaz éneket.",
"reviewCompleteStartRendering": "Ellenőrzés befejezve. A videó renderelése megkezdődött.",
"reviewCompleteError": "Hiba a(z) {job_id} feladat ellenőrzésének befejezésekor: {error}",
"instrumentalSelectionRequired": "Az instrumental_selection kötelező. Értéke 'clean' vagy 'with_backing' kell legyen.",
"invalidInstrumentalSelection": "Érvénytelen instrumental_selection. A következők egyike kell legyen: {valid_selections}",
"instrumentalSelected": "Instrumentális sáv kiválasztva. A videó generálása megkezdődött.",
"instrumentalSelectionError": "Hiba a(z) {job_id} feladat instrumentális sávjának kiválasztásakor: {error}",
"downloadUrlsError": "Hiba a letöltési URL-ek lekérésekor: {error}"
},
"review": {
"jobNotFound": "A feladat nem található",
"reviewNotReady": "A feladat még nem áll készen az ellenőrzésre (jelenlegi állapot: {status})",
"correctionsNotFound": "A javítási adatok nem találhatók. A dalszöveg feldolgozása lehet, hogy még nem fejeződött be.",
"correctionsLoadFailed": "Hiba a javítások betöltésekor: {error}",
"audioNotFound": "A hangfájl nem található",
"audioServeError": "Hiba a hang kiszolgálásakor: {error}",
"instrumentalSelectionRequired": "Az instrumental_selection kötelező. Értéke 'clean' vagy 'with_backing' kell legyen.",
"invalidInstrumentalSelection": "Érvénytelen instrumental_selection. A következők egyike kell legyen: {valid_selections}",
"reviewCompletedError": "Hiba az ellenőrzés befejezésekor: {error}",
"handlersUpdateNotImplemented": "A kezelők frissítése még nincs implementálva",
"lyricsAddError": "Nem sikerült hozzáadni a dalszöveget: {error}",
"lyricsAddInvalidRequest": "Érvénytelen dalszöveg hozzáadási kérés: {error}",
"lyricsSearchError": "Nem sikerült keresni a dalszöveget: {error}",
"lyricsSearchInvalidRequest": "Érvénytelen dalszöveg keresési kérés: {error}",
"lyricsSearchNoResults": "Nem található egyező dalszöveg egyik szolgáltatónál sem",
"previewVideoGenerationError": "Nem sikerült legenerálni az előnézeti videót: {error}",
"previewVideoNotFound": "Az előnézeti videó nem található",
"previewVideoStreamError": "Hiba az előnézeti videó streamelésekor: {error}",
"annotationSaveError": "Hiba a jegyzetek mentésekor: {error}",
"waveformGenerationError": "Hiba a hullámforma adatok generálásakor: {error}",
"waveformNoAudio": "Nincs elérhető hang a hullámformához",
"sessionSaveError": "Javítási adatok szükségesek"
},
"audioSearch": {
"notEnabled": "A hangkeresés nincs engedélyezve ehhez a bérlőhöz",
"disabled": "A hangkeresés nem érhető el",
"downloadError": "A letöltés sikertelen a(z) {job_id} feladatnál: {error}",
"jobNotFound": "A(z) {job_id} feladat nem található",
"noSearchResults": "Nincsenek elérhető keresési eredmények",
"invalidSelectionIndex": "Érvénytelen kiválasztási index: {selection_index}. Érvényes tartomány: 0-{max}",
"selectionError": "Hiba a hang kiválasztása során a(z) {job_id} feladatnál: {error}",
"youtubeDownloadError": "A YouTube letöltés sikertelen: {error}",
"torrentDownloadError": "Nem lehet letölteni a(z) {source} forrásból távoli flacfetch szolgáltatás nélkül. Konfiguráld a FLACFETCH_API_URL-t.",
"remoteDownloadNoSearchId": "Nincs elérhető source_id vagy remote_search_id a(z) {source} letöltéshez",
"remoteDownloadCompleteNoPath": "A távoli letöltés befejeződött, de nem tért vissza fájlútvonallal",
"spotifyDownloadError": "Nem lehet letölteni a Spotify-ról távoli flacfetch szolgáltatás nélkül. Konfiguráld a FLACFETCH_API_URL-t.",
"genericDownloadError": "Ismeretlen forrástípus: {source}, általános letöltés megkísérlése",
"jobNotFoundDuringDownload": "A(z) {job_id} feladat nem található a háttérben történő letöltés során",
"selectAudioError": "Hiba a hang kiválasztásakor a(z) {job_id} feladatnál: {error}",
"searchAudioError": "Hiba a hang keresésekor: {error}",
"searchCreatedSuccessfully": "Feladat létrehozva. Hang keresése...",
"autoDownloadStarted": "A legjobb eredmény automatikusan kiválasztva. Letöltés indítása..."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
"magicLinkSent": "Ha ez az e-mail cím regisztrálva van, hamarosan kapsz egy bejelentkezési linket.",
"emailServiceNotConfigured": "Az e-mail szolgáltatás nem érhető el. Kérlek, lépj kapcsolatba az ügyfélszolgálattal.",
"emailDomainNotAllowed": "Az e-mail domain nem engedélyezett ehhez a bérlőhöz",
"invalidToken": "Érvénytelen token",
"verifyError": "Az ellenőrzés sikertelen: {message}",
"magicLinkSuccess": "Sikeresen bejelentkeztél",
"logoutSuccess": "Sikeresen kijelentkeztél",
"userNotFound": "A felhasználó nem található",
"creditPackagesError": "Hiba a kreditcsomagok betöltésekor: {error}",
"stripeSendError": "Hiba a Stripe fizetési link küldésekor: {error}",
"stripeWebhookProcessingError": "Hiba a Stripe webhook feldolgozásakor: {error}",
"feedbackSaveError": "Hiba a visszajelzés mentésekor: {error}",
"feedbackNotEligible": "A felhasználó nem jogosult visszajelzésre"
},
"fileUpload": {
"invalidTheme": "A téma nem található: {theme_id}. Használd a GET /api/themes végpontot az elérhető témák listázásához.",
"uploadSuccess": "A fájl sikeresen feltöltve. A feldolgozás megkezdődött.",
"uploadError": "Hiba a fájl feltöltésekor: {error}",
"urlDownloadError": "Hiba az URL-ről történő letöltéskor: {error}",
"invalidContentType": "Érvénytelen tartalomtípus: {content_type}",
"fileSizeError": "A fájl túl nagy: {size}. Maximum: {max_size}",
"invalidFileType": "Érvénytelen fájltípus: {file_type}",
"multipleAudioFilesNotAllowed": "Csak egy hangfájl tölthető fel",
"noAudioFileProvided": "Nincs megadva hangfájl",
"urlCreationSuccess": "Feladat létrehozva. Feltöltési URL-ek generálva.",
"urlCreationError": "Hiba a feladat létrehozásakor a feltöltési URL-ekkel: {error}",
"uploadsCompleteSuccess": "Feltöltések befejezve. A feldolgozás megkezdődött.",
"uploadsCompleteError": "Hiba a feltöltések befejezésekor: {error}",
"noUploadedFiles": "Nincsenek megadva feltöltött fájlok",
"styleUploadUrlsSuccess": "Stílus feltöltési URL-ek generálva.",
"styleUploadsCompleteSuccess": "Stílusfájlok frissítve. A feldolgozás újraindítva.",
"styleUploadsCompleteError": "Hiba a stílusfeltöltések befejezésekor: {error}"
},
"catalog": {
"rateLimitExceeded": "Sebességkorlát túllépve. Maximum {max_requests} katalóguskérés percenként.",
"catalogSearchError": "Hiba a katalógus keresésekor: {error}",
"communityCheckError": "Hiba a közösségi verziók ellenőrzésekor: {error}"
},
"themes": {
"themesLoadError": "Nem sikerült betölteni a témákat",
"themeNotFound": "A téma nem található: {theme_id}",
"themeLoadError": "Nem sikerült betölteni a témát",
"previewNotAvailable": "Nincs elérhető előnézet a témához: {theme_id}",
"previewLoadError": "Nem sikerült betölteni a téma előnézetét",
"youtubeDescriptionNotFound": "A téma nem található: {theme_id}",
"youtubeDescriptionLoadError": "Nem sikerült betölteni a YouTube leírást"
},
"tenant": {
"assetNotFound": "Az eszköz nem található"
},
"push": {
"disabled": "A push értesítések nincsenek engedélyezve",
"userEmailNotAvailable": "A felhasználó e-mail címe nem érhető el",
"missingEncryptionKeys": "Hiányzó szükséges kulcsok (p256dh, auth)",
"subscriptionSaveFailed": "Nem sikerült menteni a feliratkozást",
"subscriptionRegistered": "Push feliratkozás sikeresen regisztrálva",
"subscriptionNotFound": "A feliratkozás eltávolítva (vagy nem található)",
"subscriptionRemoved": "Push feliratkozás sikeresen eltávolítva",
"testNotificationSent": "Teszt értesítés elküldve {sent_count} eszközre"
},
"pushNotifications": {
"reviewLyricsTitle": "Dalszöveg ellenőrzése",
"reviewLyricsBody": "\"{title}\" ({artist}) dalszövegének ellenőrzése szükséges",
"selectInstrumentalTitle": "Instrumentális sáv kiválasztása",
"selectInstrumentalBody": "\"{title}\" ({artist}) instrumentális sávjának kiválasztása szükséges",
"videoReadyTitle": "A videó kész!",
"videoReadyBody": "A(z) \"{title}\" ({artist}) karaoke videód készen áll a letöltésre"
},
"admin": {
"invalidDomainFormat": "Érvénytelen domain formátum",
"domainAddedToBl": "A(z) '{domain}' domain hozzáadva az eldobható domainek tiltólistájához",
"domainNotFoundInBl": "A domain nem található a tiltólistán",
"domainRemovedFromBl": "A(z) '{domain}' domain eltávolítva az eldobható domainek tiltólistájáról",
"domainAddedToAllowlist": "A(z) '{domain}' domain hozzáadva az engedélyezőlistához",
"domainNotFoundInAllowlist": "A domain nem található az engedélyezőlistán",
"domainRemovedFromAllowlist": "A(z) '{domain}' domain eltávolítva az engedélyezőlistáról",
"syncComplete": "{external_count} külső domain szinkronizálva ({added} hozzáadva, {removed} eltávolítva)",
"invalidEmailFormat": "Érvénytelen e-mail formátum",
"emailAddedToBl": "A(z) '{email}' e-mail hozzáadva a blokkolt e-mailek listájához",
"emailNotFoundInBl": "Az e-mail nem található a tiltólistán",
"emailRemovedFromBl": "A(z) '{email}' e-mail eltávolítva a blokkolt e-mailek listájáról",
"invalidIPAddress": "Érvénytelen IP-cím",
"ipAddedToBl": "A(z) '{ip_address}' IP hozzáadva a blokkolt IP-k listájához",
"ipNotFoundInBl": "Az IP nem található a tiltólistán",
"ipRemovedFromBl": "A(z) '{ip_address}' IP eltávolítva a blokkolt IP-k listájáról",
"youtubeUploadNotFound": "A feltöltés nem található, vagy nincs újrapróbálható állapotban a(z) {job_id} feladatnál",
"youtubeUploadQueuedForRetry": "A YouTube feltöltés a(z) {job_id} feladatnál sorba állítva újrapróbálkozásra",
"youtubeQueueProcessingStarted": "A YouTube sor feldolgozása elindult a háttérben"
},
"rateLimits": {
"configNotFound": "A sebességkorlát konfigurációja nem található: {config_id}",
"configUpdateError": "Hiba a sebességkorlát konfigurációjának frissítésekor: {error}"
},
"errors": {
"insufficientCredits": "Nincs elég kredited ehhez a művelethez",
"insufficientCreditsBuyUrl": "/#pricing"
},
"emails": {
"magicLink": {
"subject": "Jelentkezz be a {brand_name} fiókodba",
"greeting": "Szia!",
"signInPrompt": "Kattints az alábbi gombra a {brand_name} oldalra történő bejelentkezéshez:",
"signInButton": "Bejelentkezés",
"expiryWarning": "Ez a link 15 perc múlva lejár, és csak egyszer használható fel.",
"fallbackLink": "Ha a gomb nem működik, másold be ezt a linket a böngésződbe:",
"ignoreNote": "Ha nem te kérted ezt az e-mailt, nyugodtan hagyd figyelmen kívül."
},
"welcome": {
"subject": "Üdvözlünk a Nomad Karaoke-ban!",
"welcomeGreeting": "Üdvözlünk a Nomad Karaoke-ban!",
"turnAnySong": "Alakíts bármilyen dalt professzionális karaoke videóvá percek alatt.",
"freeCreditsLabel": "Ingyenes kreditek",
"freeCreditsNote": "Minden kredit egy professzionális karaoke videó létrehozására használható fel",
"howItWorks": "Így működik:",
"step1Title": "1. Keress egy dalt",
"step1Desc": "Add meg az előadót és a címet, és mi találunk egy kiváló minőségű hanganyagot.",
"step2Title": "2. A rendszerünk varázsol",
"step2Desc": "Szétválasztjuk az éneket, leírjuk a dalszöveget, és mindent tökéletesen szinkronizálunk.",
"step3Title": "3. Ellenőrzés és testreszabás",
"step3Desc": "Finomhangold a dalszöveget, ha szükséges, és válaszd ki az instrumentális sávot.",
"step4Title": "4. Szerezd meg a videódat",
"step4Desc": "Töltsd le a 4K karaoke videódat, vagy töltsd fel közvetlenül a YouTube-ra.",
"feedbackBonus": "Készíts el 2 videót, és szerezz további 2 ingyenes kreditet a visszajelzésed megosztásával!",
"getStartedButton": "Kezdés"
},
"creditsAdded": {
"subject": "{credits} kredit hozzáadva a Nomad Karaoke fiókodhoz",
"greatNews": "Nagyszerű hír!",
"creditsAddedMessage": "{credits} kreditet írtunk jóvá a fiókodban.",
"yourBalance": "Egyenleged:",
"credits": "kredit",
"eachCreditLets": "Minden kredit egy professzionális karaoke videó létrehozását teszi lehetővé a következőkkel:",
"featureVocalSeparation": "AI-alapú ének/instrumentális szétválasztás",
"featureLyrics": "Szinkronizált dalszöveg szószintű időzítéssel",
"feature4k": "4K videó kimenet",
"featureYoutube": "YouTube feltöltés",
"createButton": "Karaoke készítése most"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (A karaoke videód elkészült!)",
"subject": "{artist} - {title} (A karaoke videód elkészült!)",
"subjectFallback": "A karaoke videód elkészült!"
},
"youtubeUpload": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (A YouTube feltöltés kész!)",
"subject": "{artist} - {title} (A YouTube feltöltés kész!)",
"subjectFallback": "A YouTube feltöltésed kész!"
},
"actionReminder": {
"lyricsSubject": "Művelet szükséges: Ellenőrizd a dalszöveget: {artist} - {title}",
"lyricsSubjectFallback": "Művelet szükséges: Dalszöveg ellenőrzése",
"instrumentalSubject": "Művelet szükséges: Válassz instrumentális sávot: {artist} - {title}",
"instrumentalSubjectFallback": "Művelet szükséges: Instrumentális sáv kiválasztása",
"audioEditSubject": "Művelet szükséges: {artist} - {title}",
"audioEditSubjectFallback": "Művelet szükséges",
"alertHeading": "A karaoke videódhoz a te közreműködésedre van szükség!"
},
"reviewReminder": {
"subject": "Emlékeztető: A karaoke videód ellenőrzésre vár — {artist} - {title}",
"subjectFallback": "Emlékeztető: A karaoke videód ellenőrzésre vár",
"alertHeading": "A karaoke videód rád vár!",
"reminderIntro": "Csak egy baráti emlékeztető, hogy a karaoke videód{song_name} készen áll az ellenőrzésre.",
"reviewButton": "Videó ellenőrzése",
"reviewInstructions": "Az ellenőrzés során megnézheted, hogy a dalszöveg helyes-e, és kiválaszthatod a kívánt instrumentális sávot. Ez általában csak néhány percet vesz igénybe!",
"helpOffer": "Ha bármilyen problémád adódna az ellenőrzési folyamat során, csak válaszolj erre az e-mailre, és szívesen segítek.",
"expiryWarning": "Kérlek, vedd figyelembe: ha az ellenőrzés nem fejeződik be a következő 24 órában, a feladat automatikusan lejár, és a kreditedet visszatérítjük."
},
"reviewExpired": {
"subject": "A karaoke videód lejárt — {artist} - {title}",
"subjectFallback": "A karaoke videód lejárt",
"cancelNotice": "A karaoke videód{song_name} automatikusan törölve lett, mert az ellenőrzés nem fejeződött be 48 órán belül.",
"refundNotice": "Ne aggódj — a kreditedet visszatérítettük! A jelenlegi egyenleged {credits_balance} {credits_word}.",
"creditSingular": "kredit",
"creditPlural": "kredit",
"createNewPrompt": "Bármikor készíthetsz új karaoke videót a kreditjeid felhasználásával:",
"createButton": "Új videó készítése",
"helpOffer": "Ha bármilyen problémád adódott az ellenőrzési folyamattal, vagy segítségre van szükséged, csak válaszolj erre az e-mailre — szívesen segítek!"
},
"creditDenied": {
"subject": "A Nomad Karaoke ingyenes kreditjeidről",
"greeting": "Szia!",
"thankYou": "Köszönjük, hogy regisztráltál a Nomad Karaoke-ra!",
"deniedMessage": "Sajnos ezúttal nem tudtuk megadni az ingyenes {credit_type} kreditjeidet. A rendszerünk olyan mintákat észlelt, amelyek arra utalnak, hogy talán nem ez az első fiókod nálunk, és minden karaoke generálási feladat valódi pénzbe kerül nekünk a felhőalapú számítástechnikai és API díjak miatt.",
"mistakeNote": "Teljesen megértjük, ha ez egy tévedés! Ha te egy valódi új felhasználó vagy, kérlek, csak válaszolj erre az e-mailre, és jelezd Andrew-nak (az alapítónak). Ő építette ezt a szolgáltatást, és szívesen ad neked néhány ingyenes kreditet, hogy kipróbáld — csupán annyit kér, hogy cserébe adj őszinte visszajelzést a tapasztalataidról.",
"buyPrompt": "Ha azonnal el szeretnéd kezdeni, vásárolhatsz is krediteket:",
"buyButton": "Kreditek vásárlása",
"costNote": "A költségeket alacsonyan tartjuk, hogy megfizethetően kínálhassuk a szolgáltatást, ami azt jelenti, hogy óvatosnak kell lennünk az ingyenes kreditekkel való visszaélésekkel kapcsolatban. Köszönjük a megértésedet!",
"welcomeCredits": "üdvözlő",
"feedbackCredits": "visszajelzési bónusz"
},
"madeForYouConfirmation": {
"subject": "Rendelés megerősítve: {artist} - {title} | Nomad Karaoke",
"thankYou": "Köszönjük a rendelésedet!",
"orderDetails": "Rendelés részletei",
"orderId": "Rendelés azonosítója:",
"artist": "Előadó:",
"title": "Cím:",
"yourNotes": "Megjegyzéseid:",
"deliveryTime": "Csapatunk {hours} órán belül elkészíti az egyedi karaoke videódat.",
"deliveryNotice": "Amint a videód elkészült, kapsz egy e-mailt a letöltési linkekkel.",
"noAction": "Nincs teendőd — dőlj hátra, és mi mindenről gondoskodunk!"
},
"shared": {
"footerHelp": "Ha valami nem tökéletes, csak válaszolj erre az e-mailre, és kijavítom!"
},
"templates": {
"jobCompletion": {
"greeting": "Szia {name}!",
"thanks": "Köszönjük a rendelésedet!",
"youtubeLink": "Itt a link a YouTube-ra közzétett karaoke videóhoz:",
"dropboxIntro": "Itt a Dropbox mappa az összes kész fájllal és forrásfájllal, beleértve:",
"fileList": "- \"(Final Karaoke Lossless).mkv\": kombinált karaoke videó 4K H264 formátumban veszteségmentes FLAC hanggal\n- \"(Final Karaoke).mp4\": kombinált karaoke videó címmel/záróképernyővel 4K H264/AAC formátumban\n- \"(Final Karaoke 720p).mp4\": kombinált karaoke videó 720p H264/AAC formátumban (kisebb fájl régebbi rendszerekhez)\n- \"(With Vocals).mp4\": együtténeklős videó 4K H264/AAC formátumban eredeti énekhanggal\n- \"(Karaoke).mov\": karaoke videó kimenet a MidiCo-ból (cím/záróképernyő nélkül)\n- \"(Title).mov\"/\"(End).mov\": címkártya és záróképernyő videók\n- \"(Final Karaoke CDG).zip\": CDG+MP3 formátum régebbi/kereskedelmi karaoke rendszerekhez\n- \"(Final Karaoke TXT).zip\": TXT+MP3 formátum Power Karaoke-hoz\n- stems/*.flac: különböző szétválasztott instrumentális és ének sávok veszteségmentes formátumban\n- lyrics/*.txt dalszövegek különböző forrásokból egyszerű szöveges formátumban",
"fixOffer": "Szólj, ha valami nem tökéletes, és szívesen finomhangolom / kijavítom, vagy ha más formátumban van rá szükséged, valószínűleg át tudom konvertálni neked!",
"feedbackRequest": "Ha van egy perced, nagyon megköszönném a visszajelzésedet (2 percet vesz igénybe):",
"signOff": "Még egyszer köszönöm, és legyen szép napod!\n-Andrew",
"youtubeQueued": "A YouTube feltöltésed sorba van állítva, és automatikusan fel lesz dolgozva. Hamarosan kapsz egy újabb e-mailt a linkkel."
},
"actionLyrics": {
"greeting": "Szia {name}!",
"ready": "A karaoke videód a(z) \"{artist} - {title}\" dalhoz készen áll az ellenőrzésre!",
"instructions": "Rendszerünk leírta és szinkronizálta a dalszöveget, de lehet, hogy szükség van néhány javításra. Kiválaszthatod a kívánt instrumentális sávot is (háttérénekkel vagy anélkül).",
"reviewPrompt": "Kérlek, ellenőrizd a dalszöveget, és válassz egy instrumentális sávot:",
"duration": "Ez általában csak néhány percet vesz igénybe.",
"signOff": "Köszönöm!\n-Andrew"
},
"actionInstrumental": {
"greeting": "Szia {name}!",
"almostDone": "A karaoke videód a(z) \"{artist} - {title}\" dalhoz majdnem kész!",
"instructions": "Szétválasztottuk a hangot különböző verziókra. Kérlek, válaszd ki, melyik instrumentális sávot szeretnéd használni a végső videóhoz.",
"selectPrompt": "Válaszd ki az instrumentális sávot itt:",
"signOff": "Köszönöm!\n-Andrew"
},
"youtubeComplete": {
"greeting": "Szia {name}!",
"greatNews": "Nagyszerű hír! A karaoke videód a(z) \"{artist} - {title}\" dalhoz fel lett töltve a YouTube-ra:",
"delayNote": "Ez a feltöltés rövid ideig késett, amíg a rendszereink más feltöltéseket dolgoztak fel, de most már minden rendben van.",
"signOff": "Köszönöm!\n-Andrew"
}
}
}
}
+338
View File
@@ -0,0 +1,338 @@
{
"auth": {
"unknownService": "Layanan tidak dikenal: {service}",
"invalidCredentials": "Layanan berikut memerlukan otorisasi ulang: {services}",
"validCredentials": "Semua kredensial yang diminta valid",
"youtubeAuthInstructions": "Kunjungi {verification_url} dan masukkan kode: {user_code}",
"youtubeAuthStartFailed": "Gagal memulai otorisasi perangkat YouTube: {error}",
"gdriveLinkInstructions": "Kunjungi {verification_url} dan masukkan kode: {user_code}",
"gdriveAuthStartFailed": "Gagal memulai otorisasi perangkat Google Drive: {error}",
"discordAlertNotConfigured": "Webhook peringatan Discord belum dikonfigurasi"
},
"jobs": {
"created": "Tugas berhasil dibuat. Pemrosesan dimulai.",
"authError": "Kesalahan autentikasi: tidak ada identitas pengguna yang tersedia",
"noDefaultTheme": "Tidak ada tema default yang dikonfigurasi. Silakan hubungi tim dukungan atau tentukan theme_id.",
"notFound": "Tugas tidak ditemukan",
"noPermissionAccess": "Anda tidak memiliki izin untuk mengakses tugas ini",
"noPermissionEdit": "Anda tidak memiliki izin untuk mengedit tugas ini",
"noPermissionDelete": "Anda tidak memiliki izin untuk menghapus tugas ini",
"noPermissionModify": "Anda tidak memiliki izin untuk memodifikasi tugas ini",
"notCompleted": "Hanya tugas yang sudah selesai yang dapat diedit. Status saat ini: {status}",
"alreadyBeingEdited": "Tugas ini sedang diedit (output sebelumnya sudah dihapus)",
"cleanupFailed": "Pembersihan gagal untuk {services}. Tugas tidak dimodifikasi. Silakan coba lagi atau hubungi tim dukungan.",
"reopened": "Trek dibuka kembali untuk diedit. Output sebelumnya telah dihapus.",
"invalidDatetimeFormat": "Format {field} tidak valid: {value}",
"listError": "Kesalahan saat memuat daftar tugas: {error}",
"deleteError": "Kesalahan saat menghapus tugas {job_id}: {error}",
"deletionPreview": "Tambahkan &confirm=true untuk mengeksekusi penghapusan",
"deletionRequiresFilters": "Setidaknya satu filter (environment, client_id, status, created_before) diperlukan",
"bulkDeleteError": "Kesalahan saat menghapus banyak tugas sekaligus: {error}",
"reviewNotReady": "Tugas belum siap untuk ditinjau (status saat ini: {status})",
"correctionsUnavailable": "Data koreksi tidak tersedia",
"audioUnavailable": "Audio tidak tersedia untuk ditinjau",
"reviewCannotStart": "Tidak dapat memulai peninjauan",
"jobNotInReviewState": "Tugas tidak dalam status peninjauan (status saat ini: {status})",
"correctionsProcessing": "Koreksi disimpan. Panggil /complete-review jika sudah selesai.",
"editLogSaveFailed": "Kesalahan saat menyimpan log pengeditan untuk tugas {job_id}: {error}",
"stemsMissing": "Tugas tidak memiliki stem yang diperlukan (instrumental_clean dan/atau backing_vocals)",
"customInstrumentalFailed": "Kesalahan saat membuat instrumental kustom untuk tugas {job_id}: {error}",
"audioProcessingFailed": "Gagal memproses file audio: {error}",
"durationMismatch": "Durasi tidak cocok: file yang diunggah berdurasi {upload_duration} detik tetapi audio asli berdurasi {original_duration} detik. Instrumental harus tepat {original_duration} detik (±0.5 detik).",
"reviewNotInState": "Tugas tidak dalam status peninjauan (status saat ini: {status})",
"noLyricsDetected": "Tidak dapat menyelesaikan peninjauan: tidak ada lirik yang terdeteksi pada audio. Hal ini bisa terjadi jika audio input tidak memiliki vokal (misalnya trek karaoke atau instrumental). Anda dapat kembali dan menempelkan lirik secara manual menggunakan 'Replace All', atau batalkan tugas ini dan coba lagi dengan file audio yang berisi vokal.",
"reviewCompleteStartRendering": "Peninjauan selesai. Rendering video dimulai.",
"reviewCompleteError": "Kesalahan saat menyelesaikan peninjauan untuk tugas {job_id}: {error}",
"instrumentalSelectionRequired": "instrumental_selection diperlukan. Harus 'clean' atau 'with_backing'.",
"invalidInstrumentalSelection": "instrumental_selection tidak valid. Harus salah satu dari: {valid_selections}",
"instrumentalSelected": "Instrumental dipilih. Pembuatan video dimulai.",
"instrumentalSelectionError": "Kesalahan saat memilih instrumental untuk tugas {job_id}: {error}",
"downloadUrlsError": "Kesalahan saat mendapatkan URL unduhan: {error}"
},
"review": {
"jobNotFound": "Tugas tidak ditemukan",
"reviewNotReady": "Tugas belum siap untuk ditinjau (status saat ini: {status})",
"correctionsNotFound": "Data koreksi tidak ditemukan. Pemrosesan lirik mungkin belum selesai.",
"correctionsLoadFailed": "Kesalahan saat memuat koreksi: {error}",
"audioNotFound": "File audio tidak ditemukan",
"audioServeError": "Kesalahan saat menyajikan audio: {error}",
"instrumentalSelectionRequired": "instrumental_selection diperlukan. Harus 'clean' atau 'with_backing'.",
"invalidInstrumentalSelection": "instrumental_selection tidak valid. Harus salah satu dari: {valid_selections}",
"reviewCompletedError": "Kesalahan saat menyelesaikan peninjauan: {error}",
"handlersUpdateNotImplemented": "Pembaruan handler belum diimplementasikan",
"lyricsAddError": "Gagal menambahkan lirik: {error}",
"lyricsAddInvalidRequest": "Permintaan penambahan lirik tidak valid: {error}",
"lyricsSearchError": "Gagal mencari lirik: {error}",
"lyricsSearchInvalidRequest": "Permintaan pencarian lirik tidak valid: {error}",
"lyricsSearchNoResults": "Tidak ada lirik yang cocok ditemukan dari penyedia mana pun",
"previewVideoGenerationError": "Gagal membuat video pratinjau: {error}",
"previewVideoNotFound": "Video pratinjau tidak ditemukan",
"previewVideoStreamError": "Kesalahan saat streaming video pratinjau: {error}",
"annotationSaveError": "Kesalahan saat menyimpan anotasi: {error}",
"waveformGenerationError": "Kesalahan saat membuat data bentuk gelombang: {error}",
"waveformNoAudio": "Tidak ada audio yang tersedia untuk bentuk gelombang",
"sessionSaveError": "Data koreksi diperlukan"
},
"audioSearch": {
"notEnabled": "Pencarian audio tidak diaktifkan untuk tenant ini",
"disabled": "Pencarian audio tidak tersedia",
"downloadError": "Unduhan gagal untuk tugas {job_id}: {error}",
"jobNotFound": "Tugas {job_id} tidak ditemukan",
"noSearchResults": "Tidak ada hasil pencarian yang tersedia",
"invalidSelectionIndex": "Indeks pilihan tidak valid {selection_index}. Rentang yang valid: 0-{max}",
"selectionError": "Kesalahan selama pemilihan audio untuk tugas {job_id}: {error}",
"youtubeDownloadError": "Unduhan YouTube gagal: {error}",
"torrentDownloadError": "Tidak dapat mengunduh dari {source} tanpa layanan flacfetch jarak jauh. Konfigurasikan FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Tidak ada source_id atau remote_search_id yang tersedia untuk unduhan {source}",
"remoteDownloadCompleteNoPath": "Unduhan jarak jauh selesai tetapi tidak ada jalur file yang dikembalikan",
"spotifyDownloadError": "Tidak dapat mengunduh dari Spotify tanpa layanan flacfetch jarak jauh. Konfigurasikan FLACFETCH_API_URL.",
"genericDownloadError": "Jenis sumber tidak dikenal: {source}, mencoba unduhan generik",
"jobNotFoundDuringDownload": "Tugas {job_id} tidak ditemukan selama pengunduhan di latar belakang",
"selectAudioError": "Kesalahan saat memilih audio untuk tugas {job_id}: {error}",
"searchAudioError": "Kesalahan saat mencari audio: {error}",
"searchCreatedSuccessfully": "Tugas dibuat. Mencari audio...",
"autoDownloadStarted": "Hasil terbaik dipilih secara otomatis. Unduhan dimulai..."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
"magicLinkSent": "Jika email ini terdaftar, Anda akan segera menerima tautan masuk.",
"emailServiceNotConfigured": "Layanan email tidak tersedia. Silakan hubungi tim dukungan.",
"emailDomainNotAllowed": "Domain email tidak diizinkan untuk tenant ini",
"invalidToken": "Token tidak valid",
"verifyError": "Verifikasi gagal: {message}",
"magicLinkSuccess": "Berhasil masuk",
"logoutSuccess": "Berhasil keluar",
"userNotFound": "Pengguna tidak ditemukan",
"creditPackagesError": "Kesalahan saat memuat paket kredit: {error}",
"stripeSendError": "Kesalahan saat mengirim tautan checkout Stripe: {error}",
"stripeWebhookProcessingError": "Kesalahan saat memproses webhook Stripe: {error}",
"feedbackSaveError": "Kesalahan saat menyimpan umpan balik: {error}",
"feedbackNotEligible": "Pengguna tidak memenuhi syarat untuk memberikan umpan balik"
},
"fileUpload": {
"invalidTheme": "Tema tidak ditemukan: {theme_id}. Gunakan GET /api/themes untuk melihat daftar tema yang tersedia.",
"uploadSuccess": "File berhasil diunggah. Pemrosesan dimulai.",
"uploadError": "Kesalahan saat mengunggah file: {error}",
"urlDownloadError": "Kesalahan saat mengunduh dari URL: {error}",
"invalidContentType": "Jenis konten tidak valid: {content_type}",
"fileSizeError": "File terlalu besar: {size}. Maksimum: {max_size}",
"invalidFileType": "Jenis file tidak valid: {file_type}",
"multipleAudioFilesNotAllowed": "Hanya satu file audio yang dapat diunggah",
"noAudioFileProvided": "Tidak ada file audio yang disediakan",
"urlCreationSuccess": "Tugas dibuat. URL unggahan dihasilkan.",
"urlCreationError": "Kesalahan saat membuat tugas dengan URL unggahan: {error}",
"uploadsCompleteSuccess": "Unggahan selesai. Pemrosesan dimulai.",
"uploadsCompleteError": "Kesalahan saat menyelesaikan unggahan: {error}",
"noUploadedFiles": "Tidak ada file unggahan yang ditentukan",
"styleUploadUrlsSuccess": "URL unggahan gaya dihasilkan.",
"styleUploadsCompleteSuccess": "File gaya diperbarui. Pemrosesan dimulai ulang.",
"styleUploadsCompleteError": "Kesalahan saat menyelesaikan unggahan gaya: {error}"
},
"catalog": {
"rateLimitExceeded": "Batas permintaan terlampaui. Maksimum {max_requests} permintaan katalog per menit.",
"catalogSearchError": "Kesalahan saat mencari katalog: {error}",
"communityCheckError": "Kesalahan saat memeriksa versi komunitas: {error}"
},
"themes": {
"themesLoadError": "Gagal memuat tema",
"themeNotFound": "Tema tidak ditemukan: {theme_id}",
"themeLoadError": "Gagal memuat tema",
"previewNotAvailable": "Tidak ada pratinjau yang tersedia untuk tema: {theme_id}",
"previewLoadError": "Gagal memuat pratinjau tema",
"youtubeDescriptionNotFound": "Tema tidak ditemukan: {theme_id}",
"youtubeDescriptionLoadError": "Gagal memuat deskripsi YouTube"
},
"tenant": {
"assetNotFound": "Aset tidak ditemukan"
},
"push": {
"disabled": "Notifikasi push tidak diaktifkan",
"userEmailNotAvailable": "Email pengguna tidak tersedia",
"missingEncryptionKeys": "Kunci yang diperlukan hilang (p256dh, auth)",
"subscriptionSaveFailed": "Gagal menyimpan langganan",
"subscriptionRegistered": "Langganan push berhasil didaftarkan",
"subscriptionNotFound": "Langganan dihapus (atau tidak ditemukan)",
"subscriptionRemoved": "Langganan push berhasil dihapus",
"testNotificationSent": "Notifikasi pengujian dikirim ke {sent_count} perangkat"
},
"pushNotifications": {
"reviewLyricsTitle": "Tinjau Lirik",
"reviewLyricsBody": "\"{title}\" oleh {artist} memerlukan peninjauan lirik",
"selectInstrumentalTitle": "Pilih Instrumental",
"selectInstrumentalBody": "\"{title}\" oleh {artist} memerlukan pemilihan instrumental",
"videoReadyTitle": "Video Siap!",
"videoReadyBody": "Video karaoke Anda untuk \"{title}\" oleh {artist} siap diunduh"
},
"admin": {
"invalidDomainFormat": "Format domain tidak valid",
"domainAddedToBl": "Domain '{domain}' ditambahkan ke daftar blokir domain sekali pakai",
"domainNotFoundInBl": "Domain tidak ditemukan di daftar blokir",
"domainRemovedFromBl": "Domain '{domain}' dihapus dari daftar blokir domain sekali pakai",
"domainAddedToAllowlist": "Domain '{domain}' ditambahkan ke daftar izin",
"domainNotFoundInAllowlist": "Domain tidak ditemukan di daftar izin",
"domainRemovedFromAllowlist": "Domain '{domain}' dihapus dari daftar izin",
"syncComplete": "Berhasil menyinkronkan {external_count} domain eksternal ({added} ditambahkan, {removed} dihapus)",
"invalidEmailFormat": "Format email tidak valid",
"emailAddedToBl": "Email '{email}' ditambahkan ke daftar email yang diblokir",
"emailNotFoundInBl": "Email tidak ditemukan di daftar blokir",
"emailRemovedFromBl": "Email '{email}' dihapus dari daftar email yang diblokir",
"invalidIPAddress": "Alamat IP tidak valid",
"ipAddedToBl": "IP '{ip_address}' ditambahkan ke daftar IP yang diblokir",
"ipNotFoundInBl": "IP tidak ditemukan di daftar blokir",
"ipRemovedFromBl": "IP '{ip_address}' dihapus dari daftar IP yang diblokir",
"youtubeUploadNotFound": "Unggahan tidak ditemukan atau tidak dalam status dapat dicoba lagi untuk tugas {job_id}",
"youtubeUploadQueuedForRetry": "Unggahan YouTube untuk tugas {job_id} masuk antrean untuk dicoba lagi",
"youtubeQueueProcessingStarted": "Pemrosesan antrean YouTube dimulai di latar belakang"
},
"rateLimits": {
"configNotFound": "Konfigurasi batas permintaan tidak ditemukan: {config_id}",
"configUpdateError": "Kesalahan saat memperbarui konfigurasi batas permintaan: {error}"
},
"errors": {
"insufficientCredits": "Kredit tidak cukup untuk operasi ini",
"insufficientCreditsBuyUrl": "/#pricing"
},
"emails": {
"magicLink": {
"subject": "Masuk ke {brand_name}",
"greeting": "Halo,",
"signInPrompt": "Klik tombol di bawah ini untuk masuk ke {brand_name}:",
"signInButton": "Masuk",
"expiryWarning": "Tautan ini kedaluwarsa dalam 15 menit dan hanya dapat digunakan satu kali.",
"fallbackLink": "Jika tombol tidak berfungsi, salin dan tempel tautan ini ke browser Anda:",
"ignoreNote": "Jika Anda tidak meminta email ini, Anda dapat mengabaikannya dengan aman."
},
"welcome": {
"subject": "Selamat datang di Nomad Karaoke!",
"welcomeGreeting": "Selamat datang di Nomad Karaoke!",
"turnAnySong": "Ubah lagu apa pun menjadi video karaoke profesional dalam hitungan menit.",
"freeCreditsLabel": "Kredit Gratis",
"freeCreditsNote": "Setiap kredit membuat satu video karaoke profesional",
"howItWorks": "Begini cara kerjanya:",
"step1Title": "1. Cari lagu",
"step1Desc": "Masukkan artis dan judul, dan kami akan menemukan audio berkualitas tinggi.",
"step2Title": "2. Sistem kami bekerja secara ajaib",
"step2Desc": "Kami memisahkan vokal, mentranskripsi lirik, dan menyinkronkan semuanya dengan sempurna.",
"step3Title": "3. Tinjau & sesuaikan",
"step3Desc": "Sempurnakan lirik jika perlu, pilih instrumental Anda.",
"step4Title": "4. Dapatkan video Anda",
"step4Desc": "Unduh video karaoke 4K Anda atau unggah langsung ke YouTube.",
"feedbackBonus": "Selesaikan 2 video dan dapatkan 2 kredit gratis lagi dengan memberikan umpan balik Anda!",
"getStartedButton": "Mulai"
},
"creditsAdded": {
"subject": "{credits} kredit ditambahkan ke akun Nomad Karaoke Anda",
"greatNews": "Kabar baik!",
"creditsAddedMessage": "{credits} kredit telah ditambahkan ke akun Anda.",
"yourBalance": "Saldo Anda:",
"credits": "kredit",
"eachCreditLets": "Setiap kredit memungkinkan Anda membuat satu video karaoke profesional dengan:",
"featureVocalSeparation": "Pemisahan vokal/instrumental bertenaga AI",
"featureLyrics": "Lirik yang disinkronkan dengan pengaturan waktu tingkat kata",
"feature4k": "Output video 4K",
"featureYoutube": "Unggahan YouTube",
"createButton": "Buat Karaoke Sekarang"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (Video karaoke Anda sudah siap!)",
"subject": "{artist} - {title} (Video karaoke Anda sudah siap!)",
"subjectFallback": "Video karaoke Anda sudah siap!"
},
"youtubeUpload": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (Unggahan YouTube siap!)",
"subject": "{artist} - {title} (Unggahan YouTube siap!)",
"subjectFallback": "Unggahan YouTube Anda sudah siap!"
},
"actionReminder": {
"lyricsSubject": "Tindakan diperlukan: Tinjau lirik untuk {artist} - {title}",
"lyricsSubjectFallback": "Tindakan diperlukan: Tinjau lirik",
"instrumentalSubject": "Tindakan diperlukan: Pilih instrumental untuk {artist} - {title}",
"instrumentalSubjectFallback": "Tindakan diperlukan: Pilih instrumental",
"audioEditSubject": "Tindakan diperlukan untuk {artist} - {title}",
"audioEditSubjectFallback": "Tindakan diperlukan",
"alertHeading": "Video karaoke Anda memerlukan masukan dari Anda!"
},
"reviewReminder": {
"subject": "Pengingat: Video karaoke Anda menunggu untuk ditinjau — {artist} - {title}",
"subjectFallback": "Pengingat: Video karaoke Anda menunggu untuk ditinjau",
"alertHeading": "Video karaoke Anda menunggu Anda!",
"reminderIntro": "Sekadar pengingat ramah bahwa video karaoke Anda{song_name} siap untuk ditinjau.",
"reviewButton": "Tinjau Video Anda",
"reviewInstructions": "Selama peninjauan, Anda dapat memeriksa apakah liriknya sudah benar dan memilih trek instrumental pilihan Anda. Biasanya hanya butuh beberapa menit!",
"helpOffer": "Jika Anda mengalami kesulitan dengan proses peninjauan, balas saja email ini dan saya akan dengan senang hati membantu Anda.",
"expiryWarning": "Harap diperhatikan: jika peninjauan tidak diselesaikan dalam 24 jam ke depan, tugas akan otomatis kedaluwarsa dan kredit Anda akan dikembalikan."
},
"reviewExpired": {
"subject": "Video karaoke Anda telah kedaluwarsa — {artist} - {title}",
"subjectFallback": "Video karaoke Anda telah kedaluwarsa",
"cancelNotice": "Video karaoke Anda{song_name} telah otomatis dibatalkan karena peninjauan tidak diselesaikan dalam waktu 48 jam.",
"refundNotice": "Jangan khawatir — kredit Anda telah dikembalikan! Saldo Anda saat ini adalah {credits_balance} {credits_word}.",
"creditSingular": "kredit",
"creditPlural": "kredit",
"createNewPrompt": "Anda dapat membuat video karaoke baru kapan saja menggunakan kredit Anda:",
"createButton": "Buat Video Baru",
"helpOffer": "Jika Anda mengalami kesulitan dengan proses peninjauan atau butuh bantuan, balas saja email ini — saya akan dengan senang hati membantu!"
},
"creditDenied": {
"subject": "Tentang kredit gratis Nomad Karaoke Anda",
"greeting": "Halo,",
"thankYou": "Terima kasih telah mendaftar di Nomad Karaoke!",
"deniedMessage": "Sayangnya, kami tidak dapat memberikan {credit_type} gratis Anda kali ini. Sistem kami mendeteksi pola yang menunjukkan bahwa ini mungkin bukan akun pertama Anda bersama kami, dan setiap tugas pembuatan karaoke menghabiskan biaya nyata bagi kami dalam komputasi awan dan biaya API.",
"mistakeNote": "Kami sangat mengerti jika ini adalah sebuah kesalahan! Jika Anda benar-benar pengguna baru, silakan balas email ini dan beri tahu Andrew (pendiri). Dia membangun layanan ini dan dengan senang hati akan memberikan Anda beberapa kredit gratis untuk mencobanya — dia hanya meminta agar Anda memberikan umpan balik yang jujur tentang pengalaman tersebut sebagai imbalannya.",
"buyPrompt": "Jika Anda ingin segera memulai, Anda juga dapat membeli kredit:",
"buyButton": "Beli Kredit",
"costNote": "Kami menjaga biaya tetap rendah agar kami dapat menawarkan layanan dengan harga terjangkau, yang berarti kami harus berhati-hati terhadap penyalahgunaan kredit gratis. Terima kasih atas pengertiannya!",
"welcomeCredits": "kredit selamat datang",
"feedbackCredits": "kredit bonus umpan balik"
},
"madeForYouConfirmation": {
"subject": "Pesanan Dikonfirmasi: {artist} - {title} | Nomad Karaoke",
"thankYou": "Terima Kasih atas Pesanan Anda!",
"orderDetails": "Detail Pesanan",
"orderId": "ID Pesanan:",
"artist": "Artis:",
"title": "Judul:",
"yourNotes": "Catatan Anda:",
"deliveryTime": "Tim kami akan membuat video karaoke kustom Anda dalam waktu {hours} jam.",
"deliveryNotice": "Anda akan menerima email berisi tautan unduhan segera setelah video Anda siap.",
"noAction": "Tidak ada tindakan yang diperlukan — duduk manis dan kami akan mengurus semuanya!"
},
"shared": {
"footerHelp": "Jika ada yang kurang sempurna, balas saja email ini dan saya akan memperbaikinya!"
},
"templates": {
"jobCompletion": {
"greeting": "Halo {name},",
"thanks": "Terima kasih atas pesanan Anda!",
"youtubeLink": "Berikut adalah tautan untuk video karaoke yang dipublikasikan ke YouTube:",
"dropboxIntro": "Berikut adalah folder Dropbox dengan semua file yang sudah selesai dan file sumber, termasuk:",
"fileList": "- \"(Final Karaoke Lossless).mkv\": video karaoke gabungan dalam 4K H264 dengan audio FLAC lossless\n- \"(Final Karaoke).mp4\": video karaoke gabungan dengan layar judul/akhir dalam 4K H264/AAC\n- \"(Final Karaoke 720p).mp4\": video karaoke gabungan dalam 720p H264/AAC (file lebih kecil untuk sistem lama)\n- \"(With Vocals).mp4\": video bernyanyi bersama dalam 4K H264/AAC dengan vokal asli\n- \"(Karaoke).mov\": output video karaoke dari MidiCo (tanpa layar judul/akhir)\n- \"(Title).mov\"/\"(End).mov\": video kartu judul dan layar akhir\n- \"(Final Karaoke CDG).zip\": format CDG+MP3 untuk sistem karaoke lama/komersial\n- \"(Final Karaoke TXT).zip\": format TXT+MP3 untuk Power Karaoke\n- stems/*.flac: berbagai stem audio instrumental dan vokal yang dipisahkan dalam format lossless\n- lyrics/*.txt lirik lagu dari berbagai sumber dalam format teks biasa",
"fixOffer": "Beri tahu saya jika ada yang kurang sempurna dan saya akan dengan senang hati menyesuaikan / memperbaikinya, atau jika Anda membutuhkannya dalam format lain, saya mungkin dapat mengonversinya untuk Anda!",
"feedbackRequest": "Jika Anda punya waktu, saya akan sangat menghargai umpan balik Anda (hanya butuh 2 menit):",
"signOff": "Terima kasih sekali lagi dan semoga hari Anda menyenangkan!\n-Andrew",
"youtubeQueued": "Unggahan YouTube Anda masuk antrean dan akan diproses secara otomatis. Anda akan segera menerima email tindak lanjut berisi tautannya."
},
"actionLyrics": {
"greeting": "Halo {name},",
"ready": "Video karaoke Anda untuk \"{artist} - {title}\" siap untuk ditinjau!",
"instructions": "Sistem kami telah mentranskripsi dan menyinkronkan lirik, tetapi mungkin memerlukan beberapa koreksi. Anda juga dapat memilih trek instrumental pilihan Anda (dengan atau tanpa vokal latar).",
"reviewPrompt": "Silakan tinjau lirik Anda dan pilih instrumental:",
"duration": "Ini biasanya hanya memakan waktu beberapa menit.",
"signOff": "Terima kasih!\n-Andrew"
},
"actionInstrumental": {
"greeting": "Halo {name},",
"almostDone": "Video karaoke Anda untuk \"{artist} - {title}\" hampir selesai!",
"instructions": "Kami telah memisahkan audio ke dalam versi yang berbeda. Silakan pilih trek instrumental mana yang ingin Anda gunakan untuk video akhir.",
"selectPrompt": "Pilih instrumental Anda di sini:",
"signOff": "Terima kasih!\n-Andrew"
},
"youtubeComplete": {
"greeting": "Halo {name},",
"greatNews": "Kabar baik! Video karaoke Anda untuk \"{artist} - {title}\" telah diunggah ke YouTube:",
"delayNote": "Unggahan ini sempat tertunda sebentar saat sistem kami memproses unggahan lain, tetapi sekarang semuanya sudah siap.",
"signOff": "Terima kasih!\n-Andrew"
}
}
}
}
+338
View File
@@ -0,0 +1,338 @@
{
"auth": {
"unknownService": "Servizio sconosciuto: {service}",
"invalidCredentials": "I seguenti servizi richiedono una nuova autorizzazione: {services}",
"validCredentials": "Tutte le credenziali richieste sono valide",
"youtubeAuthInstructions": "Visita {verification_url} e inserisci il codice: {user_code}",
"youtubeAuthStartFailed": "Impossibile avviare l'autenticazione del dispositivo YouTube: {error}",
"gdriveLinkInstructions": "Visita {verification_url} e inserisci il codice: {user_code}",
"gdriveAuthStartFailed": "Impossibile avviare l'autenticazione del dispositivo Google Drive: {error}",
"discordAlertNotConfigured": "Webhook di avviso Discord non configurato"
},
"jobs": {
"created": "Lavoro creato con successo. Elaborazione avviata.",
"authError": "Errore di autenticazione: nessuna identità utente disponibile",
"noDefaultTheme": "Nessun tema predefinito configurato. Contatta il supporto o specifica un theme_id.",
"notFound": "Lavoro non trovato",
"noPermissionAccess": "Non hai i permessi per accedere a questo lavoro",
"noPermissionEdit": "Non hai i permessi per modificare questo lavoro",
"noPermissionDelete": "Non hai i permessi per eliminare questo lavoro",
"noPermissionModify": "Non hai i permessi per modificare questo lavoro",
"notCompleted": "Solo i lavori completati possono essere modificati. Stato attuale: {status}",
"alreadyBeingEdited": "Questo lavoro è già in fase di modifica (gli output sono già stati eliminati)",
"cleanupFailed": "Pulizia non riuscita per {services}. Lavoro non modificato. Riprova o contatta il supporto.",
"reopened": "Traccia riaperta per la modifica. Gli output precedenti sono stati rimossi.",
"invalidDatetimeFormat": "Formato {field} non valido: {value}",
"listError": "Errore durante il recupero dei lavori: {error}",
"deleteError": "Errore durante l'eliminazione del lavoro {job_id}: {error}",
"deletionPreview": "Aggiungi &confirm=true per eseguire l'eliminazione",
"deletionRequiresFilters": "È richiesto almeno un filtro (environment, client_id, status, created_before)",
"bulkDeleteError": "Errore durante l'eliminazione in blocco dei lavori: {error}",
"reviewNotReady": "Lavoro non pronto per la revisione (stato attuale: {status})",
"correctionsUnavailable": "Dati delle correzioni non disponibili",
"audioUnavailable": "Audio non disponibile per la revisione",
"reviewCannotStart": "Impossibile avviare la revisione",
"jobNotInReviewState": "Lavoro non in stato di revisione (stato attuale: {status})",
"correctionsProcessing": "Correzioni salvate. Chiama /complete-review quando hai finito.",
"editLogSaveFailed": "Errore durante il salvataggio del registro delle modifiche per il lavoro {job_id}: {error}",
"stemsMissing": "Mancano gli stem richiesti per il lavoro (instrumental_clean e/o backing_vocals)",
"customInstrumentalFailed": "Errore durante la creazione della strumentale personalizzata per il lavoro {job_id}: {error}",
"audioProcessingFailed": "Impossibile elaborare il file audio: {error}",
"durationMismatch": "Mancata corrispondenza della durata: il file caricato dura {upload_duration}s ma l'audio originale dura {original_duration}s. La strumentale deve durare esattamente {original_duration}s (±0.5s).",
"reviewNotInState": "Lavoro non in stato di revisione (stato attuale: {status})",
"noLyricsDetected": "Impossibile completare la revisione: non è stato rilevato alcun testo nell'audio. Questo può accadere quando l'audio di input non ha voci (es. una traccia karaoke o strumentale). Puoi tornare indietro e incollare il testo manualmente usando 'Sostituisci tutto', oppure annullare questo lavoro e riprovare con un file audio che contiene voci.",
"reviewCompleteStartRendering": "Revisione completata. Rendering del video avviato.",
"reviewCompleteError": "Errore durante il completamento della revisione per il lavoro {job_id}: {error}",
"instrumentalSelectionRequired": "instrumental_selection è richiesto. Deve essere 'clean' o 'with_backing'.",
"invalidInstrumentalSelection": "instrumental_selection non valido. Deve essere uno tra: {valid_selections}",
"instrumentalSelected": "Strumentale selezionata. Generazione del video avviata.",
"instrumentalSelectionError": "Errore durante la selezione della strumentale per il lavoro {job_id}: {error}",
"downloadUrlsError": "Errore durante il recupero degli URL di download: {error}"
},
"review": {
"jobNotFound": "Lavoro non trovato",
"reviewNotReady": "Lavoro non pronto per la revisione (stato attuale: {status})",
"correctionsNotFound": "Dati delle correzioni non trovati. L'elaborazione del testo potrebbe non essere completa.",
"correctionsLoadFailed": "Errore durante il caricamento delle correzioni: {error}",
"audioNotFound": "File audio non trovato",
"audioServeError": "Errore durante la fornitura dell'audio: {error}",
"instrumentalSelectionRequired": "instrumental_selection è richiesto. Deve essere 'clean' o 'with_backing'.",
"invalidInstrumentalSelection": "instrumental_selection non valido. Deve essere uno tra: {valid_selections}",
"reviewCompletedError": "Errore durante il completamento della revisione: {error}",
"handlersUpdateNotImplemented": "Aggiornamenti degli handler non ancora implementati",
"lyricsAddError": "Impossibile aggiungere il testo: {error}",
"lyricsAddInvalidRequest": "Richiesta di aggiunta testo non valida: {error}",
"lyricsSearchError": "Impossibile cercare il testo: {error}",
"lyricsSearchInvalidRequest": "Richiesta di ricerca testo non valida: {error}",
"lyricsSearchNoResults": "Nessun testo corrispondente trovato da alcun provider",
"previewVideoGenerationError": "Impossibile generare il video di anteprima: {error}",
"previewVideoNotFound": "Video di anteprima non trovato",
"previewVideoStreamError": "Errore durante lo streaming del video di anteprima: {error}",
"annotationSaveError": "Errore durante il salvataggio delle annotazioni: {error}",
"waveformGenerationError": "Errore durante la generazione dei dati della forma d'onda: {error}",
"waveformNoAudio": "Nessun audio disponibile per la forma d'onda",
"sessionSaveError": "I dati di correzione sono richiesti"
},
"audioSearch": {
"notEnabled": "La ricerca audio non è abilitata per questo tenant",
"disabled": "La ricerca audio non è disponibile",
"downloadError": "Download non riuscito per il lavoro {job_id}: {error}",
"jobNotFound": "Lavoro {job_id} non trovato",
"noSearchResults": "Nessun risultato di ricerca disponibile",
"invalidSelectionIndex": "Indice di selezione non valido {selection_index}. Intervallo valido: 0-{max}",
"selectionError": "Errore durante la selezione dell'audio per il lavoro {job_id}: {error}",
"youtubeDownloadError": "Download da YouTube non riuscito: {error}",
"torrentDownloadError": "Impossibile scaricare da {source} senza il servizio flacfetch remoto. Configura FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Nessun source_id o remote_search_id disponibile per il download da {source}",
"remoteDownloadCompleteNoPath": "Download remoto completato ma non è stato restituito alcun percorso file",
"spotifyDownloadError": "Impossibile scaricare da Spotify senza il servizio flacfetch remoto. Configura FLACFETCH_API_URL.",
"genericDownloadError": "Tipo di origine sconosciuto: {source}, tentativo di download generico",
"jobNotFoundDuringDownload": "Lavoro {job_id} non trovato durante il download in background",
"selectAudioError": "Errore durante la selezione dell'audio per il lavoro {job_id}: {error}",
"searchAudioError": "Errore durante la ricerca dell'audio: {error}",
"searchCreatedSuccessfully": "Lavoro creato. Ricerca dell'audio in corso...",
"autoDownloadStarted": "Miglior risultato selezionato automaticamente. Avvio del download..."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
"magicLinkSent": "Se questa email è registrata, riceverai a breve un link di accesso.",
"emailServiceNotConfigured": "Il servizio email non è disponibile. Contatta il supporto.",
"emailDomainNotAllowed": "Dominio email non consentito per questo tenant",
"invalidToken": "Token non valido",
"verifyError": "Verifica non riuscita: {message}",
"magicLinkSuccess": "Accesso effettuato con successo",
"logoutSuccess": "Disconnessione effettuata con successo",
"userNotFound": "Utente non trovato",
"creditPackagesError": "Errore durante il caricamento dei pacchetti di crediti: {error}",
"stripeSendError": "Errore durante l'invio del link di checkout Stripe: {error}",
"stripeWebhookProcessingError": "Errore durante l'elaborazione del webhook Stripe: {error}",
"feedbackSaveError": "Errore durante il salvataggio del feedback: {error}",
"feedbackNotEligible": "Utente non idoneo per il feedback"
},
"fileUpload": {
"invalidTheme": "Tema non trovato: {theme_id}. Usa GET /api/themes per elencare i temi disponibili.",
"uploadSuccess": "File caricato con successo. Elaborazione avviata.",
"uploadError": "Errore durante il caricamento del file: {error}",
"urlDownloadError": "Errore durante il download dall'URL: {error}",
"invalidContentType": "Tipo di contenuto non valido: {content_type}",
"fileSizeError": "Il file è troppo grande: {size}. Massimo: {max_size}",
"invalidFileType": "Tipo di file non valido: {file_type}",
"multipleAudioFilesNotAllowed": "È possibile caricare solo un file audio",
"noAudioFileProvided": "Nessun file audio fornito",
"urlCreationSuccess": "Lavoro creato. URL di caricamento generati.",
"urlCreationError": "Errore durante la creazione del lavoro con gli URL di caricamento: {error}",
"uploadsCompleteSuccess": "Caricamenti completati. Elaborazione avviata.",
"uploadsCompleteError": "Errore durante il completamento dei caricamenti: {error}",
"noUploadedFiles": "Nessun file caricato specificato",
"styleUploadUrlsSuccess": "URL di caricamento dello stile generati.",
"styleUploadsCompleteSuccess": "File di stile aggiornati. Elaborazione riavviata.",
"styleUploadsCompleteError": "Errore durante il completamento dei caricamenti di stile: {error}"
},
"catalog": {
"rateLimitExceeded": "Limite di frequenza superato. Massimo {max_requests} richieste di catalogo al minuto.",
"catalogSearchError": "Errore durante la ricerca nel catalogo: {error}",
"communityCheckError": "Errore durante il controllo delle versioni della community: {error}"
},
"themes": {
"themesLoadError": "Impossibile caricare i temi",
"themeNotFound": "Tema non trovato: {theme_id}",
"themeLoadError": "Impossibile caricare il tema",
"previewNotAvailable": "Nessuna anteprima disponibile per il tema: {theme_id}",
"previewLoadError": "Impossibile caricare l'anteprima del tema",
"youtubeDescriptionNotFound": "Tema non trovato: {theme_id}",
"youtubeDescriptionLoadError": "Impossibile caricare la descrizione di YouTube"
},
"tenant": {
"assetNotFound": "Asset non trovato"
},
"push": {
"disabled": "Le notifiche push non sono abilitate",
"userEmailNotAvailable": "Email dell'utente non disponibile",
"missingEncryptionKeys": "Chiavi richieste mancanti (p256dh, auth)",
"subscriptionSaveFailed": "Impossibile salvare l'iscrizione",
"subscriptionRegistered": "Iscrizione push registrata con successo",
"subscriptionNotFound": "Iscrizione rimossa (o non trovata)",
"subscriptionRemoved": "Iscrizione push rimossa con successo",
"testNotificationSent": "Notifica di test inviata a {sent_count} dispositivo/i"
},
"pushNotifications": {
"reviewLyricsTitle": "Revisiona il testo",
"reviewLyricsBody": "\"{title}\" di {artist} richiede la revisione del testo",
"selectInstrumentalTitle": "Seleziona la strumentale",
"selectInstrumentalBody": "\"{title}\" di {artist} richiede la selezione della strumentale",
"videoReadyTitle": "Video pronto!",
"videoReadyBody": "Il tuo video karaoke per \"{title}\" di {artist} è pronto per il download"
},
"admin": {
"invalidDomainFormat": "Formato del dominio non valido",
"domainAddedToBl": "Dominio '{domain}' aggiunto alla blocklist dei domini usa e getta",
"domainNotFoundInBl": "Dominio non trovato nella blocklist",
"domainRemovedFromBl": "Dominio '{domain}' rimosso dalla blocklist dei domini usa e getta",
"domainAddedToAllowlist": "Dominio '{domain}' aggiunto all'allowlist",
"domainNotFoundInAllowlist": "Dominio non trovato nell'allowlist",
"domainRemovedFromAllowlist": "Dominio '{domain}' rimosso dall'allowlist",
"syncComplete": "Sincronizzati {external_count} domini esterni ({added} aggiunti, {removed} rimossi)",
"invalidEmailFormat": "Formato email non valido",
"emailAddedToBl": "Email '{email}' aggiunta alla lista delle email bloccate",
"emailNotFoundInBl": "Email non trovata nella blocklist",
"emailRemovedFromBl": "Email '{email}' rimossa dalla lista delle email bloccate",
"invalidIPAddress": "Indirizzo IP non valido",
"ipAddedToBl": "IP '{ip_address}' aggiunto alla lista degli IP bloccati",
"ipNotFoundInBl": "IP non trovato nella blocklist",
"ipRemovedFromBl": "IP '{ip_address}' rimosso dalla lista degli IP bloccati",
"youtubeUploadNotFound": "Caricamento non trovato o non in uno stato in cui può essere riprovato per il lavoro {job_id}",
"youtubeUploadQueuedForRetry": "Caricamento su YouTube per il lavoro {job_id} in coda per un nuovo tentativo",
"youtubeQueueProcessingStarted": "Elaborazione della coda di YouTube avviata in background"
},
"rateLimits": {
"configNotFound": "Configurazione del limite di frequenza non trovata: {config_id}",
"configUpdateError": "Errore durante l'aggiornamento della configurazione del limite di frequenza: {error}"
},
"errors": {
"insufficientCredits": "Crediti insufficienti per questa operazione",
"insufficientCreditsBuyUrl": "/#pricing"
},
"emails": {
"magicLink": {
"subject": "Accedi a {brand_name}",
"greeting": "Ciao,",
"signInPrompt": "Clicca sul pulsante qui sotto per accedere a {brand_name}:",
"signInButton": "Accedi",
"expiryWarning": "Questo link scade tra 15 minuti e può essere utilizzato una sola volta.",
"fallbackLink": "Se il pulsante non funziona, copia e incolla questo link nel tuo browser:",
"ignoreNote": "Se non hai richiesto questa email, puoi tranquillamente ignorarla."
},
"welcome": {
"subject": "Benvenuto su Nomad Karaoke!",
"welcomeGreeting": "Benvenuto su Nomad Karaoke!",
"turnAnySong": "Trasforma qualsiasi canzone in un video karaoke professionale in pochi minuti.",
"freeCreditsLabel": "Crediti gratuiti",
"freeCreditsNote": "Ogni credito crea un video karaoke professionale",
"howItWorks": "Ecco come funziona:",
"step1Title": "1. Cerca una canzone",
"step1Desc": "Inserisci l'artista e il titolo, e noi troveremo un audio di alta qualità.",
"step2Title": "2. Il nostro sistema fa la sua magia",
"step2Desc": "Separiamo le voci, trascriviamo il testo e sincronizziamo tutto alla perfezione.",
"step3Title": "3. Revisiona e personalizza",
"step3Desc": "Perfeziona il testo se necessario, scegli la tua strumentale.",
"step4Title": "4. Ottieni il tuo video",
"step4Desc": "Scarica il tuo video karaoke in 4K o caricalo direttamente su YouTube.",
"feedbackBonus": "Completa 2 video e guadagna altri 2 crediti gratuiti condividendo il tuo feedback!",
"getStartedButton": "Inizia"
},
"creditsAdded": {
"subject": "{credits} crediti aggiunti al tuo account Nomad Karaoke",
"greatNews": "Ottime notizie!",
"creditsAddedMessage": "{credits} crediti sono stati aggiunti al tuo account.",
"yourBalance": "Il tuo saldo:",
"credits": "crediti",
"eachCreditLets": "Ogni credito ti permette di creare un video karaoke professionale con:",
"featureVocalSeparation": "Separazione voce/strumentale basata sull'IA",
"featureLyrics": "Testo sincronizzato con tempismo a livello di parola",
"feature4k": "Output video in 4K",
"featureYoutube": "Caricamento su YouTube",
"createButton": "Crea Karaoke Ora"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (Il tuo video karaoke è pronto!)",
"subject": "{artist} - {title} (Il tuo video karaoke è pronto!)",
"subjectFallback": "Il tuo video karaoke è pronto!"
},
"youtubeUpload": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (Caricamento su YouTube pronto!)",
"subject": "{artist} - {title} (Caricamento su YouTube pronto!)",
"subjectFallback": "Il tuo caricamento su YouTube è pronto!"
},
"actionReminder": {
"lyricsSubject": "Azione richiesta: Revisiona il testo per {artist} - {title}",
"lyricsSubjectFallback": "Azione richiesta: Revisiona il testo",
"instrumentalSubject": "Azione richiesta: Seleziona la strumentale per {artist} - {title}",
"instrumentalSubjectFallback": "Azione richiesta: Seleziona la strumentale",
"audioEditSubject": "Azione richiesta per {artist} - {title}",
"audioEditSubjectFallback": "Azione richiesta",
"alertHeading": "Il tuo video karaoke ha bisogno del tuo input!"
},
"reviewReminder": {
"subject": "Promemoria: Il tuo video karaoke è in attesa di revisione — {artist} - {title}",
"subjectFallback": "Promemoria: Il tuo video karaoke è in attesa di revisione",
"alertHeading": "Il tuo video karaoke ti sta aspettando!",
"reminderIntro": "Solo un promemoria amichevole che il tuo video karaoke{song_name} è pronto per la revisione.",
"reviewButton": "Revisiona il tuo video",
"reviewInstructions": "Durante la revisione, puoi controllare che il testo sia corretto e scegliere la tua traccia strumentale preferita. Di solito ci vogliono solo pochi minuti!",
"helpOffer": "Se hai problemi con il processo di revisione, rispondi a questa email e sarò felice di aiutarti.",
"expiryWarning": "Nota bene: se la revisione non viene completata entro le prossime 24 ore, il lavoro scadrà automaticamente e il tuo credito verrà rimborsato."
},
"reviewExpired": {
"subject": "Il tuo video karaoke è scaduto — {artist} - {title}",
"subjectFallback": "Il tuo video karaoke è scaduto",
"cancelNotice": "Il tuo video karaoke{song_name} è stato annullato automaticamente perché la revisione non è stata completata entro 48 ore.",
"refundNotice": "Non preoccuparti — il tuo credito è stato rimborsato! Il tuo saldo attuale è di {credits_balance} {credits_word}.",
"creditSingular": "credito",
"creditPlural": "crediti",
"createNewPrompt": "Puoi creare un nuovo video karaoke in qualsiasi momento usando i tuoi crediti:",
"createButton": "Crea Nuovo Video",
"helpOffer": "Se hai avuto problemi con il processo di revisione o hai bisogno di aiuto, rispondi a questa email — mi farebbe piacere aiutarti!"
},
"creditDenied": {
"subject": "Riguardo ai tuoi crediti gratuiti Nomad Karaoke",
"greeting": "Ciao,",
"thankYou": "Grazie per esserti registrato su Nomad Karaoke!",
"deniedMessage": "Purtroppo, questa volta non siamo riusciti a concederti i tuoi {credit_type} gratuiti. Il nostro sistema ha rilevato schemi che suggeriscono che questo potrebbe non essere il tuo primo account con noi, e ogni lavoro di generazione karaoke ci costa soldi veri in cloud computing e tariffe API.",
"mistakeNote": "Capiamo perfettamente se si tratta di un errore! Se sei un vero nuovo utente, rispondi semplicemente a questa email e fallo sapere ad Andrew (il fondatore). Ha costruito questo servizio ed è felice di concederti dei crediti gratuiti per provarlo — ti chiede solo di fornire un feedback onesto sull'esperienza in cambio.",
"buyPrompt": "Se vuoi iniziare subito, puoi anche acquistare dei crediti:",
"buyButton": "Acquista Crediti",
"costNote": "Manteniamo i costi bassi per poter offrire il servizio a prezzi accessibili, il che significa che dobbiamo stare attenti agli abusi dei crediti gratuiti. Grazie per la comprensione!",
"welcomeCredits": "crediti di benvenuto",
"feedbackCredits": "crediti bonus per il feedback"
},
"madeForYouConfirmation": {
"subject": "Ordine Confermato: {artist} - {title} | Nomad Karaoke",
"thankYou": "Grazie per il tuo ordine!",
"orderDetails": "Dettagli dell'Ordine",
"orderId": "ID Ordine:",
"artist": "Artista:",
"title": "Titolo:",
"yourNotes": "Le tue note:",
"deliveryTime": "Il nostro team creerà il tuo video karaoke personalizzato entro {hours} ore.",
"deliveryNotice": "Riceverai un'email con i link per il download non appena il tuo video sarà pronto.",
"noAction": "Nessuna azione richiesta — rilassati e ci occuperemo di tutto noi!"
},
"shared": {
"footerHelp": "Se qualcosa non è perfetto, rispondi a questa email e lo sistemerò!"
},
"templates": {
"jobCompletion": {
"greeting": "Ciao {name},",
"thanks": "Grazie per il tuo ordine!",
"youtubeLink": "Ecco il link per il video karaoke pubblicato su YouTube:",
"dropboxIntro": "Ecco la cartella Dropbox con tutti i file finiti e i file sorgente, tra cui:",
"fileList": "- \"(Final Karaoke Lossless).mkv\": video karaoke combinato in 4K H264 con audio FLAC senza perdita di dati\n- \"(Final Karaoke).mp4\": video karaoke combinato con schermata del titolo/finale in 4K H264/AAC\n- \"(Final Karaoke 720p).mp4\": video karaoke combinato in 720p H264/AAC (file più piccolo per sistemi meno recenti)\n- \"(With Vocals).mp4\": video per cantare insieme in 4K H264/AAC con voci originali\n- \"(Karaoke).mov\": output video karaoke da MidiCo (nessuna schermata del titolo/finale)\n- \"(Title).mov\"/\"(End).mov\": video della scheda del titolo e della schermata finale\n- \"(Final Karaoke CDG).zip\": formato CDG+MP3 per sistemi karaoke meno recenti/commerciali\n- \"(Final Karaoke TXT).zip\": formato TXT+MP3 per Power Karaoke\n- stems/*.flac: vari stem audio strumentali e vocali separati in formato senza perdita di dati\n- lyrics/*.txt testo della canzone da varie fonti in formato testo normale",
"fixOffer": "Fammi sapere se qualcosa non è perfetto e sarò felice di modificarlo / sistemarlo, o se ne hai bisogno in qualsiasi altro formato probabilmente posso convertirlo per te!",
"feedbackRequest": "Se hai un momento, apprezzerei molto il tuo feedback (ci vogliono 2 minuti):",
"signOff": "Grazie ancora e buona giornata!\n-Andrew",
"youtubeQueued": "Il tuo caricamento su YouTube è in coda e verrà elaborato automaticamente. Riceverai a breve un'email di follow-up con il link."
},
"actionLyrics": {
"greeting": "Ciao {name},",
"ready": "Il tuo video karaoke per \"{artist} - {title}\" è pronto per la revisione!",
"instructions": "Il nostro sistema ha trascritto e sincronizzato il testo, ma potrebbe aver bisogno di alcune correzioni. Potrai anche selezionare la tua traccia strumentale preferita (con o senza cori).",
"reviewPrompt": "Per favore, revisiona il testo e seleziona una strumentale:",
"duration": "Di solito ci vogliono solo pochi minuti.",
"signOff": "Grazie!\n-Andrew"
},
"actionInstrumental": {
"greeting": "Ciao {name},",
"almostDone": "Il tuo video karaoke per \"{artist} - {title}\" è quasi pronto!",
"instructions": "Abbiamo separato l'audio in diverse versioni. Seleziona quale traccia strumentale desideri utilizzare per il video finale.",
"selectPrompt": "Seleziona la tua strumentale qui:",
"signOff": "Grazie!\n-Andrew"
},
"youtubeComplete": {
"greeting": "Ciao {name},",
"greatNews": "Ottime notizie! Il tuo video karaoke per \"{artist} - {title}\" è stato caricato su YouTube:",
"delayNote": "Questo caricamento è stato brevemente ritardato mentre i nostri sistemi elaboravano altri caricamenti, ma ora è tutto a posto.",
"signOff": "Grazie!\n-Andrew"
}
}
}
}
+338
View File
@@ -0,0 +1,338 @@
{
"auth": {
"unknownService": "不明なサービス: {service}",
"invalidCredentials": "以下のサービスの再認証が必要です: {services}",
"validCredentials": "要求されたすべての認証情報は有効です",
"youtubeAuthInstructions": "{verification_url} にアクセスして、以下のコードを入力してください: {user_code}",
"youtubeAuthStartFailed": "YouTubeデバイス認証の開始に失敗しました: {error}",
"gdriveLinkInstructions": "{verification_url} にアクセスして、以下のコードを入力してください: {user_code}",
"gdriveAuthStartFailed": "Google Driveデバイス認証の開始に失敗しました: {error}",
"discordAlertNotConfigured": "DiscordアラートのWebhookが設定されていません"
},
"jobs": {
"created": "ジョブが正常に作成されました。処理を開始しました。",
"authError": "認証エラー: ユーザー情報がありません",
"noDefaultTheme": "デフォルトのテーマが設定されていません。サポートにお問い合わせいただくか、theme_idを指定してください。",
"notFound": "ジョブが見つかりません",
"noPermissionAccess": "このジョブにアクセスする権限がありません",
"noPermissionEdit": "このジョブを編集する権限がありません",
"noPermissionDelete": "このジョブを削除する権限がありません",
"noPermissionModify": "このジョブを変更する権限がありません",
"notCompleted": "完了したジョブのみ編集可能です。現在のステータス: {status}",
"alreadyBeingEdited": "このジョブは現在編集されています(以前の出力は削除されました)",
"cleanupFailed": "{services} のクリーンアップに失敗しました。ジョブは変更されていません。もう一度お試しいただくか、サポートにお問い合わせください。",
"reopened": "トラックを編集用に再度開きました。以前の出力は削除されました。",
"invalidDatetimeFormat": "無効な {field} の形式です: {value}",
"listError": "ジョブの取得中にエラーが発生しました: {error}",
"deleteError": "ジョブ {job_id} の削除中にエラーが発生しました: {error}",
"deletionPreview": "削除を実行するには &confirm=true を追加してください",
"deletionRequiresFilters": "少なくとも1つのフィルター(environment、client_id、status、created_before)が必要です",
"bulkDeleteError": "ジョブの一括削除中にエラーが発生しました: {error}",
"reviewNotReady": "ジョブのレビュー準備ができていません(現在のステータス: {status})",
"correctionsUnavailable": "修正データが利用できません",
"audioUnavailable": "レビュー用のオーディオが利用できません",
"reviewCannotStart": "レビューを開始できません",
"jobNotInReviewState": "ジョブがレビューステータスではありません(現在のステータス: {status})",
"correctionsProcessing": "修正を保存しました。完了後に /complete-review を呼び出してください。",
"editLogSaveFailed": "ジョブ {job_id} の編集ログの保存中にエラーが発生しました: {error}",
"stemsMissing": "ジョブに必要なステム(instrumental_clean および/または backing_vocals)がありません",
"customInstrumentalFailed": "ジョブ {job_id} のカスタムインストゥルメンタルの作成中にエラーが発生しました: {error}",
"audioProcessingFailed": "オーディオファイルの処理に失敗しました: {error}",
"durationMismatch": "長さが一致しません: アップロードされたファイルは {upload_duration} 秒ですが、元のオーディオは {original_duration} 秒です。インストゥルメンタルは正確に {original_duration} 秒(±0.5秒)である必要があります。",
"reviewNotInState": "ジョブがレビューステータスではありません(現在のステータス: {status})",
"noLyricsDetected": "レビューを完了できません: オーディオから歌詞が検出されませんでした。これは、入力オーディオにボーカルがない場合(カラオケトラックやインストゥルメンタルなど)に発生する可能性があります。戻って「すべて置換」を使用して手動で歌詞を貼り付けるか、このジョブをキャンセルしてボーカルを含むオーディオファイルで再度お試しください。",
"reviewCompleteStartRendering": "レビューが完了しました。動画のレンダリングを開始しました。",
"reviewCompleteError": "ジョブ {job_id} のレビュー完了中にエラーが発生しました: {error}",
"instrumentalSelectionRequired": "instrumental_selection は必須です。'clean' または 'with_backing' のいずれかである必要があります。",
"invalidInstrumentalSelection": "無効な instrumental_selection です。次のいずれかである必要があります: {valid_selections}",
"instrumentalSelected": "インストゥルメンタルが選択されました。動画の生成を開始しました。",
"instrumentalSelectionError": "ジョブ {job_id} のインストゥルメンタル選択中にエラーが発生しました: {error}",
"downloadUrlsError": "ダウンロードURLの取得中にエラーが発生しました: {error}"
},
"review": {
"jobNotFound": "ジョブが見つかりません",
"reviewNotReady": "ジョブのレビュー準備ができていません(現在のステータス: {status})",
"correctionsNotFound": "修正データが見つかりません。歌詞の処理が完了していない可能性があります。",
"correctionsLoadFailed": "修正の読み込み中にエラーが発生しました: {error}",
"audioNotFound": "オーディオファイルが見つかりません",
"audioServeError": "オーディオの提供中にエラーが発生しました: {error}",
"instrumentalSelectionRequired": "instrumental_selection は必須です。'clean' または 'with_backing' のいずれかである必要があります。",
"invalidInstrumentalSelection": "無効な instrumental_selection です。次のいずれかである必要があります: {valid_selections}",
"reviewCompletedError": "レビュー完了中にエラーが発生しました: {error}",
"handlersUpdateNotImplemented": "ハンドラーの更新はまだ実装されていません",
"lyricsAddError": "歌詞の追加に失敗しました: {error}",
"lyricsAddInvalidRequest": "無効な歌詞追加リクエストです: {error}",
"lyricsSearchError": "歌詞の検索に失敗しました: {error}",
"lyricsSearchInvalidRequest": "無効な歌詞検索リクエストです: {error}",
"lyricsSearchNoResults": "どのプロバイダーからも一致する歌詞が見つかりませんでした",
"previewVideoGenerationError": "プレビュー動画の生成に失敗しました: {error}",
"previewVideoNotFound": "プレビュー動画が見つかりません",
"previewVideoStreamError": "プレビュー動画のストリーミング中にエラーが発生しました: {error}",
"annotationSaveError": "アノテーションの保存中にエラーが発生しました: {error}",
"waveformGenerationError": "波形データの生成中にエラーが発生しました: {error}",
"waveformNoAudio": "波形用のオーディオがありません",
"sessionSaveError": "修正データが必要です"
},
"audioSearch": {
"notEnabled": "このテナントではオーディオ検索が有効になっていません",
"disabled": "オーディオ検索は利用できません",
"downloadError": "ジョブ {job_id} のダウンロードに失敗しました: {error}",
"jobNotFound": "ジョブ {job_id} が見つかりません",
"noSearchResults": "検索結果がありません",
"invalidSelectionIndex": "無効な選択インデックス {selection_index} です。有効な範囲: 0-{max}",
"selectionError": "ジョブ {job_id} のオーディオ選択中にエラーが発生しました: {error}",
"youtubeDownloadError": "YouTubeのダウンロードに失敗しました: {error}",
"torrentDownloadError": "リモートのflacfetchサービスなしで {source} からダウンロードすることはできません。FLACFETCH_API_URLを設定してください。",
"remoteDownloadNoSearchId": "{source} のダウンロードに利用できる source_id または remote_search_id がありません",
"remoteDownloadCompleteNoPath": "リモートダウンロードは完了しましたが、ファイルパスが返されませんでした",
"spotifyDownloadError": "リモートのflacfetchサービスなしでSpotifyからダウンロードすることはできません。FLACFETCH_API_URLを設定してください。",
"genericDownloadError": "不明なソースタイプ: {source}、一般的なダウンロードを試みます",
"jobNotFoundDuringDownload": "バックグラウンドダウンロード中にジョブ {job_id} が見つかりませんでした",
"selectAudioError": "ジョブ {job_id} のオーディオ選択中にエラーが発生しました: {error}",
"searchAudioError": "オーディオの検索中にエラーが発生しました: {error}",
"searchCreatedSuccessfully": "ジョブが作成されました。オーディオを検索しています...",
"autoDownloadStarted": "最適な結果が自動的に選択されました。ダウンロードを開始します..."
},
"users": {
"disposableEmailBlocked": "使い捨てメールアドレスは許可されていません",
"magicLinkSent": "このメールアドレスが登録されている場合、まもなくサインインリンクが届きます。",
"emailServiceNotConfigured": "メールサービスが利用できません。サポートにお問い合わせください。",
"emailDomainNotAllowed": "このテナントでは許可されていないメールドメインです",
"invalidToken": "無効なトークンです",
"verifyError": "検証に失敗しました: {message}",
"magicLinkSuccess": "サインインに成功しました",
"logoutSuccess": "ログアウトに成功しました",
"userNotFound": "ユーザーが見つかりません",
"creditPackagesError": "クレジットパッケージの読み込み中にエラーが発生しました: {error}",
"stripeSendError": "Stripeチェックアウトリンクの送信中にエラーが発生しました: {error}",
"stripeWebhookProcessingError": "Stripe Webhookの処理中にエラーが発生しました: {error}",
"feedbackSaveError": "フィードバックの保存中にエラーが発生しました: {error}",
"feedbackNotEligible": "このユーザーはフィードバックの対象外です"
},
"fileUpload": {
"invalidTheme": "テーマが見つかりません: {theme_id}。利用可能なテーマを一覧表示するには GET /api/themes を使用してください。",
"uploadSuccess": "ファイルが正常にアップロードされました。処理を開始しました。",
"uploadError": "ファイルのアップロード中にエラーが発生しました: {error}",
"urlDownloadError": "URLからのダウンロード中にエラーが発生しました: {error}",
"invalidContentType": "無効なコンテンツタイプです: {content_type}",
"fileSizeError": "ファイルが大きすぎます: {size}。最大: {max_size}",
"invalidFileType": "無効なファイルタイプです: {file_type}",
"multipleAudioFilesNotAllowed": "アップロードできるオーディオファイルは1つだけです",
"noAudioFileProvided": "オーディオファイルが提供されていません",
"urlCreationSuccess": "ジョブが作成されました。アップロードURLが生成されました。",
"urlCreationError": "アップロードURL付きのジョブ作成中にエラーが発生しました: {error}",
"uploadsCompleteSuccess": "アップロードが完了しました。処理を開始しました。",
"uploadsCompleteError": "アップロードの完了中にエラーが発生しました: {error}",
"noUploadedFiles": "アップロードされたファイルが指定されていません",
"styleUploadUrlsSuccess": "スタイルのアップロードURLが生成されました。",
"styleUploadsCompleteSuccess": "スタイルファイルが更新されました。処理を再開しました。",
"styleUploadsCompleteError": "スタイルのアップロード完了中にエラーが発生しました: {error}"
},
"catalog": {
"rateLimitExceeded": "レート制限を超過しました。カタログのリクエストは1分間に最大 {max_requests} 回までです。",
"catalogSearchError": "カタログの検索中にエラーが発生しました: {error}",
"communityCheckError": "コミュニティバージョンの確認中にエラーが発生しました: {error}"
},
"themes": {
"themesLoadError": "テーマの読み込みに失敗しました",
"themeNotFound": "テーマが見つかりません: {theme_id}",
"themeLoadError": "テーマの読み込みに失敗しました",
"previewNotAvailable": "テーマのプレビューは利用できません: {theme_id}",
"previewLoadError": "テーマプレビューの読み込みに失敗しました",
"youtubeDescriptionNotFound": "テーマが見つかりません: {theme_id}",
"youtubeDescriptionLoadError": "YouTubeの説明の読み込みに失敗しました"
},
"tenant": {
"assetNotFound": "アセットが見つかりません"
},
"push": {
"disabled": "プッシュ通知が有効になっていません",
"userEmailNotAvailable": "ユーザーのメールアドレスが利用できません",
"missingEncryptionKeys": "必要なキー(p256dh、auth)がありません",
"subscriptionSaveFailed": "サブスクリプションの保存に失敗しました",
"subscriptionRegistered": "プッシュサブスクリプションが正常に登録されました",
"subscriptionNotFound": "サブスクリプションが削除されたか、見つかりませんでした",
"subscriptionRemoved": "プッシュサブスクリプションが正常に削除されました",
"testNotificationSent": "テスト通知を {sent_count} 台のデバイスに送信しました"
},
"pushNotifications": {
"reviewLyricsTitle": "歌詞のレビュー",
"reviewLyricsBody": "{artist} の「{title}」の歌詞の確認をお願いします",
"selectInstrumentalTitle": "インストゥルメンタルの選択",
"selectInstrumentalBody": "{artist} の「{title}」のインストゥルメンタルの選択をお願いします",
"videoReadyTitle": "動画の準備ができました!",
"videoReadyBody": "{artist} の「{title}」のカラオケ動画がダウンロード可能になりました"
},
"admin": {
"invalidDomainFormat": "無効なドメイン形式です",
"domainAddedToBl": "ドメイン '{domain}' が使い捨てドメインのブロックリストに追加されました",
"domainNotFoundInBl": "ドメインがブロックリストに見つかりません",
"domainRemovedFromBl": "ドメイン '{domain}' が使い捨てドメインのブロックリストから削除されました",
"domainAddedToAllowlist": "ドメイン '{domain}' が許可リストに追加されました",
"domainNotFoundInAllowlist": "ドメインが許可リストに見つかりません",
"domainRemovedFromAllowlist": "ドメイン '{domain}' が許可リストから削除されました",
"syncComplete": "{external_count} 個の外部ドメインを同期しました(追加: {added}、削除: {removed})",
"invalidEmailFormat": "無効なメールアドレス形式です",
"emailAddedToBl": "メールアドレス '{email}' がブロックリストに追加されました",
"emailNotFoundInBl": "メールアドレスがブロックリストに見つかりません",
"emailRemovedFromBl": "メールアドレス '{email}' がブロックリストから削除されました",
"invalidIPAddress": "無効なIPアドレスです",
"ipAddedToBl": "IP '{ip_address}' がブロックされたIPリストに追加されました",
"ipNotFoundInBl": "IPがブロックリストに見つかりません",
"ipRemovedFromBl": "IP '{ip_address}' がブロックされたIPリストから削除されました",
"youtubeUploadNotFound": "ジョブ {job_id} のアップロードが見つからないか、再試行可能な状態ではありません",
"youtubeUploadQueuedForRetry": "ジョブ {job_id} のYouTubeアップロードが再試行キューに追加されました",
"youtubeQueueProcessingStarted": "YouTubeキューの処理がバックグラウンドで開始されました"
},
"rateLimits": {
"configNotFound": "レート制限の設定が見つかりません: {config_id}",
"configUpdateError": "レート制限設定の更新中にエラーが発生しました: {error}"
},
"errors": {
"insufficientCredits": "この操作に必要なクレジットが不足しています",
"insufficientCreditsBuyUrl": "/#pricing"
},
"emails": {
"magicLink": {
"subject": "{brand_name} にサインイン",
"greeting": "こんにちは、",
"signInPrompt": "下のボタンをクリックして {brand_name} にサインインしてください:",
"signInButton": "サインイン",
"expiryWarning": "このリンクの有効期限は15分間で、1回のみ使用可能です。",
"fallbackLink": "ボタンが機能しない場合は、このリンクをコピーしてブラウザに貼り付けてください:",
"ignoreNote": "このメールに心当たりがない場合は、そのまま破棄してください。"
},
"welcome": {
"subject": "Nomad Karaoke へようこそ!",
"welcomeGreeting": "Nomad Karaoke へようこそ!",
"turnAnySong": "どんな曲でも数分でプロ仕様のカラオケ動画に。",
"freeCreditsLabel": "無料クレジット",
"freeCreditsNote": "1クレジットでプロ仕様のカラオケ動画を1本作成できます",
"howItWorks": "使い方は簡単です:",
"step1Title": "1. 曲を検索する",
"step1Desc": "アーティスト名と曲名を入力するだけで、高品質なオーディオを検索します。",
"step2Title": "2. システムが魔法をかけます",
"step2Desc": "ボーカルを分離し、歌詞を文字起こしして、すべてを完璧に同期させます。",
"step3Title": "3. レビューとカスタマイズ",
"step3Desc": "必要に応じて歌詞を微調整し、お好みのインストゥルメンタルを選択します。",
"step4Title": "4. 動画を受け取る",
"step4Desc": "4Kカラオケ動画をダウンロードするか、YouTubeに直接アップロードします。",
"feedbackBonus": "動画を2本作成してフィードバックを共有すると、さらに2クレジットを無料で獲得できます!",
"getStartedButton": "はじめる"
},
"creditsAdded": {
"subject": "Nomad Karaoke アカウントに {credits} クレジットが追加されました",
"greatNews": "嬉しいお知らせです!",
"creditsAddedMessage": "アカウントに {credits} クレジットが追加されました。",
"yourBalance": "現在の残高:",
"credits": "クレジット",
"eachCreditLets": "1クレジットにつき、以下の機能を備えたプロ仕様のカラオケ動画を1本作成できます:",
"featureVocalSeparation": "AIによるボーカル/インストゥルメンタル分離",
"featureLyrics": "単語レベルのタイミングで同期された歌詞",
"feature4k": "4K動画出力",
"featureYoutube": "YouTubeへのアップロード",
"createButton": "今すぐカラオケを作成する"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (カラオケ動画の準備ができました!)",
"subject": "{artist} - {title} (カラオケ動画の準備ができました!)",
"subjectFallback": "カラオケ動画の準備ができました!"
},
"youtubeUpload": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (YouTubeアップロードの準備ができました!)",
"subject": "{artist} - {title} (YouTubeアップロードの準備ができました!)",
"subjectFallback": "YouTubeアップロードの準備ができました!"
},
"actionReminder": {
"lyricsSubject": "対応が必要です: {artist} - {title} の歌詞をご確認ください",
"lyricsSubjectFallback": "対応が必要です: 歌詞をご確認ください",
"instrumentalSubject": "対応が必要です: {artist} - {title} のインストゥルメンタルを選択してください",
"instrumentalSubjectFallback": "対応が必要です: インストゥルメンタルを選択してください",
"audioEditSubject": "対応が必要です: {artist} - {title}",
"audioEditSubjectFallback": "対応が必要です",
"alertHeading": "カラオケ動画の作成に確認が必要です!"
},
"reviewReminder": {
"subject": "リマインダー: カラオケ動画がレビュー待ちです — {artist} - {title}",
"subjectFallback": "リマインダー: カラオケ動画がレビュー待ちです",
"alertHeading": "カラオケ動画があなたを待っています!",
"reminderIntro": "カラオケ動画{song_name}の確認準備ができましたのでお知らせします。",
"reviewButton": "動画を確認する",
"reviewInstructions": "確認画面では、歌詞が正しいかチェックし、お好みのインストゥルメンタルトラックを選択できます。通常は数分で完了します!",
"helpOffer": "確認プロセスで問題が発生した場合は、このメールに返信していただければサポートいたします。",
"expiryWarning": "ご注意: 今後24時間以内に確認が完了しない場合、ジョブは自動的に期限切れとなり、クレジットは返還されます。"
},
"reviewExpired": {
"subject": "カラオケ動画の期限が切れました — {artist} - {title}",
"subjectFallback": "カラオケ動画の期限が切れました",
"cancelNotice": "48時間以内に確認が完了しなかったため、カラオケ動画{song_name}は自動的にキャンセルされました。",
"refundNotice": "ご安心ください — クレジットは返還されました!現在の残高は {credits_balance} {credits_word} です。",
"creditSingular": "クレジット",
"creditPlural": "クレジット",
"createNewPrompt": "クレジットを使用して、いつでも新しいカラオケ動画を作成できます:",
"createButton": "新しい動画を作成する",
"helpOffer": "確認プロセスで問題があった場合やサポートが必要な場合は、このメールに返信してください。喜んでお手伝いします!"
},
"creditDenied": {
"subject": "Nomad Karaoke の無料クレジットについて",
"greeting": "こんにちは、",
"thankYou": "Nomad Karaoke にご登録いただきありがとうございます!",
"deniedMessage": "残念ながら、今回は無料の {credit_type} を付与することができませんでした。当社のシステムが、これがお客様の最初のアカウントではない可能性を示唆するパターンを検出しました。カラオケ生成ジョブには、クラウドコンピューティングとAPIの料金として実際のコストがかかっているため、何卒ご了承ください。",
"mistakeNote": "もしこれが何かの間違いで、純粋な新規ユーザーである場合は、このメールに返信して創設者のAndrewにお知らせください。お試し用の無料クレジットを喜んで付与させていただきます。その代わり、体験についての率直なフィードバックをご提供いただけますと幸いです。",
"buyPrompt": "すぐに始めたい場合は、クレジットを購入することもできます:",
"buyButton": "クレジットを購入する",
"costNote": "サービスを手頃な価格で提供できるようコストを抑えているため、無料クレジットの悪用には注意を払う必要があります。ご理解のほどよろしくお願いいたします!",
"welcomeCredits": "ウェルカムクレジット",
"feedbackCredits": "フィードバックボーナスクレジット"
},
"madeForYouConfirmation": {
"subject": "注文の確認: {artist} - {title} | Nomad Karaoke",
"thankYou": "ご注文ありがとうございます!",
"orderDetails": "注文の詳細",
"orderId": "注文ID:",
"artist": "アーティスト:",
"title": "タイトル:",
"yourNotes": "あなたのメモ:",
"deliveryTime": "私たちのチームが {hours} 時間以内にカスタムカラオケ動画を作成します。",
"deliveryNotice": "動画の準備ができ次第、ダウンロードリンクを記載したメールをお送りします。",
"noAction": "お客様側での作業は不要です — あとは私たちにお任せください!"
},
"shared": {
"footerHelp": "お気づきの点があれば、このメールに返信してください。修正いたします!"
},
"templates": {
"jobCompletion": {
"greeting": "{name} さん、こんにちは。",
"thanks": "ご注文ありがとうございます!",
"youtubeLink": "YouTubeに公開されたカラオケ動画のリンクはこちらです:",
"dropboxIntro": "完成したすべてのファイルとソースファイルが含まれるDropboxのフォルダはこちらです:",
"fileList": "- \"(Final Karaoke Lossless).mkv\": ロスレスFLACオーディオ付きの4K H264結合カラオケ動画\n- \"(Final Karaoke).mp4\": タイトル/エンドスクリーン付きの4K H264/AAC結合カラオケ動画\n- \"(Final Karaoke 720p).mp4\": 720p H264/AACの結合カラオケ動画(古いシステム向けの小さなファイル)\n- \"(With Vocals).mp4\": オリジナルボーカル付きの4K H264/AACの歌唱用動画\n- \"(Karaoke).mov\": MidiCoからのカラオケ動画出力(タイトル/エンドスクリーンなし)\n- \"(Title).mov\"/\"(End).mov\": タイトルカードとエンドスクリーンの動画\n- \"(Final Karaoke CDG).zip\": 古い/商用カラオケシステム向けのCDG+MP3形式\n- \"(Final Karaoke TXT).zip\": Power Karaoke向けのTXT+MP3形式\n- stems/*.flac: ロスレス形式の分離された各種インストゥルメンタルおよびボーカルのオーディオステム\n- lyrics/*.txt: さまざまなソースからのプレーンテキスト形式の曲の歌詞",
"fixOffer": "お気づきの点があればお知らせください。喜んで微調整や修正をいたします。また、他の形式が必要な場合も、おそらく変換可能です!",
"feedbackRequest": "もしお時間があれば、フィードバックをいただけると大変助かります(2分程度で終わります):",
"signOff": "改めて、ありがとうございます。良い一日を!\n-Andrew",
"youtubeQueued": "YouTubeへのアップロードはキューに追加され、自動的に処理されます。まもなくリンクを記載したフォローアップメールが届きます。"
},
"actionLyrics": {
"greeting": "{name} さん、こんにちは。",
"ready": "「{artist} - {title}」のカラオケ動画の確認準備ができました!",
"instructions": "システムが歌詞を文字起こしして同期しましたが、いくつか修正が必要な場合があります。また、お好みのインストゥルメンタルトラック(バックコーラスの有無)を選択することもできます。",
"reviewPrompt": "歌詞を確認し、インストゥルメンタルを選択してください:",
"duration": "通常、これには数分しかかかりません。",
"signOff": "よろしくお願いします!\n-Andrew"
},
"actionInstrumental": {
"greeting": "{name} さん、こんにちは。",
"almostDone": "「{artist} - {title}」のカラオケ動画がほぼ完成しました!",
"instructions": "オーディオを異なるバージョンに分離しました。最終的な動画に使用するインストゥルメンタルトラックを選択してください。",
"selectPrompt": "こちらでインストゥルメンタルを選択してください:",
"signOff": "よろしくお願いします!\n-Andrew"
},
"youtubeComplete": {
"greeting": "{name} さん、こんにちは。",
"greatNews": "お知らせです!「{artist} - {title}」のカラオケ動画がYouTubeにアップロードされました:",
"delayNote": "システムが他のアップロードを処理していたため一時的に遅延していましたが、現在はすべて完了しています。",
"signOff": "よろしくお願いします!\n-Andrew"
}
}
}
}
+338
View File
@@ -0,0 +1,338 @@
{
"auth": {
"unknownService": "알 수 없는 서비스: {service}",
"invalidCredentials": "다음 서비스의 재인증이 필요합니다: {services}",
"validCredentials": "요청된 모든 자격 증명이 유효합니다",
"youtubeAuthInstructions": "{verification_url}에 방문하여 다음 코드를 입력하세요: {user_code}",
"youtubeAuthStartFailed": "YouTube 기기 인증을 시작하지 못했습니다: {error}",
"gdriveLinkInstructions": "{verification_url}에 방문하여 다음 코드를 입력하세요: {user_code}",
"gdriveAuthStartFailed": "Google Drive 기기 인증을 시작하지 못했습니다: {error}",
"discordAlertNotConfigured": "Discord 알림 웹훅이 구성되지 않았습니다"
},
"jobs": {
"created": "작업이 성공적으로 생성되었습니다. 처리가 시작되었습니다.",
"authError": "인증 오류: 사용 가능한 사용자 신원이 없습니다",
"noDefaultTheme": "기본 테마가 구성되지 않았습니다. 지원팀에 문의하거나 theme_id를 지정해 주세요.",
"notFound": "작업을 찾을 수 없습니다",
"noPermissionAccess": "이 작업에 액세스할 권한이 없습니다",
"noPermissionEdit": "이 작업을 편집할 권한이 없습니다",
"noPermissionDelete": "이 작업을 삭제할 권한이 없습니다",
"noPermissionModify": "이 작업을 수정할 권한이 없습니다",
"notCompleted": "완료된 작업만 편집할 수 있습니다. 현재 상태: {status}",
"alreadyBeingEdited": "이 작업은 이미 편집 중입니다(출력물이 이미 삭제됨)",
"cleanupFailed": "{services}의 정리에 실패했습니다. 작업이 수정되지 않았습니다. 다시 시도하거나 지원팀에 문의해 주세요.",
"reopened": "편집을 위해 트랙이 다시 열렸습니다. 이전 출력물이 제거되었습니다.",
"invalidDatetimeFormat": "잘못된 {field} 형식: {value}",
"listError": "작업 목록을 불러오는 중 오류 발생: {error}",
"deleteError": "작업 {job_id} 삭제 중 오류 발생: {error}",
"deletionPreview": "삭제를 실행하려면 &confirm=true를 추가하세요",
"deletionRequiresFilters": "최소 하나 이상의 필터(environment, client_id, status, created_before)가 필요합니다",
"bulkDeleteError": "작업 일괄 삭제 중 오류 발생: {error}",
"reviewNotReady": "작업을 검토할 준비가 되지 않았습니다 (현재 상태: {status})",
"correctionsUnavailable": "수정 데이터를 사용할 수 없습니다",
"audioUnavailable": "검토할 오디오를 사용할 수 없습니다",
"reviewCannotStart": "검토를 시작할 수 없습니다",
"jobNotInReviewState": "작업이 검토 상태가 아닙니다 (현재 상태: {status})",
"correctionsProcessing": "수정 사항이 저장되었습니다. 완료되면 /complete-review를 호출하세요.",
"editLogSaveFailed": "작업 {job_id}의 편집 로그 저장 중 오류 발생: {error}",
"stemsMissing": "작업에 필요한 스템(instrumental_clean 및/또는 backing_vocals)이 누락되었습니다",
"customInstrumentalFailed": "작업 {job_id}의 맞춤형 반주 생성 중 오류 발생: {error}",
"audioProcessingFailed": "오디오 파일 처리 실패: {error}",
"durationMismatch": "길이 불일치: 업로드된 파일은 {upload_duration}초이지만 원본 오디오는 {original_duration}초입니다. 반주는 정확히 {original_duration}초(±0.5초)여야 합니다.",
"reviewNotInState": "작업이 검토 상태가 아닙니다 (현재 상태: {status})",
"noLyricsDetected": "검토를 완료할 수 없습니다: 오디오에서 가사가 감지되지 않았습니다. 입력 오디오에 보컬이 없는 경우(예: 노래방 트랙 또는 반주) 발생할 수 있습니다. 뒤로 돌아가서 '모두 바꾸기'를 사용하여 가사를 수동으로 붙여넣거나, 이 작업을 취소하고 보컬이 포함된 오디오 파일로 다시 시도할 수 있습니다.",
"reviewCompleteStartRendering": "검토가 완료되었습니다. 비디오 렌더링이 시작되었습니다.",
"reviewCompleteError": "작업 {job_id}의 검토 완료 중 오류 발생: {error}",
"instrumentalSelectionRequired": "instrumental_selection이 필요합니다. 'clean' 또는 'with_backing'이어야 합니다.",
"invalidInstrumentalSelection": "잘못된 instrumental_selection입니다. 다음 중 하나여야 합니다: {valid_selections}",
"instrumentalSelected": "반주가 선택되었습니다. 비디오 생성이 시작되었습니다.",
"instrumentalSelectionError": "작업 {job_id}의 반주 선택 중 오류 발생: {error}",
"downloadUrlsError": "다운로드 URL을 가져오는 중 오류 발생: {error}"
},
"review": {
"jobNotFound": "작업을 찾을 수 없습니다",
"reviewNotReady": "작업을 검토할 준비가 되지 않았습니다 (현재 상태: {status})",
"correctionsNotFound": "수정 데이터를 찾을 수 없습니다. 가사 처리가 완료되지 않았을 수 있습니다.",
"correctionsLoadFailed": "수정 사항을 불러오는 중 오류 발생: {error}",
"audioNotFound": "오디오 파일을 찾을 수 없습니다",
"audioServeError": "오디오 제공 중 오류 발생: {error}",
"instrumentalSelectionRequired": "instrumental_selection이 필요합니다. 'clean' 또는 'with_backing'이어야 합니다.",
"invalidInstrumentalSelection": "잘못된 instrumental_selection입니다. 다음 중 하나여야 합니다: {valid_selections}",
"reviewCompletedError": "검토 완료 중 오류 발생: {error}",
"handlersUpdateNotImplemented": "핸들러 업데이트가 아직 구현되지 않았습니다",
"lyricsAddError": "가사 추가 실패: {error}",
"lyricsAddInvalidRequest": "잘못된 가사 추가 요청: {error}",
"lyricsSearchError": "가사 검색 실패: {error}",
"lyricsSearchInvalidRequest": "잘못된 가사 검색 요청: {error}",
"lyricsSearchNoResults": "어떤 제공업체에서도 일치하는 가사를 찾을 수 없습니다",
"previewVideoGenerationError": "미리보기 비디오 생성 실패: {error}",
"previewVideoNotFound": "미리보기 비디오를 찾을 수 없습니다",
"previewVideoStreamError": "미리보기 비디오 스트리밍 중 오류 발생: {error}",
"annotationSaveError": "주석 저장 중 오류 발생: {error}",
"waveformGenerationError": "파형 데이터 생성 중 오류 발생: {error}",
"waveformNoAudio": "파형에 사용할 오디오가 없습니다",
"sessionSaveError": "수정 데이터가 필요합니다"
},
"audioSearch": {
"notEnabled": "이 테넌트에서는 오디오 검색이 활성화되어 있지 않습니다",
"disabled": "오디오 검색을 사용할 수 없습니다",
"downloadError": "작업 {job_id} 다운로드 실패: {error}",
"jobNotFound": "작업 {job_id}을(를) 찾을 수 없습니다",
"noSearchResults": "검색 결과가 없습니다",
"invalidSelectionIndex": "잘못된 선택 인덱스 {selection_index}. 유효 범위: 0-{max}",
"selectionError": "작업 {job_id}의 오디오 선택 중 오류 발생: {error}",
"youtubeDownloadError": "YouTube 다운로드 실패: {error}",
"torrentDownloadError": "원격 flacfetch 서비스 없이 {source}에서 다운로드할 수 없습니다. FLACFETCH_API_URL을 구성하세요.",
"remoteDownloadNoSearchId": "{source} 다운로드에 사용할 수 있는 source_id 또는 remote_search_id가 없습니다",
"remoteDownloadCompleteNoPath": "원격 다운로드가 완료되었지만 파일 경로가 반환되지 않았습니다",
"spotifyDownloadError": "원격 flacfetch 서비스 없이 Spotify에서 다운로드할 수 없습니다. FLACFETCH_API_URL을 구성하세요.",
"genericDownloadError": "알 수 없는 소스 유형: {source}, 일반 다운로드를 시도합니다",
"jobNotFoundDuringDownload": "백그라운드 다운로드 중 작업 {job_id}을(를) 찾을 수 없습니다",
"selectAudioError": "작업 {job_id}의 오디오 선택 중 오류 발생: {error}",
"searchAudioError": "오디오 검색 중 오류 발생: {error}",
"searchCreatedSuccessfully": "작업이 생성되었습니다. 오디오를 검색하는 중...",
"autoDownloadStarted": "가장 적합한 결과가 자동으로 선택되었습니다. 다운로드를 시작합니다..."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
"magicLinkSent": "등록된 이메일인 경우 곧 로그인 링크가 전송됩니다.",
"emailServiceNotConfigured": "이메일 서비스를 사용할 수 없습니다. 지원팀에 문의해 주세요.",
"emailDomainNotAllowed": "이 테넌트에서 허용되지 않는 이메일 도메인입니다",
"invalidToken": "유효하지 않은 토큰입니다",
"verifyError": "인증 실패: {message}",
"magicLinkSuccess": "성공적으로 로그인되었습니다",
"logoutSuccess": "성공적으로 로그아웃되었습니다",
"userNotFound": "사용자를 찾을 수 없습니다",
"creditPackagesError": "크레딧 패키지를 불러오는 중 오류 발생: {error}",
"stripeSendError": "Stripe 결제 링크 전송 중 오류 발생: {error}",
"stripeWebhookProcessingError": "Stripe 웹훅 처리 중 오류 발생: {error}",
"feedbackSaveError": "피드백 저장 중 오류 발생: {error}",
"feedbackNotEligible": "사용자가 피드백 대상이 아닙니다"
},
"fileUpload": {
"invalidTheme": "테마를 찾을 수 없습니다: {theme_id}. 사용 가능한 테마를 나열하려면 GET /api/themes를 사용하세요.",
"uploadSuccess": "파일이 성공적으로 업로드되었습니다. 처리가 시작되었습니다.",
"uploadError": "파일 업로드 중 오류 발생: {error}",
"urlDownloadError": "URL에서 다운로드 중 오류 발생: {error}",
"invalidContentType": "잘못된 콘텐츠 유형: {content_type}",
"fileSizeError": "파일이 너무 큽니다: {size}. 최대: {max_size}",
"invalidFileType": "잘못된 파일 유형: {file_type}",
"multipleAudioFilesNotAllowed": "오디오 파일은 하나만 업로드할 수 있습니다",
"noAudioFileProvided": "오디오 파일이 제공되지 않았습니다",
"urlCreationSuccess": "작업이 생성되었습니다. 업로드 URL이 생성되었습니다.",
"urlCreationError": "업로드 URL로 작업을 생성하는 중 오류 발생: {error}",
"uploadsCompleteSuccess": "업로드가 완료되었습니다. 처리가 시작되었습니다.",
"uploadsCompleteError": "업로드 완료 중 오류 발생: {error}",
"noUploadedFiles": "업로드된 파일이 지정되지 않았습니다",
"styleUploadUrlsSuccess": "스타일 업로드 URL이 생성되었습니다.",
"styleUploadsCompleteSuccess": "스타일 파일이 업데이트되었습니다. 처리가 다시 시작되었습니다.",
"styleUploadsCompleteError": "스타일 업로드 완료 중 오류 발생: {error}"
},
"catalog": {
"rateLimitExceeded": "요청 한도를 초과했습니다. 분당 최대 {max_requests}개의 카탈로그 요청이 가능합니다.",
"catalogSearchError": "카탈로그 검색 중 오류 발생: {error}",
"communityCheckError": "커뮤니티 버전 확인 중 오류 발생: {error}"
},
"themes": {
"themesLoadError": "테마를 불러오지 못했습니다",
"themeNotFound": "테마를 찾을 수 없습니다: {theme_id}",
"themeLoadError": "테마를 불러오지 못했습니다",
"previewNotAvailable": "테마의 미리보기를 사용할 수 없습니다: {theme_id}",
"previewLoadError": "테마 미리보기를 불러오지 못했습니다",
"youtubeDescriptionNotFound": "테마를 찾을 수 없습니다: {theme_id}",
"youtubeDescriptionLoadError": "YouTube 설명을 불러오지 못했습니다"
},
"tenant": {
"assetNotFound": "에셋을 찾을 수 없습니다"
},
"push": {
"disabled": "푸시 알림이 활성화되지 않았습니다",
"userEmailNotAvailable": "사용자 이메일을 사용할 수 없습니다",
"missingEncryptionKeys": "필수 키(p256dh, auth)가 누락되었습니다",
"subscriptionSaveFailed": "구독 저장에 실패했습니다",
"subscriptionRegistered": "푸시 구독이 성공적으로 등록되었습니다",
"subscriptionNotFound": "구독이 제거되었거나 찾을 수 없습니다",
"subscriptionRemoved": "푸시 구독이 성공적으로 제거되었습니다",
"testNotificationSent": "{sent_count}대의 기기로 테스트 알림이 전송되었습니다"
},
"pushNotifications": {
"reviewLyricsTitle": "가사 검토",
"reviewLyricsBody": "{artist}의 \"{title}\" 가사 검토가 필요합니다",
"selectInstrumentalTitle": "반주 선택",
"selectInstrumentalBody": "{artist}의 \"{title}\" 반주 선택이 필요합니다",
"videoReadyTitle": "비디오 준비 완료!",
"videoReadyBody": "{artist}의 \"{title}\" 노래방 비디오를 다운로드할 준비가 되었습니다"
},
"admin": {
"invalidDomainFormat": "잘못된 도메인 형식",
"domainAddedToBl": "도메인 '{domain}'이(가) 일회용 도메인 차단 목록에 추가되었습니다",
"domainNotFoundInBl": "차단 목록에서 도메인을 찾을 수 없습니다",
"domainRemovedFromBl": "도메인 '{domain}'이(가) 일회용 도메인 차단 목록에서 제거되었습니다",
"domainAddedToAllowlist": "도메인 '{domain}'이(가) 허용 목록에 추가되었습니다",
"domainNotFoundInAllowlist": "허용 목록에서 도메인을 찾을 수 없습니다",
"domainRemovedFromAllowlist": "도메인 '{domain}'이(가) 허용 목록에서 제거되었습니다",
"syncComplete": "{external_count}개의 외부 도메인 동기화 완료 ({added}개 추가됨, {removed}개 제거됨)",
"invalidEmailFormat": "잘못된 이메일 형식",
"emailAddedToBl": "이메일 '{email}'이(가) 차단된 이메일 목록에 추가되었습니다",
"emailNotFoundInBl": "차단 목록에서 이메일을 찾을 수 없습니다",
"emailRemovedFromBl": "이메일 '{email}'이(가) 차단된 이메일 목록에서 제거되었습니다",
"invalidIPAddress": "잘못된 IP 주소",
"ipAddedToBl": "IP '{ip_address}'이(가) 차단된 IP 목록에 추가되었습니다",
"ipNotFoundInBl": "차단 목록에서 IP를 찾을 수 없습니다",
"ipRemovedFromBl": "IP '{ip_address}'이(가) 차단된 IP 목록에서 제거되었습니다",
"youtubeUploadNotFound": "작업 {job_id}의 업로드를 찾을 수 없거나 재시도할 수 있는 상태가 아닙니다",
"youtubeUploadQueuedForRetry": "작업 {job_id}의 YouTube 업로드가 재시도를 위해 대기열에 추가되었습니다",
"youtubeQueueProcessingStarted": "백그라운드에서 YouTube 대기열 처리가 시작되었습니다"
},
"rateLimits": {
"configNotFound": "요청 한도 구성을 찾을 수 없습니다: {config_id}",
"configUpdateError": "요청 한도 구성 업데이트 중 오류 발생: {error}"
},
"errors": {
"insufficientCredits": "이 작업을 수행하기에 크레딧이 부족합니다",
"insufficientCreditsBuyUrl": "/#pricing"
},
"emails": {
"magicLink": {
"subject": "{brand_name}에 로그인하세요",
"greeting": "안녕하세요,",
"signInPrompt": "아래 버튼을 클릭하여 {brand_name}에 로그인하세요:",
"signInButton": "로그인",
"expiryWarning": "이 링크는 15분 후에 만료되며 한 번만 사용할 수 있습니다.",
"fallbackLink": "버튼이 작동하지 않으면 다음 링크를 복사하여 브라우저에 붙여넣으세요:",
"ignoreNote": "이 이메일을 요청하지 않으셨다면 무시하셔도 안전합니다."
},
"welcome": {
"subject": "Nomad Karaoke에 오신 것을 환영합니다!",
"welcomeGreeting": "Nomad Karaoke에 오신 것을 환영합니다!",
"turnAnySong": "어떤 노래든 몇 분 만에 전문적인 노래방 비디오로 만들어 보세요.",
"freeCreditsLabel": "무료 크레딧",
"freeCreditsNote": "크레딧 1개당 전문적인 노래방 비디오 1개를 만들 수 있습니다",
"howItWorks": "이용 방법은 다음과 같습니다:",
"step1Title": "1. 노래 검색",
"step1Desc": "아티스트와 제목을 입력하시면 고품질 오디오를 찾아드립니다.",
"step2Title": "2. 시스템 자동 처리",
"step2Desc": "보컬을 분리하고, 가사를 추출하며, 모든 싱크를 완벽하게 맞춥니다.",
"step3Title": "3. 검토 및 맞춤 설정",
"step3Desc": "필요한 경우 가사를 미세 조정하고, 반주를 선택하세요.",
"step4Title": "4. 비디오 받기",
"step4Desc": "4K 노래방 비디오를 다운로드하거나 YouTube에 직접 업로드하세요.",
"feedbackBonus": "비디오 2개를 완성하고 피드백을 공유하여 무료 크레딧 2개를 추가로 받으세요!",
"getStartedButton": "시작하기"
},
"creditsAdded": {
"subject": "Nomad Karaoke 계정에 {credits} 크레딧이 추가되었습니다",
"greatNews": "좋은 소식입니다!",
"creditsAddedMessage": "계정에 {credits} 크레딧이 추가되었습니다.",
"yourBalance": "잔여 크레딧:",
"credits": "크레딧",
"eachCreditLets": "각 크레딧으로 다음과 같은 전문적인 노래방 비디오를 1개 만들 수 있습니다:",
"featureVocalSeparation": "AI 기반 보컬/반주 분리",
"featureLyrics": "단어 단위 타이밍이 맞춰진 동기화된 가사",
"feature4k": "4K 비디오 출력",
"featureYoutube": "YouTube 업로드",
"createButton": "지금 노래방 비디오 만들기"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (노래방 비디오가 준비되었습니다!)",
"subject": "{artist} - {title} (노래방 비디오가 준비되었습니다!)",
"subjectFallback": "노래방 비디오가 준비되었습니다!"
},
"youtubeUpload": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (YouTube 업로드가 준비되었습니다!)",
"subject": "{artist} - {title} (YouTube 업로드가 준비되었습니다!)",
"subjectFallback": "YouTube 업로드가 준비되었습니다!"
},
"actionReminder": {
"lyricsSubject": "조치 필요: {artist} - {title}의 가사를 검토해 주세요",
"lyricsSubjectFallback": "조치 필요: 가사를 검토해 주세요",
"instrumentalSubject": "조치 필요: {artist} - {title}의 반주를 선택해 주세요",
"instrumentalSubjectFallback": "조치 필요: 반주를 선택해 주세요",
"audioEditSubject": "조치 필요: {artist} - {title}",
"audioEditSubjectFallback": "조치 필요",
"alertHeading": "노래방 비디오에 사용자의 입력이 필요합니다!"
},
"reviewReminder": {
"subject": "알림: 노래방 비디오가 검토를 기다리고 있습니다 — {artist} - {title}",
"subjectFallback": "알림: 노래방 비디오가 검토를 기다리고 있습니다",
"alertHeading": "노래방 비디오가 기다리고 있습니다!",
"reminderIntro": "노래방 비디오{song_name}의 검토가 준비되었음을 알려드립니다.",
"reviewButton": "비디오 검토하기",
"reviewInstructions": "검토하는 동안 가사가 정확한지 확인하고 원하는 반주 트랙을 선택할 수 있습니다. 보통 몇 분밖에 걸리지 않습니다!",
"helpOffer": "검토 과정에서 문제가 발생하면 이 이메일에 답장해 주세요. 기꺼이 도와드리겠습니다.",
"expiryWarning": "참고: 향후 24시간 이내에 검토를 완료하지 않으면 작업이 자동으로 만료되고 크레딧이 환불됩니다."
},
"reviewExpired": {
"subject": "노래방 비디오가 만료되었습니다 — {artist} - {title}",
"subjectFallback": "노래방 비디오가 만료되었습니다",
"cancelNotice": "48시간 이내에 검토가 완료되지 않아 노래방 비디오{song_name}가 자동으로 취소되었습니다.",
"refundNotice": "걱정하지 마세요. 크레딧이 환불되었습니다! 현재 잔액은 {credits_balance} {credits_word}입니다.",
"creditSingular": "크레딧",
"creditPlural": "크레딧",
"createNewPrompt": "크레딧을 사용하여 언제든지 새 노래방 비디오를 만들 수 있습니다:",
"createButton": "새 비디오 만들기",
"helpOffer": "검토 과정에서 문제가 있었거나 도움이 필요하시면 이 이메일에 답장해 주세요. 기꺼이 도와드리겠습니다!"
},
"creditDenied": {
"subject": "Nomad Karaoke 무료 크레딧 관련 안내",
"greeting": "안녕하세요,",
"thankYou": "Nomad Karaoke에 가입해 주셔서 감사합니다!",
"deniedMessage": "안타깝게도 이번에는 무료 {credit_type}을(를) 제공해 드리지 못했습니다. 저희 시스템에서 이것이 고객님의 첫 번째 계정이 아닐 수 있음을 시사하는 패턴을 감지했으며, 각 노래방 생성 작업에는 클라우드 컴퓨팅 및 API 수수료 등 실제 비용이 발생합니다.",
"mistakeNote": "이것이 실수라면 충분히 이해합니다! 진정한 신규 사용자이시라면 이 이메일에 답장하여 설립자인 Andrew에게 알려주세요. 그는 이 서비스를 구축했으며 고객님이 사용해 보실 수 있도록 기꺼이 무료 크레딧을 제공해 드릴 것입니다. 그 대가로 경험에 대한 솔직한 피드백만 부탁드립니다.",
"buyPrompt": "바로 시작하고 싶으시다면 크레딧을 구매하실 수도 있습니다:",
"buyButton": "크레딧 구매",
"costNote": "저희는 서비스를 저렴하게 제공하기 위해 비용을 낮게 유지하고 있으며, 이는 무료 크레딧 남용에 주의해야 함을 의미합니다. 이해해 주셔서 감사합니다!",
"welcomeCredits": "환영 크레딧",
"feedbackCredits": "피드백 보너스 크레딧"
},
"madeForYouConfirmation": {
"subject": "주문 확인: {artist} - {title} | Nomad Karaoke",
"thankYou": "주문해 주셔서 감사합니다!",
"orderDetails": "주문 세부 정보",
"orderId": "주문 ID:",
"artist": "아티스트:",
"title": "제목:",
"yourNotes": "요청 사항:",
"deliveryTime": "저희 팀이 {hours}시간 이내에 맞춤형 노래방 비디오를 제작해 드립니다.",
"deliveryNotice": "비디오가 준비되는 대로 다운로드 링크가 포함된 이메일을 받으시게 됩니다.",
"noAction": "아무런 조치도 필요하지 않습니다. 편안히 기다려 주시면 저희가 모든 것을 처리해 드리겠습니다!"
},
"shared": {
"footerHelp": "완벽하지 않은 부분이 있다면 이 이메일에 답장해 주세요. 수정해 드리겠습니다!"
},
"templates": {
"jobCompletion": {
"greeting": "안녕하세요 {name}님,",
"thanks": "주문해 주셔서 감사합니다!",
"youtubeLink": "YouTube에 게시된 노래방 비디오 링크입니다:",
"dropboxIntro": "완성된 모든 파일과 소스 파일이 포함된 Dropbox 폴더입니다. 포함된 항목:",
"fileList": "- \"(Final Karaoke Lossless).mkv\": 무손실 FLAC 오디오가 포함된 4K H264 통합 노래방 비디오\n- \"(Final Karaoke).mp4\": 타이틀/엔딩 화면이 포함된 4K H264/AAC 통합 노래방 비디오\n- \"(Final Karaoke 720p).mp4\": 720p H264/AAC 통합 노래방 비디오 (구형 시스템용 작은 파일)\n- \"(With Vocals).mp4\": 원본 보컬이 포함된 4K H264/AAC 따라 부르기 비디오\n- \"(Karaoke).mov\": MidiCo에서 출력된 노래방 비디오 (타이틀/엔딩 화면 없음)\n- \"(Title).mov\"/\"(End).mov\": 타이틀 카드 및 엔딩 화면 비디오\n- \"(Final Karaoke CDG).zip\": 구형/상업용 노래방 시스템을 위한 CDG+MP3 형식\n- \"(Final Karaoke TXT).zip\": Power Karaoke를 위한 TXT+MP3 형식\n- stems/*.flac: 무손실 형식의 분리된 다양한 반주 및 보컬 오디오 스템\n- lyrics/*.txt: 일반 텍스트 형식의 다양한 출처에서 가져온 노래 가사",
"fixOffer": "완벽하지 않은 부분이 있다면 알려주세요. 기꺼이 수정/보완해 드리겠습니다. 다른 형식이 필요하신 경우에도 변환해 드릴 수 있습니다!",
"feedbackRequest": "시간이 되신다면 피드백을 남겨주시면 정말 감사하겠습니다 (2분 소요):",
"signOff": "다시 한번 감사드리며 좋은 하루 보내세요!\n-Andrew",
"youtubeQueued": "YouTube 업로드가 대기열에 추가되었으며 자동으로 처리됩니다. 곧 링크가 포함된 후속 이메일을 받으시게 됩니다."
},
"actionLyrics": {
"greeting": "안녕하세요 {name}님,",
"ready": "\"{artist} - {title}\" 노래방 비디오의 검토 준비가 완료되었습니다!",
"instructions": "저희 시스템이 가사를 추출하고 동기화했지만, 일부 수정이 필요할 수 있습니다. 또한 원하는 반주 트랙(백보컬 포함 또는 미포함)을 선택하실 수 있습니다.",
"reviewPrompt": "가사를 검토하고 반주를 선택해 주세요:",
"duration": "이 작업은 보통 몇 분밖에 걸리지 않습니다.",
"signOff": "감사합니다!\n-Andrew"
},
"actionInstrumental": {
"greeting": "안녕하세요 {name}님,",
"almostDone": "\"{artist} - {title}\" 노래방 비디오가 거의 완성되었습니다!",
"instructions": "오디오를 여러 버전으로 분리했습니다. 최종 비디오에 사용할 반주 트랙을 선택해 주세요.",
"selectPrompt": "여기에서 반주를 선택하세요:",
"signOff": "감사합니다!\n-Andrew"
},
"youtubeComplete": {
"greeting": "안녕하세요 {name}님,",
"greatNews": "좋은 소식입니다! \"{artist} - {title}\" 노래방 비디오가 YouTube에 업로드되었습니다:",
"delayNote": "시스템에서 다른 업로드를 처리하는 동안 이 업로드가 잠시 지연되었으나, 이제 모두 완료되었습니다.",
"signOff": "감사합니다!\n-Andrew"
}
}
}
}
+338
View File
@@ -0,0 +1,338 @@
{
"auth": {
"unknownService": "Perkhidmatan tidak diketahui: {service}",
"invalidCredentials": "Perkhidmatan berikut memerlukan pengesahan semula: {services}",
"validCredentials": "Semua kelayakan yang diminta adalah sah",
"youtubeAuthInstructions": "Layari {verification_url} dan masukkan kod: {user_code}",
"youtubeAuthStartFailed": "Gagal memulakan pengesahan peranti YouTube: {error}",
"gdriveLinkInstructions": "Layari {verification_url} dan masukkan kod: {user_code}",
"gdriveAuthStartFailed": "Gagal memulakan pengesahan peranti Google Drive: {error}",
"discordAlertNotConfigured": "Webhook amaran Discord tidak dikonfigurasikan"
},
"jobs": {
"created": "Tugasan berjaya dicipta. Pemprosesan bermula.",
"authError": "Ralat pengesahan: tiada identiti pengguna tersedia",
"noDefaultTheme": "Tiada tema lalai dikonfigurasikan. Sila hubungi sokongan atau nyatakan theme_id.",
"notFound": "Tugasan tidak dijumpai",
"noPermissionAccess": "Anda tiada kebenaran untuk mengakses tugasan ini",
"noPermissionEdit": "Anda tiada kebenaran untuk mengedit tugasan ini",
"noPermissionDelete": "Anda tiada kebenaran untuk memadam tugasan ini",
"noPermissionModify": "Anda tiada kebenaran untuk mengubah suai tugasan ini",
"notCompleted": "Hanya tugasan yang selesai boleh diedit. Status semasa: {status}",
"alreadyBeingEdited": "Tugasan ini sedang diedit (output telah pun dipadamkan)",
"cleanupFailed": "Pembersihan gagal untuk {services}. Tugasan tidak diubah suai. Sila cuba lagi atau hubungi sokongan.",
"reopened": "Trek dibuka semula untuk diedit. Output sebelumnya telah dialih keluar.",
"invalidDatetimeFormat": "Format {field} tidak sah: {value}",
"listError": "Ralat menyenaraikan tugasan: {error}",
"deleteError": "Ralat memadam tugasan {job_id}: {error}",
"deletionPreview": "Tambah &confirm=true untuk melaksanakan pemadaman",
"deletionRequiresFilters": "Sekurang-kurangnya satu penapis (environment, client_id, status, created_before) diperlukan",
"bulkDeleteError": "Ralat memadam tugasan secara pukal: {error}",
"reviewNotReady": "Tugasan belum sedia untuk disemak (status semasa: {status})",
"correctionsUnavailable": "Data pembetulan tidak tersedia",
"audioUnavailable": "Audio tidak tersedia untuk disemak",
"reviewCannotStart": "Tidak dapat memulakan semakan",
"jobNotInReviewState": "Tugasan bukan dalam keadaan semakan (status semasa: {status})",
"correctionsProcessing": "Pembetulan disimpan. Panggil /complete-review apabila selesai.",
"editLogSaveFailed": "Ralat menyimpan log edit untuk tugasan {job_id}: {error}",
"stemsMissing": "Tugasan tidak mempunyai stem yang diperlukan (instrumental_clean dan/atau backing_vocals)",
"customInstrumentalFailed": "Ralat mencipta instrumental tersuai untuk tugasan {job_id}: {error}",
"audioProcessingFailed": "Gagal memproses fail audio: {error}",
"durationMismatch": "Ketidakpadanan tempoh: fail yang dimuat naik ialah {upload_duration}s tetapi audio asal ialah {original_duration}s. Instrumental mestilah tepat {original_duration}s (±0.5s).",
"reviewNotInState": "Tugasan bukan dalam keadaan semakan (status semasa: {status})",
"noLyricsDetected": "Tidak dapat menyelesaikan semakan: tiada lirik dikesan dalam audio. Ini boleh berlaku apabila input audio tiada vokal (cth. trek karaoke atau instrumental). Anda boleh kembali dan menampal lirik secara manual menggunakan 'Ganti Semua', atau batalkan tugasan ini dan cuba lagi dengan fail audio yang mengandungi vokal.",
"reviewCompleteStartRendering": "Semakan selesai. Pemaparan video bermula.",
"reviewCompleteError": "Ralat menyelesaikan semakan untuk tugasan {job_id}: {error}",
"instrumentalSelectionRequired": "instrumental_selection diperlukan. Mesti 'clean' atau 'with_backing'.",
"invalidInstrumentalSelection": "instrumental_selection tidak sah. Mesti salah satu daripada: {valid_selections}",
"instrumentalSelected": "Instrumental dipilih. Penjanaan video bermula.",
"instrumentalSelectionError": "Ralat memilih instrumental untuk tugasan {job_id}: {error}",
"downloadUrlsError": "Ralat mendapatkan URL muat turun: {error}"
},
"review": {
"jobNotFound": "Tugasan tidak dijumpai",
"reviewNotReady": "Tugasan belum sedia untuk disemak (status semasa: {status})",
"correctionsNotFound": "Data pembetulan tidak dijumpai. Pemprosesan lirik mungkin belum selesai.",
"correctionsLoadFailed": "Ralat memuatkan pembetulan: {error}",
"audioNotFound": "Fail audio tidak dijumpai",
"audioServeError": "Ralat menyediakan audio: {error}",
"instrumentalSelectionRequired": "instrumental_selection diperlukan. Mesti 'clean' atau 'with_backing'.",
"invalidInstrumentalSelection": "instrumental_selection tidak sah. Mesti salah satu daripada: {valid_selections}",
"reviewCompletedError": "Ralat menyelesaikan semakan: {error}",
"handlersUpdateNotImplemented": "Kemas kini pengendali belum dilaksanakan",
"lyricsAddError": "Gagal menambah lirik: {error}",
"lyricsAddInvalidRequest": "Permintaan tambah lirik tidak sah: {error}",
"lyricsSearchError": "Gagal mencari lirik: {error}",
"lyricsSearchInvalidRequest": "Permintaan cari lirik tidak sah: {error}",
"lyricsSearchNoResults": "Tiada lirik yang sepadan dijumpai daripada mana-mana pembekal",
"previewVideoGenerationError": "Gagal menjana video pratonton: {error}",
"previewVideoNotFound": "Video pratonton tidak dijumpai",
"previewVideoStreamError": "Ralat menstrim video pratonton: {error}",
"annotationSaveError": "Ralat menyimpan anotasi: {error}",
"waveformGenerationError": "Ralat menjana data bentuk gelombang: {error}",
"waveformNoAudio": "Tiada audio tersedia untuk bentuk gelombang",
"sessionSaveError": "Data pembetulan diperlukan"
},
"audioSearch": {
"notEnabled": "Carian audio tidak didayakan untuk penyewa ini",
"disabled": "Carian audio tidak tersedia",
"downloadError": "Muat turun gagal untuk tugasan {job_id}: {error}",
"jobNotFound": "Tugasan {job_id} tidak dijumpai",
"noSearchResults": "Tiada hasil carian tersedia",
"invalidSelectionIndex": "Indeks pilihan tidak sah {selection_index}. Julat sah: 0-{max}",
"selectionError": "Ralat semasa pemilihan audio untuk tugasan {job_id}: {error}",
"youtubeDownloadError": "Muat turun YouTube gagal: {error}",
"torrentDownloadError": "Tidak dapat memuat turun daripada {source} tanpa perkhidmatan flacfetch jauh. Konfigurasikan FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Tiada source_id atau remote_search_id tersedia untuk muat turun {source}",
"remoteDownloadCompleteNoPath": "Muat turun jauh selesai tetapi tiada laluan fail dikembalikan",
"spotifyDownloadError": "Tidak dapat memuat turun daripada Spotify tanpa perkhidmatan flacfetch jauh. Konfigurasikan FLACFETCH_API_URL.",
"genericDownloadError": "Jenis sumber tidak diketahui: {source}, cuba muat turun generik",
"jobNotFoundDuringDownload": "Tugasan {job_id} tidak dijumpai semasa muat turun latar belakang",
"selectAudioError": "Ralat memilih audio untuk tugasan {job_id}: {error}",
"searchAudioError": "Ralat mencari audio: {error}",
"searchCreatedSuccessfully": "Tugasan dicipta. Sedang mencari audio...",
"autoDownloadStarted": "Hasil terbaik dipilih secara automatik. Muat turun bermula..."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
"magicLinkSent": "Jika e-mel ini didaftarkan, anda akan menerima pautan log masuk sebentar lagi.",
"emailServiceNotConfigured": "Perkhidmatan e-mel tidak tersedia. Sila hubungi sokongan.",
"emailDomainNotAllowed": "Domain e-mel tidak dibenarkan untuk penyewa ini",
"invalidToken": "Token tidak sah",
"verifyError": "Pengesahan gagal: {message}",
"magicLinkSuccess": "Berjaya log masuk",
"logoutSuccess": "Berjaya log keluar",
"userNotFound": "Pengguna tidak dijumpai",
"creditPackagesError": "Ralat memuatkan pakej kredit: {error}",
"stripeSendError": "Ralat menghantar pautan daftar keluar Stripe: {error}",
"stripeWebhookProcessingError": "Ralat memproses webhook Stripe: {error}",
"feedbackSaveError": "Ralat menyimpan maklum balas: {error}",
"feedbackNotEligible": "Pengguna tidak layak untuk maklum balas"
},
"fileUpload": {
"invalidTheme": "Tema tidak dijumpai: {theme_id}. Gunakan GET /api/themes untuk menyenaraikan tema yang tersedia.",
"uploadSuccess": "Fail berjaya dimuat naik. Pemprosesan bermula.",
"uploadError": "Ralat memuat naik fail: {error}",
"urlDownloadError": "Ralat memuat turun daripada URL: {error}",
"invalidContentType": "Jenis kandungan tidak sah: {content_type}",
"fileSizeError": "Fail terlalu besar: {size}. Maksimum: {max_size}",
"invalidFileType": "Jenis fail tidak sah: {file_type}",
"multipleAudioFilesNotAllowed": "Hanya satu fail audio boleh dimuat naik",
"noAudioFileProvided": "Tiada fail audio disediakan",
"urlCreationSuccess": "Tugasan dicipta. URL muat naik dijana.",
"urlCreationError": "Ralat mencipta tugasan dengan URL muat naik: {error}",
"uploadsCompleteSuccess": "Muat naik selesai. Pemprosesan bermula.",
"uploadsCompleteError": "Ralat melengkapkan muat naik: {error}",
"noUploadedFiles": "Tiada fail muat naik dinyatakan",
"styleUploadUrlsSuccess": "URL muat naik gaya dijana.",
"styleUploadsCompleteSuccess": "Fail gaya dikemas kini. Pemprosesan dimulakan semula.",
"styleUploadsCompleteError": "Ralat melengkapkan muat naik gaya: {error}"
},
"catalog": {
"rateLimitExceeded": "Had kadar dilebihi. Maksimum {max_requests} permintaan katalog seminit.",
"catalogSearchError": "Ralat mencari katalog: {error}",
"communityCheckError": "Ralat menyemak versi komuniti: {error}"
},
"themes": {
"themesLoadError": "Gagal memuatkan tema",
"themeNotFound": "Tema tidak dijumpai: {theme_id}",
"themeLoadError": "Gagal memuatkan tema",
"previewNotAvailable": "Tiada pratonton tersedia untuk tema: {theme_id}",
"previewLoadError": "Gagal memuatkan pratonton tema",
"youtubeDescriptionNotFound": "Tema tidak dijumpai: {theme_id}",
"youtubeDescriptionLoadError": "Gagal memuatkan huraian YouTube"
},
"tenant": {
"assetNotFound": "Aset tidak dijumpai"
},
"push": {
"disabled": "Pemberitahuan tolak tidak didayakan",
"userEmailNotAvailable": "E-mel pengguna tidak tersedia",
"missingEncryptionKeys": "Ketiadaan kunci yang diperlukan (p256dh, auth)",
"subscriptionSaveFailed": "Gagal menyimpan langganan",
"subscriptionRegistered": "Langganan tolak berjaya didaftarkan",
"subscriptionNotFound": "Langganan dialih keluar (atau tidak dijumpai)",
"subscriptionRemoved": "Langganan tolak berjaya dialih keluar",
"testNotificationSent": "Pemberitahuan ujian dihantar ke {sent_count} peranti"
},
"pushNotifications": {
"reviewLyricsTitle": "Semak Lirik",
"reviewLyricsBody": "\"{title}\" oleh {artist} memerlukan semakan lirik",
"selectInstrumentalTitle": "Pilih Instrumental",
"selectInstrumentalBody": "\"{title}\" oleh {artist} memerlukan pemilihan instrumental",
"videoReadyTitle": "Video Sedia!",
"videoReadyBody": "Video karaoke anda untuk \"{title}\" oleh {artist} sedia untuk dimuat turun"
},
"admin": {
"invalidDomainFormat": "Format domain tidak sah",
"domainAddedToBl": "Domain '{domain}' ditambahkan pada senarai sekat domain pakai buang",
"domainNotFoundInBl": "Domain tidak dijumpai dalam senarai sekat",
"domainRemovedFromBl": "Domain '{domain}' dialih keluar daripada senarai sekat domain pakai buang",
"domainAddedToAllowlist": "Domain '{domain}' ditambahkan pada senarai benarkan",
"domainNotFoundInAllowlist": "Domain tidak dijumpai dalam senarai benarkan",
"domainRemovedFromAllowlist": "Domain '{domain}' dialih keluar daripada senarai benarkan",
"syncComplete": "Menyegerakkan {external_count} domain luaran ({added} ditambah, {removed} dialih keluar)",
"invalidEmailFormat": "Format e-mel tidak sah",
"emailAddedToBl": "E-mel '{email}' ditambahkan pada senarai e-mel yang disekat",
"emailNotFoundInBl": "E-mel tidak dijumpai dalam senarai sekat",
"emailRemovedFromBl": "E-mel '{email}' dialih keluar daripada senarai e-mel yang disekat",
"invalidIPAddress": "Alamat IP tidak sah",
"ipAddedToBl": "IP '{ip_address}' ditambahkan pada senarai IP yang disekat",
"ipNotFoundInBl": "IP tidak dijumpai dalam senarai sekat",
"ipRemovedFromBl": "IP '{ip_address}' dialih keluar daripada senarai IP yang disekat",
"youtubeUploadNotFound": "Muat naik tidak dijumpai atau bukan dalam keadaan boleh dicuba semula untuk tugasan {job_id}",
"youtubeUploadQueuedForRetry": "Muat naik YouTube untuk tugasan {job_id} dibaris gilir untuk dicuba semula",
"youtubeQueueProcessingStarted": "Pemprosesan baris gilir YouTube bermula di latar belakang"
},
"rateLimits": {
"configNotFound": "Konfigurasi had kadar tidak dijumpai: {config_id}",
"configUpdateError": "Ralat mengemas kini konfigurasi had kadar: {error}"
},
"errors": {
"insufficientCredits": "Kredit tidak mencukupi untuk operasi ini",
"insufficientCreditsBuyUrl": "/#pricing"
},
"emails": {
"magicLink": {
"subject": "Log masuk ke {brand_name}",
"greeting": "Hai,",
"signInPrompt": "Klik butang di bawah untuk log masuk ke {brand_name}:",
"signInButton": "Log Masuk",
"expiryWarning": "Pautan ini tamat tempoh dalam 15 minit dan hanya boleh digunakan sekali.",
"fallbackLink": "Jika butang tidak berfungsi, salin dan tampal pautan ini ke dalam pelayar anda:",
"ignoreNote": "Jika anda tidak meminta e-mel ini, anda boleh mengabaikannya."
},
"welcome": {
"subject": "Selamat datang ke Nomad Karaoke!",
"welcomeGreeting": "Selamat datang ke Nomad Karaoke!",
"turnAnySong": "Tukar mana-mana lagu menjadi video karaoke profesional dalam beberapa minit.",
"freeCreditsLabel": "Kredit Percuma",
"freeCreditsNote": "Setiap kredit mencipta satu video karaoke profesional",
"howItWorks": "Begini cara ia berfungsi:",
"step1Title": "1. Cari lagu",
"step1Desc": "Masukkan artis dan tajuk, dan kami akan mencari audio berkualiti tinggi.",
"step2Title": "2. Sistem kami melakukan keajaibannya",
"step2Desc": "Kami mengasingkan vokal, menyalin lirik, dan menyegerakkan semuanya dengan sempurna.",
"step3Title": "3. Semak & sesuaikan",
"step3Desc": "Perhalusi lirik jika perlu, pilih instrumental anda.",
"step4Title": "4. Dapatkan video anda",
"step4Desc": "Muat turun video karaoke 4K anda atau muat naik terus ke YouTube.",
"feedbackBonus": "Lengkapkan 2 video dan dapatkan 2 lagi kredit percuma dengan berkongsi maklum balas anda!",
"getStartedButton": "Mula Sekarang"
},
"creditsAdded": {
"subject": "{credits} kredit ditambahkan pada akaun Nomad Karaoke anda",
"greatNews": "Berita baik!",
"creditsAddedMessage": "{credits} kredit telah ditambahkan pada akaun anda.",
"yourBalance": "Baki anda:",
"credits": "kredit",
"eachCreditLets": "Setiap kredit membolehkan anda mencipta satu video karaoke profesional dengan:",
"featureVocalSeparation": "Pengasingan vokal/instrumental dikuasakan AI",
"featureLyrics": "Lirik disegerakkan dengan pemasaan tahap perkataan",
"feature4k": "Output video 4K",
"featureYoutube": "Muat naik YouTube",
"createButton": "Cipta Karaoke Sekarang"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (Video karaoke anda sudah sedia!)",
"subject": "{artist} - {title} (Video karaoke anda sudah sedia!)",
"subjectFallback": "Video karaoke anda sudah sedia!"
},
"youtubeUpload": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (Muat naik YouTube sedia!)",
"subject": "{artist} - {title} (Muat naik YouTube sedia!)",
"subjectFallback": "Muat naik YouTube anda sudah sedia!"
},
"actionReminder": {
"lyricsSubject": "Tindakan diperlukan: Semak lirik untuk {artist} - {title}",
"lyricsSubjectFallback": "Tindakan diperlukan: Semak lirik",
"instrumentalSubject": "Tindakan diperlukan: Pilih instrumental untuk {artist} - {title}",
"instrumentalSubjectFallback": "Tindakan diperlukan: Pilih instrumental",
"audioEditSubject": "Tindakan diperlukan untuk {artist} - {title}",
"audioEditSubjectFallback": "Tindakan diperlukan",
"alertHeading": "Video karaoke anda memerlukan input daripada anda!"
},
"reviewReminder": {
"subject": "Peringatan: Video karaoke anda sedang menunggu untuk disemak — {artist} - {title}",
"subjectFallback": "Peringatan: Video karaoke anda sedang menunggu untuk disemak",
"alertHeading": "Video karaoke anda sedang menunggu anda!",
"reminderIntro": "Sekadar peringatan mesra bahawa video karaoke anda{song_name} sedia untuk disemak.",
"reviewButton": "Semak Video Anda",
"reviewInstructions": "Semasa semakan, anda boleh menyemak lirik adalah betul dan memilih trek instrumental pilihan anda. Ia biasanya hanya mengambil masa beberapa minit!",
"helpOffer": "Jika anda menghadapi sebarang masalah dengan proses semakan, balas sahaja e-mel ini dan saya dengan senang hati akan membantu anda.",
"expiryWarning": "Sila ambil perhatian: jika semakan tidak diselesaikan dalam masa 24 jam yang akan datang, tugasan akan tamat tempoh secara automatik dan kredit anda akan dikembalikan."
},
"reviewExpired": {
"subject": "Video karaoke anda telah tamat tempoh — {artist} - {title}",
"subjectFallback": "Video karaoke anda telah tamat tempoh",
"cancelNotice": "Video karaoke anda{song_name} telah dibatalkan secara automatik kerana semakan tidak diselesaikan dalam masa 48 jam.",
"refundNotice": "Jangan risau — kredit anda telah dikembalikan! Baki semasa anda ialah {credits_balance} {credits_word}.",
"creditSingular": "kredit",
"creditPlural": "kredit",
"createNewPrompt": "Anda boleh mencipta video karaoke baharu pada bila-bila masa menggunakan kredit anda:",
"createButton": "Cipta Video Baharu",
"helpOffer": "Jika anda menghadapi sebarang masalah dengan proses semakan atau memerlukan bantuan, balas sahaja e-mel ini — saya sedia membantu!"
},
"creditDenied": {
"subject": "Mengenai kredit percuma Nomad Karaoke anda",
"greeting": "Hai,",
"thankYou": "Terima kasih kerana mendaftar untuk Nomad Karaoke!",
"deniedMessage": "Malangnya, kami tidak dapat memberikan {credit_type} percuma anda kali ini. Sistem kami mengesan corak yang menunjukkan ini mungkin bukan akaun pertama anda dengan kami, dan setiap tugasan penjanaan karaoke menelan kos wang sebenar dalam pengkomputeran awan dan yuran API.",
"mistakeNote": "Kami amat memahami jika ini adalah satu kesilapan! Jika anda pengguna baharu yang tulen, sila balas e-mel ini dan beritahu Andrew (pengasas). Beliau membina perkhidmatan ini dan dengan senang hati akan memberikan anda beberapa kredit percuma untuk mencubanya — beliau hanya meminta anda memberikan maklum balas jujur mengenai pengalaman tersebut sebagai balasan.",
"buyPrompt": "Jika anda ingin bermula segera, anda juga boleh membeli kredit:",
"buyButton": "Beli Kredit",
"costNote": "Kami mengekalkan kos yang rendah supaya kami dapat menawarkan perkhidmatan pada harga berpatutan, yang bermaksud kami perlu berhati-hati dengan penyalahgunaan kredit percuma. Terima kasih kerana memahami!",
"welcomeCredits": "kredit alu-aluan",
"feedbackCredits": "kredit bonus maklum balas"
},
"madeForYouConfirmation": {
"subject": "Pesanan Disahkan: {artist} - {title} | Nomad Karaoke",
"thankYou": "Terima Kasih atas Pesanan Anda!",
"orderDetails": "Butiran Pesanan",
"orderId": "ID Pesanan:",
"artist": "Artis:",
"title": "Tajuk:",
"yourNotes": "Nota Anda:",
"deliveryTime": "Pasukan kami akan mencipta video karaoke tersuai anda dalam masa {hours} jam.",
"deliveryNotice": "Anda akan menerima e-mel dengan pautan muat turun sebaik sahaja video anda sedia.",
"noAction": "Tiada tindakan diperlukan — berehat dan kami akan menguruskan semuanya!"
},
"shared": {
"footerHelp": "Jika ada yang tidak sempurna, balas sahaja e-mel ini dan saya akan membetulkannya!"
},
"templates": {
"jobCompletion": {
"greeting": "Hai {name},",
"thanks": "Terima kasih atas pesanan anda!",
"youtubeLink": "Berikut ialah pautan untuk video karaoke yang diterbitkan ke YouTube:",
"dropboxIntro": "Berikut ialah folder Dropbox dengan semua fail yang telah siap dan fail sumber, termasuk:",
"fileList": "- \"(Final Karaoke Lossless).mkv\": video karaoke gabungan dalam 4K H264 dengan audio FLAC tanpa kerugian\n- \"(Final Karaoke).mp4\": video karaoke gabungan dengan skrin tajuk/akhir dalam 4K H264/AAC\n- \"(Final Karaoke 720p).mp4\": video karaoke gabungan dalam 720p H264/AAC (fail lebih kecil untuk sistem lama)\n- \"(With Vocals).mp4\": video nyanyi bersama dalam 4K H264/AAC dengan vokal asal\n- \"(Karaoke).mov\": output video karaoke daripada MidiCo (tiada skrin tajuk/akhir)\n- \"(Title).mov\"/\"(End).mov\": video kad tajuk dan skrin akhir\n- \"(Final Karaoke CDG).zip\": format CDG+MP3 untuk sistem karaoke lama/komersial\n- \"(Final Karaoke TXT).zip\": format TXT+MP3 untuk Power Karaoke\n- stems/*.flac: pelbagai stem audio instrumental dan vokal yang diasingkan dalam format tanpa kerugian\n- lyrics/*.txt lirik lagu daripada pelbagai sumber dalam format teks biasa",
"fixOffer": "Beritahu saya jika ada yang tidak sempurna dan saya dengan senang hati akan mengubah suai / membetulkannya, atau jika anda memerlukannya dalam format lain, saya mungkin boleh menukarnya untuk anda!",
"feedbackRequest": "Jika anda ada masa, saya amat menghargai maklum balas anda (mengambil masa 2 minit):",
"signOff": "Terima kasih sekali lagi dan semoga hari anda menyenangkan!\n-Andrew",
"youtubeQueued": "Muat naik YouTube anda telah dibaris gilir dan akan diproses secara automatik. Anda akan menerima e-mel susulan dengan pautan sebentar lagi."
},
"actionLyrics": {
"greeting": "Hai {name},",
"ready": "Video karaoke anda untuk \"{artist} - {title}\" sedia untuk disemak!",
"instructions": "Sistem kami telah menyalin dan menyegerakkan lirik, tetapi ia mungkin memerlukan beberapa pembetulan. Anda juga akan dapat memilih trek instrumental pilihan anda (dengan atau tanpa vokal latar).",
"reviewPrompt": "Sila semak lirik anda dan pilih instrumental:",
"duration": "Ini biasanya hanya mengambil masa beberapa minit.",
"signOff": "Terima kasih!\n-Andrew"
},
"actionInstrumental": {
"greeting": "Hai {name},",
"almostDone": "Video karaoke anda untuk \"{artist} - {title}\" hampir siap!",
"instructions": "Kami telah mengasingkan audio kepada versi yang berbeza. Sila pilih trek instrumental yang anda ingin gunakan untuk video akhir.",
"selectPrompt": "Pilih instrumental anda di sini:",
"signOff": "Terima kasih!\n-Andrew"
},
"youtubeComplete": {
"greeting": "Hai {name},",
"greatNews": "Berita baik! Video karaoke anda untuk \"{artist} - {title}\" telah dimuat naik ke YouTube:",
"delayNote": "Muat naik ini tertangguh seketika semasa sistem kami memproses muat naik lain, tetapi semuanya sudah sedia sekarang.",
"signOff": "Terima kasih!\n-Andrew"
}
}
}
}
Loaded 100 of 408 files, more files were not shown because too many files have changed in this diff. Show more