Compare commits

...
3 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude fd92040dc7 feat: Make non-interactive mode job-specific instead of global toggle (#162)
## Summary

- Changes non-interactive/auto mode from a global toggle to a per-job
option selected during job creation
- Adds clear warning to users that skipping lyrics review will likely
result in mistakes
- Uses existing backing vocals analyzer for smart instrumental selection
in non-interactive mode

## Changes

### Backend
- Added `non_interactive: bool = False` field to Job and JobCreate
models
- Accept `non_interactive` in all job creation endpoints (upload, URL,
audio search)

### Frontend
- Added checkbox with warning in JobSubmission form for all 3 tabs
(Search, Upload, URL)
- Updated AutoProcessor to check `job.non_interactive` instead of global
flag
- AutoProcessor now uses backing vocals analyzer recommendation for
instrumental selection
- Added "Auto" badge on JobCard for non-interactive jobs
- Removed global auto mode toggle button and banner from header
- Deleted unused `auto-mode.ts` store and its tests
- Updated JobCard tests for new per-job behavior

## Testing
- [x] Backend tests pass (57 passed)
- [x] Frontend unit tests pass (128 passed)
- [x] Version bumped to 0.86.7

## Review
- [ ] CodeRabbit CLI review was rate limited - skipping for this PR

@coderabbitai ignore

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

Co-authored-by: Claude <noreply@anthropic.com>
2026-01-03 01:09:01 -05:00
Andrew Beveridge ☄️andClaude Opus 4.5 30f6fc6c05 perf: Improve cloud karaoke generation performance (#160)
## Summary

Infrastructure changes to address 3x performance gap between local and
cloud karaoke generation:

- **Keep Cloud Run warm** with `min-instances: 4` (eliminates 77s cold
starts)
- **Upgrade FFmpeg** from Debian 5.1.8 to static 7.0.2 (~20-40% faster
encoding)
- **Add diagnostics** to `/api/health/detailed` endpoint (FFmpeg
version, CPU info)
- **Add performance scripts** for benchmarking and comparison

## Changes

- `.github/workflows/ci.yml`: Changed `--min-instances` from 0 to 4
- `backend/Dockerfile.base`: Replace `apt-get install ffmpeg` with John
Van Sickle's static build
- `backend/api/routes/health.py`: Add `get_system_info()` and
`get_ffmpeg_info()` to detailed health endpoint
- `docs/DEVELOPMENT.md`: Add new scripts to Key Scripts table
- `docs/LESSONS-LEARNED.md`: Document Cloud Run cold start and FFmpeg
optimization findings
- `scripts/benchmark_ffmpeg.py`: Isolated FFmpeg encoding benchmark
- `scripts/compare_local_vs_remote.py`: Compare local vs cloud
karaoke-gen performance

## Expected Performance Improvement

| Metric | Before | After |
|--------|--------|-------|
| Cold start | 77s | 0s (warm instances) |
| Video encoding | 174s | ~120-140s (FFmpeg 7.x) |

## Testing

- [ ] Tests pass locally
- [x] FFmpeg static build verified in Docker container
- [ ] Manual testing after deploy

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 00:00:44 -05:00
Andrew Beveridge ☄️andClaude dfb2ebc184 feat(frontend): migrate from MailSlurp to testmail.app for E2E testing (#159)
## Summary

- Replace MailSlurp email testing service with testmail.app for E2E
magic link authentication tests
- Simpler API with namespace-based email addresses
(`{namespace}.{tag}@inbox.testmail.app`)
- No new dependencies - uses native `fetch` instead of mailslurp-client

## Changes

- **`frontend/e2e/helpers/email-testing.ts`** - Complete rewrite using
testmail.app JSON API
  - Uses `livequery=true` to wait for emails (no polling needed)
  - Generates unique tags per test run to avoid collisions
  - Same `EmailHelper` interface maintained for minimal test changes
- **`frontend/e2e/production/full-user-journey.spec.ts`** - Update env
var references and messages
- **`frontend/playwright.record.config.ts`** - Update env var comment
- **`frontend/package.json`** - Remove `mailslurp-client` dependency,
bump version to 0.79.0
- **`frontend/.env.local.example`** - New file documenting required env
vars for local testing
- **`docs/DEVELOPMENT.md`** - Add testmail.app env vars to frontend
section

## Environment Variables

| Old | New |
|-----|-----|
| `MAILSLURP_API_KEY` | `TESTMAIL_API_KEY` |
| (none) | `TESTMAIL_NAMESPACE` |

**Note:** GitHub Actions org secrets already configured with new env
vars.

## Testing

- [x] Backend tests pass (`make test` - 57 tests)
- [x] Frontend unit tests pass (139 tests)
- [x] Frontend E2E tests pass (64 tests)
- [x] TypeScript compilation clean for changed files

## Review

- [x] Local CodeRabbit CLI review completed
- [x] Review feedback addressed (removed exposed credentials from plan
file)

@coderabbitai ignore

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-01-02 22:24:19 -05:00
28 changed files with 1883 additions and 514 deletions

No files matched your search

@@ -0,0 +1,106 @@
# Plan: Migrate from MailSlurp to testmail.app
**Created:** 2026-01-02
**Branch:** feat/sess-20260102-2109-migrate-mailslurp-testmail
**Status:** Complete
## Overview
Replace MailSlurp email testing service with testmail.app for E2E testing of magic link authentication. testmail.app uses a simpler API with namespace-based email addresses that require no inbox creation/deletion - emails just arrive at `{namespace}.{tag}@inbox.testmail.app`.
## Requirements
- [x] Remove all code referencing MailSlurp
- [x] Remove `mailslurp-client` npm dependency
- [x] Implement testmail.app API integration
- [x] Update environment variable names (`TESTMAIL_API_KEY`, `TESTMAIL_NAMESPACE`)
- [x] Maintain same `EmailHelper` interface for minimal test changes
- [x] Update archive docs to note migration (optional - historical accuracy)
## Technical Approach
### API Differences
| Feature | MailSlurp | testmail.app |
|---------|-----------|--------------|
| Email format | Random `xxx@mailslurp.com` | `{namespace}.{tag}@inbox.testmail.app` |
| Inbox creation | Required (`createInbox()`) | Not needed - use any tag |
| Inbox deletion | Required (`deleteInbox()`) | Not needed |
| Get emails | `waitForLatestEmail(inboxId)` | GET `/api/json?apikey=X&namespace=Y&tag=Z&livequery=true` |
| Auth | API key in constructor | API key as query param |
| Email body | `email.body` | `email.html` or `email.text` |
### Implementation Strategy
1. **Keep same `EmailHelper` interface** - `createInbox()`, `waitForEmail()`, `extractMagicLink()`, `deleteInbox()`
2. **Use testmail.app's live query feature** - `livequery=true` waits for email to arrive (up to timeout)
3. **Generate unique tags** - Use timestamp + random suffix for each test run to avoid collisions
4. **Inbox becomes a simple object** - `{ id: tag, emailAddress: '{namespace}.{tag}@inbox.testmail.app' }`
5. **Delete becomes no-op** - testmail.app emails auto-expire, no cleanup needed
### Environment Variables
| Old | New |
|-----|-----|
| `MAILSLURP_API_KEY` | `TESTMAIL_API_KEY` |
| (none) | `TESTMAIL_NAMESPACE` |
Values: Set via environment variables (see `frontend/.env.local.example`)
## Implementation Steps
1. [x] **Update `email-testing.ts`** - Replace MailSlurp implementation with testmail.app
- Remove `mailslurp-client` import
- Add testmail.app API fetch implementation
- Use native `fetch` (no new dependencies)
- Generate unique tag for each "inbox"
- Implement `livequery=true` for waiting
- Adapt email body extraction (`html`/`text` instead of `body`)
2. [x] **Update `full-user-journey.spec.ts`** - Change references
- Update doc comments (env var name)
- Update error messages
- Update console logs
3. [x] **Update `playwright.record.config.ts`** - Change env var comment
4. [x] **Update `package.json`** - Remove `mailslurp-client` dependency
5. [x] **Run `npm install`** - Update package-lock.json
6. [x] **Create `.env.local.example`** - Document required env vars for local testing
7. [x] **Update archive docs** - Skipped intentionally; historical docs preserved for accuracy
## Files to Create/Modify
| File | Action | Description |
|------|--------|-------------|
| `frontend/e2e/helpers/email-testing.ts` | Modify | Replace MailSlurp with testmail.app |
| `frontend/e2e/production/full-user-journey.spec.ts` | Modify | Update env var refs and messages |
| `frontend/playwright.record.config.ts` | Modify | Update env var comment |
| `frontend/package.json` | Modify | Remove `mailslurp-client` |
| `frontend/package-lock.json` | Modify | Auto-updated by npm install |
| `frontend/.env.local.example` | Create | Document env vars for local testing |
## Testing Strategy
- **Manual testing**: Run production E2E test with testmail.app credentials
```bash
cd frontend
TESTMAIL_API_KEY=your-api-key \
TESTMAIL_NAMESPACE=your-namespace \
npm run test:e2e:prod:headed
```
- **Verify**: Email received, magic link extracted, auth flow completes
- **CI testing**: Env vars already configured in GitHub Actions org secrets
## Open Questions
None - requirements are clear.
## Rollback Plan
1. Revert the commit
2. Run `npm install` to restore mailslurp-client
3. Re-add MAILSLURP_API_KEY to secrets if removed
+1 -1
View File
@@ -930,7 +930,7 @@ jobs:
--timeout 1800 \
--concurrency 1 \
--max-instances 50 \
--min-instances 0 \
--min-instances 4 \
--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://nomadkaraoke--audio-separator-api.modal.run,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD" \
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,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"
+13 -1
View File
@@ -10,14 +10,26 @@ FROM python:3.11-slim
# Note: Transmission daemon removed - torrent downloads now handled by
# dedicated flacfetch VM service (see docs/00-current-plan/TORRENT-SERVICE-PLAN.md)
RUN apt-get update && apt-get install -y \
ffmpeg \
libsndfile1 \
libsox-dev \
sox \
build-essential \
curl \
xz-utils \
&& rm -rf /var/lib/apt/lists/*
# Install optimized static FFmpeg build (7.0.2) instead of Debian package (5.1.8)
# John Van Sickle's builds are compiled with better optimizations for x86_64
# This provides ~20-40% performance improvement for encoding tasks
# Source: https://johnvansickle.com/ffmpeg/
RUN curl -L https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-amd64-static.tar.xz -o /tmp/ffmpeg.tar.xz && \
tar -xf /tmp/ffmpeg.tar.xz -C /tmp && \
cp /tmp/ffmpeg-*-amd64-static/ffmpeg /usr/local/bin/ && \
cp /tmp/ffmpeg-*-amd64-static/ffprobe /usr/local/bin/ && \
chmod +x /usr/local/bin/ffmpeg /usr/local/bin/ffprobe && \
rm -rf /tmp/ffmpeg* && \
ffmpeg -version
# Set working directory
WORKDIR /app
+5 -1
View File
@@ -117,6 +117,9 @@ class AudioSearchRequest(BaseModel):
# Style params JSON and related assets (background images, fonts)
style_files: Optional[List[StyleFileRequest]] = Field(None, description="Style files to upload (style_params JSON, backgrounds, fonts)")
# Non-interactive mode
non_interactive: bool = Field(False, description="Skip interactive steps (lyrics review, instrumental selection)")
class AudioSearchResultResponse(BaseModel):
"""A single audio search result.
@@ -552,10 +555,11 @@ async def search_audio(
audio_search_title=body.title,
auto_download=body.auto_download,
request_metadata=request_metadata,
non_interactive=body.non_interactive,
)
job = job_manager.create_job(job_create)
job_id = job.job_id
logger.info(f"Created job {job_id} for audio search: {body.artist} - {body.title}")
# Update job with audio search fields
+12
View File
@@ -92,6 +92,9 @@ class CreateJobFromUrlRequest(BaseModel):
backing_vocals_models: Optional[List[str]] = Field(None, description="Models for backing vocals separation")
other_stems_models: Optional[List[str]] = Field(None, description="Models for other stems")
# Non-interactive mode
non_interactive: bool = Field(False, description="Skip interactive steps (lyrics review, instrumental selection)")
class CreateJobFromUrlResponse(BaseModel):
"""Response from creating a job from URL."""
@@ -150,6 +153,9 @@ class CreateJobWithUploadUrlsRequest(BaseModel):
prep_only: bool = Field(False, description="Stop after review phase, don't run finalisation")
keep_brand_code: Optional[str] = Field(None, description="Preserve existing brand code instead of generating new one")
# Non-interactive mode
non_interactive: bool = Field(False, description="Skip interactive steps (lyrics review, instrumental selection)")
class SignedUploadUrl(BaseModel):
"""Signed URL for uploading a file."""
@@ -419,6 +425,8 @@ async def upload_and_create_job(
clean_instrumental_model: Optional[str] = Form(None, description="Model for clean instrumental separation (e.g., model_bs_roformer_ep_317_sdr_12.9755.ckpt)"),
backing_vocals_models: Optional[str] = Form(None, description="Comma-separated list of models for backing vocals separation"),
other_stems_models: Optional[str] = Form(None, description="Comma-separated list of models for other stems (bass, drums, guitar, etc.)"),
# Non-interactive mode
non_interactive: bool = Form(False, description="Skip interactive steps (lyrics review, instrumental selection)"),
):
"""
Upload an audio file and create a karaoke generation job with full style configuration.
@@ -606,6 +614,8 @@ async def upload_and_create_job(
other_stems_models=parsed_other_stems_models,
# Request metadata for tracking and filtering
request_metadata=request_metadata,
# Non-interactive mode
non_interactive=non_interactive,
)
job = job_manager.create_job(job_create)
job_id = job.job_id
@@ -1111,6 +1121,7 @@ async def create_job_with_upload_urls(
backing_vocals_models=body.backing_vocals_models,
other_stems_models=body.other_stems_models,
request_metadata=request_metadata,
non_interactive=body.non_interactive,
)
job = job_manager.create_job(job_create)
job_id = job.job_id
@@ -1526,6 +1537,7 @@ async def create_job_from_url(
backing_vocals_models=body.backing_vocals_models,
other_stems_models=body.other_stems_models,
request_metadata=request_metadata,
non_interactive=body.non_interactive,
)
job = job_manager.create_job(job_create)
job_id = job.job_id
+110
View File
@@ -3,6 +3,8 @@ Health check routes.
"""
import os
import logging
import subprocess
import platform
from fastapi import APIRouter
from typing import Dict, Any, Optional
@@ -15,6 +17,108 @@ router = APIRouter()
logger = logging.getLogger(__name__)
def get_system_info() -> Dict[str, Any]:
"""Get system information for performance analysis."""
info = {
"platform": platform.system(),
"platform_release": platform.release(),
"python_version": platform.python_version(),
}
# Get CPU info
try:
cpu_count = os.cpu_count() or 0
info["cpu_count"] = cpu_count
# Try to get more detailed CPU info on Linux
if platform.system() == "Linux":
try:
with open("/proc/cpuinfo", "r") as f:
for line in f:
if "model name" in line:
info["cpu_model"] = line.split(":")[1].strip()
break
except Exception:
pass
except Exception as e:
info["cpu_error"] = str(e)
# Get memory info
try:
if platform.system() == "Linux":
with open("/proc/meminfo", "r") as f:
for line in f:
if line.startswith("MemTotal:"):
mem_kb = int(line.split()[1])
info["memory_gb"] = round(mem_kb / (1024 * 1024), 1)
break
except Exception as e:
info["memory_error"] = str(e)
return info
def get_ffmpeg_info() -> Dict[str, Any]:
"""Get FFmpeg version and configuration for debugging encoding performance."""
try:
# Get FFmpeg version
result = subprocess.run(
["ffmpeg", "-version"],
capture_output=True,
text=True,
timeout=10
)
if result.returncode == 0:
lines = result.stdout.split("\n")
version_line = lines[0] if lines else "unknown"
# Check for hardware acceleration support
hw_accel = {}
config_result = subprocess.run(
["ffmpeg", "-hwaccels"],
capture_output=True,
text=True,
timeout=10
)
if config_result.returncode == 0:
hw_lines = config_result.stdout.strip().split("\n")
hw_accel["available"] = [h.strip() for h in hw_lines[1:] if h.strip()]
# Check encoder availability
encoders = {}
encoder_result = subprocess.run(
["ffmpeg", "-encoders"],
capture_output=True,
text=True,
timeout=10
)
if encoder_result.returncode == 0:
encoder_output = encoder_result.stdout
# Check for specific encoders we care about
encoders["libx264"] = "libx264" in encoder_output
encoders["h264_nvenc"] = "h264_nvenc" in encoder_output
encoders["h264_vaapi"] = "h264_vaapi" in encoder_output
encoders["hevc_nvenc"] = "hevc_nvenc" in encoder_output
return {
"available": True,
"version": version_line,
"hw_acceleration": hw_accel,
"encoders": encoders,
}
else:
return {
"available": False,
"error": result.stderr[:500] if result.stderr else "Unknown error",
}
except subprocess.TimeoutExpired:
return {"available": False, "error": "Timeout getting FFmpeg info"}
except FileNotFoundError:
return {"available": False, "error": "FFmpeg not found"}
except Exception as e:
return {"available": False, "error": str(e)}
def check_transmission_status() -> Dict[str, Any]:
"""Check if Transmission daemon is available and responsive."""
try:
@@ -141,10 +245,16 @@ async def detailed_health_check() -> Dict[str, Any]:
if not stripe_status["configured"]:
logger.warning("Stripe service not configured - payments will not work")
# Get system and FFmpeg info for performance analysis
system_info = get_system_info()
ffmpeg_info = get_ffmpeg_info()
return {
"status": "healthy",
"service": "karaoke-gen-backend",
"version": VERSION,
"system": system_info,
"ffmpeg": ffmpeg_info,
"dependencies": {
"transmission_local": transmission_status,
"flacfetch_remote": flacfetch_status,
+2
View File
@@ -204,6 +204,7 @@ class Job(BaseModel):
youtube_description: Optional[str] = None # YouTube video description
webhook_url: Optional[str] = None # Webhook for notifications
user_email: Optional[str] = None # Email for notifications
non_interactive: bool = False # Skip interactive steps (lyrics review, instrumental selection)
# Theme configuration (pre-made themes from GCS)
theme_id: Optional[str] = None # Theme identifier (e.g., "nomad", "default")
@@ -419,6 +420,7 @@ class JobCreate(BaseModel):
youtube_description: Optional[str] = None
webhook_url: Optional[str] = None
user_email: Optional[str] = None
non_interactive: bool = False # Skip interactive steps (lyrics review, instrumental selection)
# Theme configuration (pre-made themes from GCS)
theme_id: Optional[str] = None # Theme identifier (e.g., "nomad", "default")
+11 -1
View File
@@ -151,7 +151,11 @@ ADMIN_TOKENS=token1,token2
```bash
NEXT_PUBLIC_API_URL=http://localhost:8000
KARAOKE_ACCESS_TOKEN=... # For E2E tests
# For E2E tests (see frontend/.env.local.example)
KARAOKE_ACCESS_TOKEN=... # Skip email enrollment
TESTMAIL_API_KEY=... # testmail.app API key
TESTMAIL_NAMESPACE=... # testmail.app namespace
```
## Key Scripts
@@ -162,6 +166,12 @@ KARAOKE_ACCESS_TOKEN=... # For E2E tests
| `./scripts/run-backend-local.sh` | Start backend with emulators |
| `./scripts/start-emulators.sh` | Start emulators only |
| `./scripts/stop-emulators.sh` | Stop emulators |
| `./scripts/debug-job.sh <job_id>` | Debug a cloud job (status, logs, files) |
| `./scripts/get_job.py <job_id>` | Fetch job data from Firestore |
| `./scripts/fetch_job_logs.py <job_id>` | Fetch cloud job logs to local file |
| `./scripts/analyze_log_timing.py <log>` | Profile karaoke-gen performance from logs |
| `./scripts/benchmark_ffmpeg.py` | Isolated FFmpeg encoding benchmark |
| `./scripts/compare_local_vs_remote.py` | Compare local vs cloud karaoke-gen performance |
## Project Structure
+25
View File
@@ -32,6 +32,31 @@ Audio separation and lyrics transcription run in parallel:
- Progress tracked separately in `state_data`
- Screens generation waits for both to complete
### Cloud Run Performance: Cold Starts and FFmpeg
**Problem**: Cloud karaoke generation was ~3x slower than local CLI (15 min vs 5 min for a typical song).
**Root causes identified**:
1. **Cold start penalty**: Cloud Run with `min-instances: 0` caused 77-second cold starts for FFmpeg-heavy operations (title screen generation). Warm instances take only 6 seconds.
2. **FFmpeg version**: Debian's package (5.1.8) is outdated and built with security-focused `--toolchain=hardened` which reduces performance. Static builds (7.0.2) from johnvansickle.com are ~20-40% faster.
3. **Generic x86_64 build**: Debian packages use generic CPU instructions, not optimized for Cloud Run's Cascade Lake/Ice Lake processors.
**Solutions applied**:
- Set `min-instances: 4` to keep workers warm (eliminates cold start entirely)
- Use John Van Sickle's static FFmpeg 7.0.2 instead of Debian package
- Added `/api/health/detailed` endpoint to expose FFmpeg version for debugging
**Key insight**: For CPU-bound encoding workloads on Cloud Run:
- GPU acceleration often doesn't help (filters like libass aren't GPU-accelerated)
- Newer FFmpeg versions have significant encoding optimizations
- Static builds with CPU-specific tuning outperform generic distribution packages
- Cold starts hurt more than expected for initialization-heavy binaries like FFmpeg
**Debugging**: Use `scripts/compare_local_vs_remote.py` to benchmark local vs cloud performance.
## Common Gotchas
### Cross-Domain localStorage Isolation
+19
View File
@@ -0,0 +1,19 @@
# Environment variables for local development and testing
# Copy this file to .env.local and fill in your values
# =============================================================================
# E2E Testing - Email (for beta enrollment flow)
# =============================================================================
# testmail.app credentials for email testing
# Get these from https://testmail.app dashboard
TESTMAIL_API_KEY=your-api-key-here
TESTMAIL_NAMESPACE=your-namespace-here
# =============================================================================
# E2E Testing - Authentication (optional)
# =============================================================================
# Skip email enrollment by providing an existing access token
# Useful for faster local testing when you already have credits
# KARAOKE_ACCESS_TOKEN=your-token-here
+2 -63
View File
@@ -3,11 +3,10 @@
import { useState, useEffect, useCallback } from "react"
import { useRouter } from "next/navigation"
import { api, Job, getAccessToken } from "@/lib/api"
import { useAutoMode, getAutoModeFromUrl } from "@/lib/auto-mode"
import { useJobNotifications, useVisibilityRefresh } from "@/hooks/use-notifications"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Music2, RefreshCw, Loader2, Zap, ZapOff, Moon, Sun } from "lucide-react"
import { Music2, RefreshCw, Loader2, Moon, Sun } from "lucide-react"
import { WarmingUpLoader } from "@/components/WarmingUpLoader"
import { JobCard } from "@/components/job"
import { JobSubmission } from "@/components/job/JobSubmission"
@@ -28,7 +27,6 @@ export default function AppPage() {
const [isLoadingJobs, setIsLoadingJobs] = useState(true)
const [isInitialLoad, setIsInitialLoad] = useState(true)
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null)
const { enabled: autoModeEnabled, setEnabled: setAutoMode, toggle: toggleAutoMode } = useAutoMode()
const { isDarkMode, toggleTheme, mounted } = useTheme()
// Memoize loadJobs for use with visibility refresh
@@ -69,14 +67,6 @@ export default function AppPage() {
setIsAuthenticated(true)
}, [router])
// Initialize auto-mode from URL parameter on mount
useEffect(() => {
const urlAutoMode = getAutoModeFromUrl()
if (urlAutoMode) {
setAutoMode(true)
}
}, [setAutoMode])
// Load jobs on mount (only if authenticated)
useEffect(() => {
if (isAuthenticated !== true) {
@@ -109,7 +99,7 @@ export default function AppPage() {
return (
<div className="min-h-screen" style={{ background: 'var(--bg)' }}>
{/* AutoProcessor - handles non-interactive mode */}
{/* AutoProcessor - handles non-interactive mode for jobs with that flag */}
<AutoProcessor jobs={jobs} onJobsChanged={loadJobs} />
{/* Header */}
@@ -122,36 +112,6 @@ export default function AppPage() {
</div>
</div>
<div className="flex items-center gap-1 sm:gap-2 shrink-0">
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="sm"
onClick={toggleAutoMode}
className={`min-h-[40px] px-2 sm:px-3 ${autoModeEnabled ? "text-amber-400 hover:text-amber-300 bg-amber-500/10" : ""}`}
style={!autoModeEnabled ? { color: 'var(--text-muted)' } : undefined}
>
{autoModeEnabled ? (
<Zap className="w-4 h-4 sm:mr-2" />
) : (
<ZapOff className="w-4 h-4 sm:mr-2" />
)}
<span className="hidden sm:inline">Auto</span>
</Button>
</TooltipTrigger>
<TooltipContent side="bottom" className="max-w-xs">
<p className="font-medium">
{autoModeEnabled ? "Auto Mode Enabled" : "Auto Mode Disabled"}
</p>
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
{autoModeEnabled
? "Jobs will auto-complete review and select clean instrumental (like -y flag)"
: "Click to enable non-interactive mode"}
</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
<Button
variant="ghost"
size="sm"
@@ -193,27 +153,6 @@ export default function AppPage() {
</header>
<main className="px-4 py-8 space-y-6">
{/* Auto Mode Banner */}
{autoModeEnabled && (
<div className="bg-amber-500/10 border border-amber-500/30 rounded-lg p-4 flex items-center gap-3">
<Zap className="w-5 h-5 text-amber-400 flex-shrink-0" />
<div className="flex-1">
<p className="text-sm text-amber-200 font-medium">Non-Interactive Mode Active</p>
<p className="text-xs text-amber-200/70 mt-0.5">
Jobs will automatically accept lyrics and select clean instrumental (equivalent to -y flag)
</p>
</div>
<Button
variant="ghost"
size="sm"
onClick={toggleAutoMode}
className="text-amber-200 hover:text-amber-100 hover:bg-amber-500/20"
>
Disable
</Button>
</div>
)}
<div className="grid lg:grid-cols-2 gap-8">
{/* Submit Job Card */}
<Card className="backdrop-blur" style={{ borderColor: 'var(--card-border)', backgroundColor: 'var(--card)' }}>
+24 -17
View File
@@ -2,7 +2,6 @@
import { useEffect, useCallback, useRef } from "react"
import { api, Job } from "@/lib/api"
import { useAutoMode } from "@/lib/auto-mode"
interface AutoProcessorProps {
/** List of jobs to monitor */
@@ -13,27 +12,27 @@ interface AutoProcessorProps {
/**
* AutoProcessor component that automatically handles interactive states
* when auto-mode is enabled.
* for jobs that have non_interactive mode enabled.
*
* This is equivalent to the -y flag in karaoke-gen-remote CLI:
* - Auto-completes lyrics review (accepts auto-corrected lyrics)
* - Auto-selects "clean" instrumental
* - Auto-selects instrumental based on backing vocals analyzer recommendation
* - Auto-selects first/best audio search result
*/
export function AutoProcessor({ jobs, onJobsChanged }: AutoProcessorProps) {
const { enabled, markProcessing, unmarkProcessing, isProcessing } = useAutoMode()
const processedRef = useRef<Set<string>>(new Set())
const processingRef = useRef<Set<string>>(new Set())
const processJob = useCallback(async (job: Job, action: string) => {
const processingKey = `${job.job_id}-${action}`
// Skip if already being processed
if (isProcessing(processingKey) || processedRef.current.has(processingKey)) {
// Skip if already being processed or already processed
if (processingRef.current.has(processingKey) || processedRef.current.has(processingKey)) {
return
}
// Mark as processing
markProcessing(processingKey)
processingRef.current.add(processingKey)
processedRef.current.add(processingKey)
console.log(`[AutoProcessor] Auto-processing ${action} for job ${job.job_id}`)
@@ -46,11 +45,16 @@ export function AutoProcessor({ jobs, onJobsChanged }: AutoProcessorProps) {
console.log(`[AutoProcessor] Auto-completed review for job ${job.job_id}`)
break
case 'instrumental':
// Auto-select "clean" instrumental
await api.selectInstrumental(job.job_id, 'clean')
console.log(`[AutoProcessor] Auto-selected clean instrumental for job ${job.job_id}`)
case 'instrumental': {
// Use backing vocals analyzer recommendation (default to clean if review needed or missing)
const analysis = job.state_data?.backing_vocals_analysis
const recommendation = analysis?.recommended_selection
// Only use 'with_backing' if explicitly recommended by analyzer, otherwise clean (safe default)
const selection = recommendation === 'with_backing' ? 'with_backing' : 'clean'
await api.selectInstrumental(job.job_id, selection)
console.log(`[AutoProcessor] Auto-selected ${selection} instrumental for job ${job.job_id} (analyzer recommendation: ${recommendation || 'none'})`)
break
}
case 'audio':
// Auto-select first audio search result (index 0)
@@ -66,15 +70,18 @@ export function AutoProcessor({ jobs, onJobsChanged }: AutoProcessorProps) {
// Remove from processed so it can be retried
processedRef.current.delete(processingKey)
} finally {
unmarkProcessing(processingKey)
processingRef.current.delete(processingKey)
}
}, [isProcessing, markProcessing, unmarkProcessing, onJobsChanged])
}, [onJobsChanged])
useEffect(() => {
if (!enabled) return
// Find jobs that need auto-processing
// Find jobs that need auto-processing (only jobs with non_interactive flag)
for (const job of jobs) {
// Only process jobs with non_interactive mode enabled
if (!job.non_interactive) {
continue
}
switch (job.status) {
case 'awaiting_review':
processJob(job, 'review')
@@ -87,7 +94,7 @@ export function AutoProcessor({ jobs, onJobsChanged }: AutoProcessorProps) {
break
}
}
}, [enabled, jobs, processJob])
}, [jobs, processJob])
// This component doesn't render anything - it's purely for side effects
return null
+18 -44
View File
@@ -7,14 +7,6 @@
import { render, screen } from '@testing-library/react'
import { JobCard } from '../job/JobCard'
import { Job } from '@/lib/api'
import { useAutoMode } from '@/lib/auto-mode'
// Mock the auto-mode hook
jest.mock('@/lib/auto-mode', () => ({
useAutoMode: jest.fn()
}))
const mockUseAutoMode = useAutoMode as jest.Mock
// Mock the child components
jest.mock('../job/JobActions', () => ({
@@ -48,11 +40,6 @@ describe('JobCard', () => {
beforeEach(() => {
jest.clearAllMocks()
// Default mock: auto-mode disabled
mockUseAutoMode.mockReturnValue({
enabled: false,
isProcessing: jest.fn().mockReturnValue(false)
})
})
it('renders job information', () => {
@@ -104,14 +91,7 @@ describe('JobCard', () => {
expect(card).toHaveClass('border-red-500/30')
})
describe('when auto-mode is disabled', () => {
beforeEach(() => {
mockUseAutoMode.mockReturnValue({
enabled: false,
isProcessing: jest.fn().mockReturnValue(false)
})
})
describe('regular jobs (non_interactive: false)', () => {
it('shows lyrics review link for awaiting_review status', () => {
const reviewJob = { ...mockJob, status: 'awaiting_review', review_token: 'test-token-123' }
render(<JobCard job={reviewJob} onRefresh={mockOnRefresh} />)
@@ -146,18 +126,24 @@ describe('JobCard', () => {
expect(href).toContain('baseApiUrl=')
expect(href).toContain('instrumentalToken=test-instrumental-token')
})
it('does not show Auto badge for regular jobs', () => {
render(<JobCard job={mockJob} onRefresh={mockOnRefresh} />)
expect(screen.queryByText('Auto')).not.toBeInTheDocument()
})
})
describe('when auto-mode is enabled', () => {
beforeEach(() => {
mockUseAutoMode.mockReturnValue({
enabled: true,
isProcessing: jest.fn().mockReturnValue(false)
})
describe('non-interactive jobs (non_interactive: true)', () => {
it('shows Auto badge for non-interactive jobs', () => {
const nonInteractiveJob = { ...mockJob, non_interactive: true }
render(<JobCard job={nonInteractiveJob} onRefresh={mockOnRefresh} />)
expect(screen.getByText('Auto')).toBeInTheDocument()
})
it('shows auto-accept message for awaiting_review status', () => {
const reviewJob = { ...mockJob, status: 'awaiting_review' }
const reviewJob = { ...mockJob, status: 'awaiting_review', non_interactive: true }
render(<JobCard job={reviewJob} onRefresh={mockOnRefresh} />)
expect(screen.getByText(/Will auto-accept/)).toBeInTheDocument()
@@ -165,32 +151,20 @@ describe('JobCard', () => {
})
it('shows auto-select message for awaiting_instrumental_selection status', () => {
const instrumentalJob = { ...mockJob, status: 'awaiting_instrumental_selection' }
const instrumentalJob = { ...mockJob, status: 'awaiting_instrumental_selection', non_interactive: true }
render(<JobCard job={instrumentalJob} onRefresh={mockOnRefresh} />)
expect(screen.getByText(/Will auto-select clean/)).toBeInTheDocument()
expect(screen.getByText(/Will auto-select/)).toBeInTheDocument()
expect(screen.queryByText('Select Instrumental')).not.toBeInTheDocument()
})
it('shows auto-select message for awaiting_audio_selection status', () => {
const audioJob = { ...mockJob, status: 'awaiting_audio_selection' }
it('shows auto-select first message for awaiting_audio_selection status', () => {
const audioJob = { ...mockJob, status: 'awaiting_audio_selection', non_interactive: true }
render(<JobCard job={audioJob} onRefresh={mockOnRefresh} />)
expect(screen.getByText(/Will auto-select first/)).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Select Audio' })).not.toBeInTheDocument()
})
it('shows auto-processing indicator when processing', () => {
mockUseAutoMode.mockReturnValue({
enabled: true,
isProcessing: jest.fn().mockReturnValue(true)
})
const reviewJob = { ...mockJob, status: 'awaiting_review' }
render(<JobCard job={reviewJob} onRefresh={mockOnRefresh} />)
expect(screen.getByText(/Auto-processing.../)).toBeInTheDocument()
})
})
it('shows output links for complete jobs', () => {
+19 -30
View File
@@ -2,9 +2,8 @@
import { useState } from "react"
import { Job } from "@/lib/api"
import { useAutoMode } from "@/lib/auto-mode"
import { Button } from "@/components/ui/button"
import { Loader2, ExternalLink, Zap } from "lucide-react"
import { ExternalLink, Zap } from "lucide-react"
import { JobActions } from "./JobActions"
import { JobLogs } from "./JobLogs"
import { OutputLinks } from "./OutputLinks"
@@ -77,7 +76,6 @@ interface JobCardProps {
export function JobCard({ job, onRefresh }: JobCardProps) {
const [showLogs, setShowLogs] = useState(false)
const [showAudioSearch, setShowAudioSearch] = useState(false)
const { enabled: autoModeEnabled, isProcessing: isAutoProcessing } = useAutoMode()
const createdAt = new Date(job.created_at).toLocaleString()
const isInteractive = job.status === "awaiting_review" ||
@@ -86,14 +84,6 @@ export function JobCard({ job, onRefresh }: JobCardProps) {
job.status === "awaiting_audio_selection"
const isComplete = job.status === "complete"
const isFailed = job.status === "failed"
const isProcessing = !isComplete && !isFailed && job.status !== "cancelled"
// Check if this job is being auto-processed
const isBeingAutoProcessed = autoModeEnabled && isInteractive && (
isAutoProcessing(`${job.job_id}-review`) ||
isAutoProcessing(`${job.job_id}-instrumental`) ||
isAutoProcessing(`${job.job_id}-audio`)
)
// Build review URL for awaiting_review status
const getReviewUrl = () => {
@@ -125,22 +115,14 @@ export function JobCard({ job, onRefresh }: JobCardProps) {
// Render primary action button based on status
const renderPrimaryAction = () => {
if (autoModeEnabled && isInteractive) {
// For non-interactive jobs in interactive states, show auto-processing message
if (job.non_interactive && isInteractive) {
return (
<div className="flex items-center gap-1 text-xs text-amber-400">
{isBeingAutoProcessed ? (
<>
<Loader2 className="w-3 h-3 animate-spin" />
Auto-processing...
</>
) : (
<>
<Zap className="w-3 h-3" />
Will auto-{job.status === "awaiting_review" || job.status === "in_review" ? "accept" :
job.status === "awaiting_instrumental_selection" ? "select clean" :
"select first"}
</>
)}
<Zap className="w-3 h-3" />
Will auto-{job.status === "awaiting_review" || job.status === "in_review" ? "accept" :
job.status === "awaiting_instrumental_selection" ? "select" :
"select first"}
</div>
)
}
@@ -198,10 +180,18 @@ export function JobCard({ job, onRefresh }: JobCardProps) {
backgroundColor: 'var(--card)',
}}
>
{/* Header row with title */}
<p className="font-medium truncate" style={{ color: 'var(--text)' }}>
{job.artist || "Unknown"} - {job.title || "Unknown"}
</p>
{/* Header row with title and non-interactive badge */}
<div className="flex items-start justify-between gap-2">
<p className="font-medium truncate" style={{ color: 'var(--text)' }}>
{job.artist || "Unknown"} - {job.title || "Unknown"}
</p>
{job.non_interactive && (
<span className="shrink-0 inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400 font-medium">
<Zap className="w-2.5 h-2.5" />
Auto
</span>
)}
</div>
{/* Meta row: ID, date, status */}
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
@@ -254,4 +244,3 @@ export function JobCard({ job, onRefresh }: JobCardProps) {
</div>
)
}
+75
View File
@@ -39,6 +39,9 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
const [selectedTheme, setSelectedTheme] = useState<string | undefined>()
const [colorOverrides, setColorOverrides] = useState<ColorOverrides>({})
// Non-interactive mode (shared across all tabs)
const [nonInteractive, setNonInteractive] = useState(false)
async function handleUploadSubmit(e: React.FormEvent) {
e.preventDefault()
setError("")
@@ -57,6 +60,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
await api.uploadJob(uploadFile, uploadArtist.trim(), uploadTitle.trim(), {
theme_id: selectedTheme,
color_overrides: cleanColorOverrides(colorOverrides),
non_interactive: nonInteractive,
})
setUploadFile(null)
setUploadArtist("")
@@ -91,6 +95,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
{
theme_id: selectedTheme,
color_overrides: cleanColorOverrides(colorOverrides),
non_interactive: nonInteractive,
}
)
setYoutubeUrl("")
@@ -122,6 +127,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
await api.searchAudio(searchArtist.trim(), searchTitle.trim(), false, {
theme_id: selectedTheme,
color_overrides: cleanColorOverrides(colorOverrides),
non_interactive: nonInteractive,
})
setSearchArtist("")
setSearchTitle("")
@@ -250,6 +256,29 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
/>
</div>
{/* Non-interactive mode */}
<div className="space-y-2 pt-4 border-t" style={{ borderColor: 'var(--card-border)' }}>
<div className="flex items-start gap-3">
<input
type="checkbox"
id="non-interactive-upload"
checked={nonInteractive}
onChange={(e) => setNonInteractive(e.target.checked)}
disabled={isSubmitting}
className="mt-1 w-4 h-4 rounded border-gray-600 bg-gray-700 text-amber-500 focus:ring-amber-500 focus:ring-offset-gray-800"
/>
<div>
<Label htmlFor="non-interactive-upload" className="cursor-pointer" style={{ color: 'var(--text)' }}>
Skip lyrics review (non-interactive)
</Label>
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
<span className="text-amber-500 font-medium">Warning:</span> AI lyrics correction isn&apos;t perfect.
Skipping review will likely result in timing errors and incorrect words in your karaoke video.
</p>
</div>
</div>
</div>
{error && activeTab === "upload" && (
<p className="text-sm text-red-400 bg-red-500/10 rounded p-2">{error}</p>
)}
@@ -332,6 +361,29 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
/>
</div>
{/* Non-interactive mode */}
<div className="space-y-2 pt-4 border-t" style={{ borderColor: 'var(--card-border)' }}>
<div className="flex items-start gap-3">
<input
type="checkbox"
id="non-interactive-url"
checked={nonInteractive}
onChange={(e) => setNonInteractive(e.target.checked)}
disabled={isSubmitting}
className="mt-1 w-4 h-4 rounded border-gray-600 bg-gray-700 text-amber-500 focus:ring-amber-500 focus:ring-offset-gray-800"
/>
<div>
<Label htmlFor="non-interactive-url" className="cursor-pointer" style={{ color: 'var(--text)' }}>
Skip lyrics review (non-interactive)
</Label>
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
<span className="text-amber-500 font-medium">Warning:</span> AI lyrics correction isn&apos;t perfect.
Skipping review will likely result in timing errors and incorrect words in your karaoke video.
</p>
</div>
</div>
</div>
{error && activeTab === "url" && (
<p className="text-sm text-red-400 bg-red-500/10 rounded p-2">{error}</p>
)}
@@ -397,6 +449,29 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
/>
</div>
{/* Non-interactive mode */}
<div className="space-y-2 pt-4 border-t" style={{ borderColor: 'var(--card-border)' }}>
<div className="flex items-start gap-3">
<input
type="checkbox"
id="non-interactive-search"
checked={nonInteractive}
onChange={(e) => setNonInteractive(e.target.checked)}
disabled={isSubmitting}
className="mt-1 w-4 h-4 rounded border-gray-600 bg-gray-700 text-amber-500 focus:ring-amber-500 focus:ring-offset-gray-800"
/>
<div>
<Label htmlFor="non-interactive-search" className="cursor-pointer" style={{ color: 'var(--text)' }}>
Skip lyrics review (non-interactive)
</Label>
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
<span className="text-amber-500 font-medium">Warning:</span> AI lyrics correction isn&apos;t perfect.
Skipping review will likely result in timing errors and incorrect words in your karaoke video.
</p>
</div>
</div>
</div>
{error && activeTab === "search" && (
<p className="text-sm text-red-400 bg-red-500/10 rounded p-2">{error}</p>
)}
+129 -28
View File
@@ -1,13 +1,13 @@
/**
* Email Testing Utilities using MailSlurp
* Email Testing Utilities using testmail.app
*
* MailSlurp provides disposable email inboxes for e2e testing.
* Free tier: 50 emails/month - perfect for CI/CD testing.
* testmail.app provides namespace-based email addresses for e2e testing.
* Emails arrive at: {namespace}.{tag}@inbox.testmail.app
*
* Setup:
* 1. Create account at https://app.mailslurp.com
* 2. Get API key from dashboard
* 3. Set MAILSLURP_API_KEY environment variable
* 1. Create account at https://testmail.app
* 2. Get API key and namespace from dashboard
* 3. Set TESTMAIL_API_KEY and TESTMAIL_NAMESPACE environment variables
*
* Usage in tests:
* const emailHelper = await createEmailHelper();
@@ -17,9 +17,27 @@
* const magicLink = emailHelper.extractMagicLink(email);
*/
import { MailSlurp, InboxDto, Email } from 'mailslurp-client';
const TESTMAIL_API_KEY = process.env.TESTMAIL_API_KEY;
const TESTMAIL_NAMESPACE = process.env.TESTMAIL_NAMESPACE;
const TESTMAIL_API_URL = 'https://api.testmail.app/api/json';
const MAILSLURP_API_KEY = process.env.MAILSLURP_API_KEY;
/**
* Inbox object compatible with existing test code
*/
export interface InboxDto {
id: string;
emailAddress: string;
}
/**
* Email object compatible with existing test code
*/
export interface Email {
subject?: string;
body?: string;
from?: string;
timestamp?: number;
}
export interface EmailHelper {
isAvailable: boolean;
@@ -30,40 +48,122 @@ export interface EmailHelper {
deleteInbox: (inboxId: string) => Promise<void>;
}
/**
* testmail.app API response structure
*/
interface TestmailResponse {
result: string;
message?: string;
count: number;
limit: number;
offset: number;
emails: TestmailEmail[];
}
interface TestmailEmail {
from: string;
subject: string;
html: string;
text: string;
timestamp: number;
tag: string;
}
/**
* Generate a unique tag for this test run
*/
function generateUniqueTag(): string {
const timestamp = Date.now();
const random = Math.random().toString(36).substring(2, 8);
return `test-${timestamp}-${random}`;
}
/**
* Creates an email testing helper.
* Returns a helper with isAvailable=false if MAILSLURP_API_KEY is not set.
* Returns a helper with isAvailable=false if testmail.app env vars are not set.
*/
export async function createEmailHelper(): Promise<EmailHelper> {
if (!MAILSLURP_API_KEY) {
console.warn('MAILSLURP_API_KEY not set - email testing disabled');
if (!TESTMAIL_API_KEY || !TESTMAIL_NAMESPACE) {
console.warn('TESTMAIL_API_KEY or TESTMAIL_NAMESPACE not set - email testing disabled');
return createDisabledHelper();
}
const mailslurp = new MailSlurp({ apiKey: MAILSLURP_API_KEY });
return {
isAvailable: true,
/**
* Create a new disposable inbox for testing
* Create a new "inbox" for testing.
* In testmail.app, this just generates a unique tag - no API call needed.
*/
async createInbox(): Promise<InboxDto> {
const inbox = await mailslurp.createInbox();
console.log(`Created test inbox: ${inbox.emailAddress}`);
return inbox;
const tag = generateUniqueTag();
const emailAddress = `${TESTMAIL_NAMESPACE}.${tag}@inbox.testmail.app`;
console.log(`Created test inbox: ${emailAddress}`);
return { id: tag, emailAddress };
},
/**
* Wait for an email to arrive in the inbox
* @param inboxId - The inbox ID to check
* @param inboxId - The tag to check (returned from createInbox as id)
* @param timeout - Timeout in ms (default: 60000 = 1 minute)
*/
async waitForEmail(inboxId: string, timeout = 60000): Promise<Email> {
console.log(`Waiting for email in inbox ${inboxId}...`);
const email = await mailslurp.waitForLatestEmail(inboxId, timeout);
console.log(`Received email: ${email.subject}`);
return email;
console.log(`Waiting for email with tag ${inboxId}...`);
// testmail.app livequery timeout is in seconds, max ~60s per request
// For longer timeouts, we poll multiple times
const pollInterval = Math.min(timeout, 30000); // 30s max per poll
const startTime = Date.now();
while (Date.now() - startTime < timeout) {
const remainingTime = timeout - (Date.now() - startTime);
const waitTime = Math.min(pollInterval, remainingTime);
const waitSeconds = Math.ceil(waitTime / 1000);
const url = new URL(TESTMAIL_API_URL);
url.searchParams.set('apikey', TESTMAIL_API_KEY!);
url.searchParams.set('namespace', TESTMAIL_NAMESPACE!);
url.searchParams.set('tag', inboxId);
url.searchParams.set('livequery', 'true');
url.searchParams.set('wait', waitSeconds.toString());
try {
const response = await fetch(url.toString());
if (!response.ok) {
throw new Error(`testmail.app API error: ${response.status} ${response.statusText}`);
}
const data: TestmailResponse = await response.json();
if (data.result !== 'success') {
throw new Error(`testmail.app API error: ${data.message || 'Unknown error'}`);
}
if (data.emails && data.emails.length > 0) {
// Return the most recent email
const latestEmail = data.emails.sort((a, b) => b.timestamp - a.timestamp)[0];
console.log(`Received email: ${latestEmail.subject}`);
// Convert to our Email format (use html as body, fallback to text)
return {
subject: latestEmail.subject,
body: latestEmail.html || latestEmail.text,
from: latestEmail.from,
timestamp: latestEmail.timestamp,
};
}
} catch (error) {
// If it's a timeout or network error, continue polling
if (Date.now() - startTime < timeout) {
console.log(`Polling for email... (${Math.round((Date.now() - startTime) / 1000)}s elapsed)`);
continue;
}
throw error;
}
}
throw new Error(`Timed out waiting for email after ${timeout}ms`);
},
/**
@@ -135,21 +235,22 @@ export async function createEmailHelper(): Promise<EmailHelper> {
},
/**
* Delete an inbox after testing
* Delete an inbox after testing.
* In testmail.app, emails auto-expire - this is a no-op.
*/
async deleteInbox(inboxId: string): Promise<void> {
await mailslurp.deleteInbox(inboxId);
console.log(`Deleted inbox ${inboxId}`);
// testmail.app emails auto-expire, no cleanup needed
console.log(`Inbox ${inboxId} cleanup skipped (testmail.app auto-expires)`);
},
};
}
/**
* Creates a disabled helper for when MailSlurp is not configured
* Creates a disabled helper for when testmail.app is not configured
*/
function createDisabledHelper(): EmailHelper {
const notAvailable = () => {
throw new Error('Email testing not available - set MAILSLURP_API_KEY');
throw new Error('Email testing not available - set TESTMAIL_API_KEY and TESTMAIL_NAMESPACE');
};
return {
@@ -166,5 +267,5 @@ function createDisabledHelper(): EmailHelper {
* Check if email testing is available
*/
export function isEmailTestingAvailable(): boolean {
return !!MAILSLURP_API_KEY;
return !!(TESTMAIL_API_KEY && TESTMAIL_NAMESPACE);
}
@@ -25,7 +25,8 @@ import { createEmailHelper, isEmailTestingAvailable } from '../helpers/email-tes
* 10. Verify Outputs - Check download URLs
*
* Environment Variables:
* - MAILSLURP_API_KEY: For email testing (required for full flow)
* - TESTMAIL_API_KEY: For email testing (required for full flow)
* - TESTMAIL_NAMESPACE: Your testmail.app namespace
* - KARAOKE_ACCESS_TOKEN: Skip enrollment and use existing token
*/
@@ -189,11 +190,11 @@ test.describe('Production E2E - Full User Journey', () => {
});
console.log(' Authenticated successfully with existing token');
} else if (isEmailTestingAvailable()) {
console.log(' Starting beta enrollment with MailSlurp');
console.log(' Starting beta enrollment with testmail.app');
const emailHelper = await createEmailHelper();
if (!emailHelper.isAvailable) {
throw new Error('MailSlurp not available');
throw new Error('testmail.app not available');
}
// Create test inbox
@@ -249,7 +250,7 @@ test.describe('Production E2E - Full User Journey', () => {
}
} else {
throw new Error(
'No KARAOKE_ACCESS_TOKEN and no MAILSLURP_API_KEY - cannot authenticate'
'No KARAOKE_ACCESS_TOKEN and no TESTMAIL_API_KEY/TESTMAIL_NAMESPACE - cannot authenticate'
);
}
-171
View File
@@ -1,171 +0,0 @@
/**
* Tests for auto-mode state management
*/
import { renderHook, act } from "@testing-library/react"
import { useAutoMode, getAutoModeFromUrl } from "../auto-mode"
// Mock localStorage
const localStorageMock = (() => {
let store: Record<string, string> = {}
return {
getItem: jest.fn((key: string) => store[key] || null),
setItem: jest.fn((key: string, value: string) => {
store[key] = value
}),
removeItem: jest.fn((key: string) => {
delete store[key]
}),
clear: jest.fn(() => {
store = {}
}),
}
})()
Object.defineProperty(window, "localStorage", { value: localStorageMock })
describe("Auto Mode", () => {
beforeEach(() => {
localStorageMock.clear()
jest.clearAllMocks()
})
describe("useAutoMode hook", () => {
it("should initialize with enabled=false", () => {
const { result } = renderHook(() => useAutoMode())
expect(result.current.enabled).toBe(false)
})
it("should enable auto-mode", () => {
const { result } = renderHook(() => useAutoMode())
act(() => {
result.current.enable()
})
expect(result.current.enabled).toBe(true)
})
it("should disable auto-mode", () => {
const { result } = renderHook(() => useAutoMode())
act(() => {
result.current.enable()
result.current.disable()
})
expect(result.current.enabled).toBe(false)
})
it("should toggle auto-mode", () => {
const { result } = renderHook(() => useAutoMode())
act(() => {
result.current.toggle()
})
expect(result.current.enabled).toBe(true)
act(() => {
result.current.toggle()
})
expect(result.current.enabled).toBe(false)
})
it("should set enabled directly", () => {
const { result } = renderHook(() => useAutoMode())
act(() => {
result.current.setEnabled(true)
})
expect(result.current.enabled).toBe(true)
act(() => {
result.current.setEnabled(false)
})
expect(result.current.enabled).toBe(false)
})
it("should track processing jobs", () => {
const { result } = renderHook(() => useAutoMode())
expect(result.current.isProcessing("job-123-review")).toBe(false)
act(() => {
result.current.markProcessing("job-123-review")
})
expect(result.current.isProcessing("job-123-review")).toBe(true)
expect(result.current.isProcessing("job-456-review")).toBe(false)
act(() => {
result.current.unmarkProcessing("job-123-review")
})
expect(result.current.isProcessing("job-123-review")).toBe(false)
})
it("should handle multiple processing jobs", () => {
const { result } = renderHook(() => useAutoMode())
act(() => {
result.current.markProcessing("job-1-review")
result.current.markProcessing("job-2-instrumental")
})
expect(result.current.isProcessing("job-1-review")).toBe(true)
expect(result.current.isProcessing("job-2-instrumental")).toBe(true)
act(() => {
result.current.unmarkProcessing("job-1-review")
})
expect(result.current.isProcessing("job-1-review")).toBe(false)
expect(result.current.isProcessing("job-2-instrumental")).toBe(true)
})
})
describe("getAutoModeFromUrl", () => {
const originalLocation = window.location
beforeEach(() => {
// @ts-ignore - mocking location
delete window.location
// @ts-ignore - mocking location
window.location = { search: "" }
})
afterEach(() => {
window.location = originalLocation
})
it("should return false when no auto parameter", () => {
// @ts-ignore
window.location.search = ""
expect(getAutoModeFromUrl()).toBe(false)
})
it('should return true when auto=true', () => {
// @ts-ignore
window.location.search = "?auto=true"
expect(getAutoModeFromUrl()).toBe(true)
})
it('should return true when auto=1', () => {
// @ts-ignore
window.location.search = "?auto=1"
expect(getAutoModeFromUrl()).toBe(true)
})
it('should return false when auto=false', () => {
// @ts-ignore
window.location.search = "?auto=false"
expect(getAutoModeFromUrl()).toBe(false)
})
it("should handle multiple query params", () => {
// @ts-ignore
window.location.search = "?foo=bar&auto=true&baz=qux"
expect(getAutoModeFromUrl()).toBe(true)
})
})
})
+9
View File
@@ -65,6 +65,7 @@ export interface Job {
review_token?: string;
instrumental_token?: string;
audio_hash?: string;
non_interactive?: boolean;
}
export interface UploadJobResponse {
@@ -225,6 +226,7 @@ export const api = {
enable_youtube_upload?: boolean;
theme_id?: string;
color_overrides?: ColorOverrides;
non_interactive?: boolean;
}
): Promise<UploadJobResponse> {
const formData = new FormData();
@@ -250,6 +252,9 @@ export const api = {
if (options?.color_overrides) {
formData.append('color_overrides', JSON.stringify(options.color_overrides));
}
if (options?.non_interactive !== undefined) {
formData.append('non_interactive', String(options.non_interactive));
}
const response = await fetch(`${API_BASE_URL}/api/jobs/upload`, {
method: 'POST',
@@ -274,6 +279,7 @@ export const api = {
enable_youtube_upload?: boolean;
theme_id?: string;
color_overrides?: ColorOverrides;
non_interactive?: boolean;
}
): Promise<{ status: string; job_id: string; message: string }> {
const body: Record<string, any> = { url };
@@ -285,6 +291,7 @@ export const api = {
if (options?.enable_youtube_upload !== undefined) body.enable_youtube_upload = options.enable_youtube_upload;
if (options?.theme_id) body.theme_id = options.theme_id;
if (options?.color_overrides) body.color_overrides = options.color_overrides;
if (options?.non_interactive !== undefined) body.non_interactive = options.non_interactive;
const response = await fetch(`${API_BASE_URL}/api/jobs/create-from-url`, {
method: 'POST',
@@ -409,6 +416,7 @@ export const api = {
enable_youtube_upload?: boolean;
theme_id?: string;
color_overrides?: ColorOverrides;
non_interactive?: boolean;
}
): Promise<AudioSearchResponse> {
const body: Record<string, any> = { artist, title, auto_download: autoDownload };
@@ -418,6 +426,7 @@ export const api = {
if (options?.enable_youtube_upload !== undefined) body.enable_youtube_upload = options.enable_youtube_upload;
if (options?.theme_id) body.theme_id = options.theme_id;
if (options?.color_overrides) body.color_overrides = options.color_overrides;
if (options?.non_interactive !== undefined) body.non_interactive = options.non_interactive;
const response = await fetch(`${API_BASE_URL}/api/audio-search/search`, {
method: 'POST',
-80
View File
@@ -1,80 +0,0 @@
/**
* Auto-mode state management for non-interactive processing.
*
* When auto-mode is enabled (via ?auto=true URL parameter or UI toggle),
* the frontend automatically:
* - Completes lyrics review without human intervention
* - Selects "clean" instrumental automatically
* - Selects the first/best audio search result automatically
*
* This is equivalent to the -y flag in karaoke-gen-remote CLI.
*/
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
interface AutoModeState {
/** Whether auto-mode is enabled */
enabled: boolean
/** Jobs currently being auto-processed (to prevent duplicate processing) */
processingJobs: Set<string>
/** Enable auto-mode */
enable: () => void
/** Disable auto-mode */
disable: () => void
/** Toggle auto-mode */
toggle: () => void
/** Set auto-mode state directly */
setEnabled: (enabled: boolean) => void
/** Mark a job as being processed */
markProcessing: (jobId: string) => void
/** Unmark a job as being processed */
unmarkProcessing: (jobId: string) => void
/** Check if a job is currently being processed */
isProcessing: (jobId: string) => boolean
}
export const useAutoMode = create<AutoModeState>()(
persist(
(set, get) => ({
enabled: false,
processingJobs: new Set<string>(),
enable: () => set({ enabled: true }),
disable: () => set({ enabled: false }),
toggle: () => set((state) => ({ enabled: !state.enabled })),
setEnabled: (enabled: boolean) => set({ enabled }),
markProcessing: (jobId: string) => set((state) => {
const newSet = new Set(state.processingJobs)
newSet.add(jobId)
return { processingJobs: newSet }
}),
unmarkProcessing: (jobId: string) => set((state) => {
const newSet = new Set(state.processingJobs)
newSet.delete(jobId)
return { processingJobs: newSet }
}),
isProcessing: (jobId: string) => get().processingJobs.has(jobId),
}),
{
name: 'karaoke-auto-mode',
// Only persist the enabled state, not the processing jobs
partialize: (state) => ({ enabled: state.enabled }),
}
)
)
/**
* Check URL for auto-mode parameter.
* Returns true if ?auto=true or ?auto=1 is in the URL.
*/
export function getAutoModeFromUrl(): boolean {
if (typeof window === 'undefined') return false
const params = new URLSearchParams(window.location.search)
const autoParam = params.get('auto')
return autoParam === 'true' || autoParam === '1'
}
+2 -69
View File
@@ -1,12 +1,12 @@
{
"name": "karaoke-gen-frontend",
"version": "0.77.0",
"version": "0.78.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "karaoke-gen-frontend",
"version": "0.77.0",
"version": "0.78.0",
"dependencies": {
"@hookform/resolvers": "^3.10.0",
"@radix-ui/react-accordion": "1.2.2",
@@ -75,7 +75,6 @@
"concurrently": "^9.2.1",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"mailslurp-client": "^16.0.0",
"postcss": "^8.5",
"tailwindcss": "^4.1.9",
"ts-node": "^10.9.2",
@@ -4504,16 +4503,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/cross-fetch": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-4.1.0.tgz",
"integrity": "sha512-uKm5PU+MHTootlWEY+mZ4vvXoCn4fLQxT9dSc1sXVMSFkINTJVN8cAQROpwcKm8bJ/c7rgZVIBWzH5T78sNZZw==",
"dev": true,
"license": "MIT",
"dependencies": {
"node-fetch": "^2.7.0"
}
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@@ -7103,16 +7092,6 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
"node_modules/mailslurp-client": {
"version": "16.0.0",
"resolved": "https://registry.npmjs.org/mailslurp-client/-/mailslurp-client-16.0.0.tgz",
"integrity": "sha512-4g3Zauq5vcHZ2HAanfLpdcXcsZhZj6ToL/hUY10YS1vHK2DGt9EEO43ms5wzLFHCMFOCsx6So1JMIER/n8rIXw==",
"dev": true,
"license": "MIT",
"dependencies": {
"cross-fetch": "^4.1.0"
}
},
"node_modules/make-dir": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz",
@@ -7355,52 +7334,6 @@
"node": "^10 || ^12 || >=14"
}
},
"node_modules/node-fetch": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
"integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
"dev": true,
"license": "MIT",
"dependencies": {
"whatwg-url": "^5.0.0"
},
"engines": {
"node": "4.x || >=6.0.0"
},
"peerDependencies": {
"encoding": "^0.1.0"
},
"peerDependenciesMeta": {
"encoding": {
"optional": true
}
}
},
"node_modules/node-fetch/node_modules/tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
"dev": true,
"license": "MIT"
},
"node_modules/node-fetch/node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
"dev": true,
"license": "BSD-2-Clause"
},
"node_modules/node-fetch/node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
"dev": true,
"license": "MIT",
"dependencies": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
},
"node_modules/node-int64": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz",
+1 -2
View File
@@ -1,6 +1,6 @@
{
"name": "karaoke-gen-frontend",
"version": "0.78.0",
"version": "0.79.0",
"private": true,
"scripts": {
"build": "next build",
@@ -93,7 +93,6 @@
"concurrently": "^9.2.1",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"mailslurp-client": "^16.0.0",
"postcss": "^8.5",
"tailwindcss": "^4.1.9",
"ts-node": "^10.9.2",
+1 -1
View File
@@ -2,7 +2,7 @@ import { defineConfig, devices } from '@playwright/test';
import * as fs from 'fs';
import * as path from 'path';
// Load .env.local file if it exists (for KARAOKE_ACCESS_TOKEN, MAILSLURP_API_KEY)
// Load .env.local file if it exists (for KARAOKE_ACCESS_TOKEN, TESTMAIL_API_KEY, TESTMAIL_NAMESPACE)
const envLocalPath = path.join(__dirname, '.env.local');
if (fs.existsSync(envLocalPath)) {
const envContent = fs.readFileSync(envLocalPath, 'utf-8');
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.86.6"
version = "0.86.7"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"
+464
View File
@@ -0,0 +1,464 @@
#!/usr/bin/env python3
"""
Karaoke-Gen Log Timing Analyzer
Parses karaoke-gen log output (both local CLI and cloud job logs) and extracts
timing information for each stage of the processing pipeline. Identifies both
automated processing time and human interaction wait times.
Supports two log formats:
- Local CLI: "2025-12-30 16:22:28.657 - INFO - logger - message"
- Cloud Job: "2025-12-30T20:52:21.293 - INFO - backend.service - message"
Usage:
python analyze_log_timing.py <log_file>
python analyze_log_timing.py <log_file> --json # Output as JSON
python analyze_log_timing.py <log_file> --verbose # Show all events
"""
import argparse
import json
import re
import sys
from dataclasses import dataclass, field, asdict
from datetime import datetime, timedelta
from pathlib import Path
from typing import Optional
@dataclass
class Stage:
"""Represents a processing stage with timing information."""
name: str
start_time: Optional[datetime] = None
end_time: Optional[datetime] = None
is_human_wait: bool = False
sub_stages: list = field(default_factory=list)
@property
def duration(self) -> Optional[timedelta]:
if self.start_time and self.end_time:
return self.end_time - self.start_time
return None
@property
def duration_seconds(self) -> Optional[float]:
d = self.duration
return d.total_seconds() if d else None
def to_dict(self) -> dict:
return {
'name': self.name,
'start_time': self.start_time.isoformat() if self.start_time else None,
'end_time': self.end_time.isoformat() if self.end_time else None,
'duration_seconds': self.duration_seconds,
'is_human_wait': self.is_human_wait,
'sub_stages': [s.to_dict() for s in self.sub_stages]
}
# Timestamp patterns for both formats
# Local: 2025-12-30 16:22:28.657
# Cloud: 2025-12-30T20:52:21.293
TIMESTAMP_PATTERN_LOCAL = re.compile(r'^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3})')
TIMESTAMP_PATTERN_CLOUD = re.compile(r'^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3})')
# Stage detection patterns
STAGE_PATTERNS = {
# Initial setup
'flacfetch_search': (r'Using remote flacfetch API at:', r'Found \d+ results'),
'human_track_select': (r'Select \(1-\d+\)', r'Downloading:.*from'),
'audio_download': (r'\[RemoteFlacFetcher\] Downloading:', r'Audio downloaded from'),
# Parallel processing phase
'parallel_start': (r'=== Starting Parallel Processing ===', None),
# Lyrics track
'lyrics_fetch_lrclib': (r'lrclib - Searching LRCLIB for', r'Successfully fetched lyrics from lrclib'),
'lyrics_fetch_genius': (r'genius - Trying RapidAPI for', r'Successfully fetched lyrics from genius'),
'lyrics_fetch_spotify': (r'spotify - Trying RapidAPI for', r'Successfully fetched lyrics from spotify'),
'lyrics_transcription': (r'audioshake - Starting transcription for', r'audioshake - All targets completed'),
'lyrics_correction': (r'corrector - Starting correction process', r'Correction process completed'),
# Audio track
'audio_separation_stage1': (r'Stage 1: Submitting audio separation job', r'Stage 1 completed'),
'audio_separation_stage2': (r'Stage 2: Processing clean vocals', r'Stage 2 completed'),
'audio_normalization': (r'Normalizing clean instrumental', r'Audio normalization process completed'),
# Human review
'human_lyrics_review': (r'Opening review UI:', r'Human review completed'),
# Post-review rendering
'video_render_main': (r'Rendering karaoke video with synchronized lyrics', r'Video rendered successfully:'),
'title_screen_gen': (r'Creating title video', r'Creating end screen video'),
'end_screen_gen': (r'Creating end screen video', r'Audio separation was already completed'),
# Human instrumental selection
'human_instrumental_select': (r'Starting instrumental review UI', r'User selected:'),
# KaraokeFinalise phase
'human_finalise_confirm': (r'Confirm features enabled log messages above match', r'Finding input file ending in'),
'cdg_package': (r'Creating CDG package', r'CDG package created successfully'),
'txt_package': (r'Creating TXT package', r'TXT package created successfully'),
# Video encoding (the big one)
'encode_step1_remux': (r'\[Step 1/6\] Remuxing video', r'\[Step 2/6\]'),
'encode_step2_mp4_convert': (r'\[Step 2/6\] Converting karaoke video', r'\[Step 3/6\]'),
'encode_step3_lossless_4k': (r'\[Step 3/6\] Encoding lossless 4K', r'\[Step 4/6\]'),
'encode_step4_lossy_4k': (r'\[Step 4/6\] Encoding lossy 4K', r'\[Step 5/6\]'),
'encode_step5_mkv_flac': (r'\[Step 5/6\] Creating MKV', r'\[Step 6/6\]'),
'encode_step6_720p': (r'\[Step 6/6\] Encoding 720p', r'Video encoding completed'),
# Human video check
'human_video_check': (r'Please check them! Proceed\?', r'Video encoding completed successfully'),
# Modal file downloads (often overlooked)
'modal_download_stage1': (r'📥 Downloading 8 output files', r'🎉 Successfully downloaded 8 files'),
'modal_download_stage2': (r'📥 Downloading 2 output files', r'🎉 Successfully downloaded 2 files'),
# Distribution
'youtube_upload': (r'Uploading final MKV to YouTube', r'Uploaded video to YouTube:'),
'discord_notification': (r'Posting Discord notification', r'Message posted to Discord'),
'rclone_copy': (r'Copying to cloud destination', r'Command completed successfully'),
}
# Cloud-specific stage patterns (for backend workers)
CLOUD_STAGE_PATTERNS = {
# Job lifecycle
'job_created': (r'transitioned to searching_audio', None),
'audio_search': (r'transitioned to searching_audio', r'transitioned to awaiting_audio_selection'),
'human_audio_select': (r'transitioned to awaiting_audio_selection', r'transitioned to downloading_audio'),
'flacfetch_download': (r'transitioned to downloading_audio', r'transitioned to downloading'),
# Audio worker (cloud) - overall
'cloud_audio_worker': (r'=== AUDIO WORKER STARTED ===', r'Audio separation complete!'),
# Audio worker stages
'cloud_audio_gcs_download': (r'Downloading audio file\.\.\.', r'Audio downloaded:'),
'cloud_modal_stage1': (r'Stage 1: Submitting audio separation job', r'Stage 1 completed'),
'cloud_modal_stage1_download': (r'📥 Downloading 8 output files', r'🎉 Successfully downloaded 8 files'),
'cloud_modal_stage2': (r'Stage 2: Processing clean vocals', r'Stage 2 completed'),
'cloud_modal_stage2_download': (r'📥 Downloading 2 output files', r'🎉 Successfully downloaded 2 files'),
'cloud_audio_normalize': (r'Normalizing clean instrumental', r'Audio normalization process completed'),
'cloud_stems_upload': (r'Uploading separation results to GCS', r'All stems uploaded successfully'),
# Lyrics worker (cloud) - overall
'cloud_lyrics_worker': (r'=== LYRICS WORKER STARTED ===', r'=== LYRICS WORKER COMPLETE ==='),
# Lyrics worker stages
'cloud_lyrics_gcs_download': (r'Downloading audio file from GCS', r'Audio downloaded:.*lyrics'),
'cloud_style_download': (r'Loading style configuration for lyrics', r'Using custom style params:'),
'cloud_lyrics_fetch_lrclib': (r'Searching LRCLIB for', r'Successfully fetched lyrics from lrclib'),
'cloud_lyrics_fetch_genius': (r'Trying RapidAPI for.*genius|Trying RapidAPI for', r'Successfully fetched lyrics from genius'),
'cloud_lyrics_fetch_spotify': (r'Successfully fetched lyrics from genius', r'Successfully fetched lyrics from spotify'),
'cloud_audioshake_transcribe': (r'Uploading.*to AudioShake', r'Getting task result for task'),
'cloud_lyrics_correction': (r'Starting correction process', r'Correction process completed'),
'cloud_lyrics_upload': (r'Uploading lyrics results to GCS', r'Successfully uploaded lyrics'),
# Screens worker (cloud)
'cloud_screens_worker': (r'=== SCREENS WORKER STARTED ===', r'=== SCREENS WORKER COMPLETE ==='),
'cloud_title_screen': (r'Creating title screen', r'Title screen created'),
'cloud_end_screen': (r'Creating end screen', r'End screen created'),
# Render worker (cloud)
'cloud_render_worker': (r'=== RENDER WORKER STARTED ===', r'=== RENDER WORKER COMPLETE ==='),
'cloud_video_render': (r'Rendering karaoke video|Starting video render', r'Video rendered successfully|Video generation complete'),
'cloud_render_upload': (r'Uploading rendered video', r'Successfully uploaded.*video'),
# Video worker (cloud)
'cloud_video_worker': (r'=== VIDEO WORKER STARTED ===', r'=== VIDEO WORKER COMPLETE ==='),
'cloud_video_download': (r'Downloading files for video encoding', r'All files downloaded'),
'cloud_video_encode': (r'Starting video encoding', r'Video encoding completed'),
}
# Human wait stages
HUMAN_STAGES = {
'human_track_select',
'human_lyrics_review',
'human_instrumental_select',
'human_finalise_confirm',
'human_video_check',
'human_audio_select', # Cloud
}
def parse_timestamp(line: str) -> Optional[datetime]:
"""Extract timestamp from log line. Handles both local and cloud formats."""
# Try local format first: 2025-12-30 16:22:28.657
match = TIMESTAMP_PATTERN_LOCAL.match(line)
if match:
return datetime.strptime(match.group(1), '%Y-%m-%d %H:%M:%S.%f')
# Try cloud format: 2025-12-30T20:52:21.293
match = TIMESTAMP_PATTERN_CLOUD.match(line)
if match:
return datetime.strptime(match.group(1), '%Y-%m-%dT%H:%M:%S.%f')
return None
def detect_log_type(lines: list) -> str:
"""Detect whether log is from local CLI or cloud backend."""
for line in lines[:50]: # Check first 50 lines
if TIMESTAMP_PATTERN_CLOUD.match(line):
if 'backend.' in line or 'WORKER_START' in line or 'Firestore' in line:
return 'cloud'
if TIMESTAMP_PATTERN_LOCAL.match(line):
if 'karaoke_gen' in line or 'nomadauto' in line.lower():
return 'local'
# Default based on timestamp format
for line in lines[:10]:
if TIMESTAMP_PATTERN_CLOUD.match(line):
return 'cloud'
if TIMESTAMP_PATTERN_LOCAL.match(line):
return 'local'
return 'unknown'
def find_pattern_match(line: str, pattern: str) -> bool:
"""Check if line matches pattern."""
return bool(re.search(pattern, line))
def analyze_log(log_path: Path, verbose: bool = False) -> dict:
"""
Analyze a karaoke-gen log file and extract timing information.
Returns:
Dictionary with stage timings and summary statistics.
"""
with open(log_path, 'r', encoding='utf-8', errors='replace') as f:
lines = f.readlines()
# Detect log type
log_type = detect_log_type(lines)
if verbose:
print(f"Detected log type: {log_type}")
# Select appropriate patterns based on log type
if log_type == 'cloud':
patterns_to_use = {**CLOUD_STAGE_PATTERNS}
else:
patterns_to_use = {**STAGE_PATTERNS}
# Track stage states
stages: dict[str, Stage] = {}
active_stages: set[str] = set()
first_timestamp = None
last_timestamp = None
for line in lines:
ts = parse_timestamp(line)
if ts:
if first_timestamp is None:
first_timestamp = ts
last_timestamp = ts
# Check each stage pattern
for stage_name, (start_pattern, end_pattern) in patterns_to_use.items():
# Check for stage start
if start_pattern and find_pattern_match(line, start_pattern):
if stage_name not in stages:
stages[stage_name] = Stage(
name=stage_name,
is_human_wait=stage_name in HUMAN_STAGES
)
if ts and not stages[stage_name].start_time:
stages[stage_name].start_time = ts
active_stages.add(stage_name)
if verbose:
print(f"[START] {stage_name} at {ts}")
# Check for stage end
if end_pattern and find_pattern_match(line, end_pattern):
if stage_name in stages and stage_name in active_stages:
if ts:
stages[stage_name].end_time = ts
active_stages.discard(stage_name)
if verbose:
print(f"[END] {stage_name} at {ts} ({stages[stage_name].duration})")
# Calculate summary statistics
total_duration = (last_timestamp - first_timestamp) if (first_timestamp and last_timestamp) else None
human_time = timedelta()
processing_time = timedelta()
for stage in stages.values():
if stage.duration:
if stage.is_human_wait:
human_time += stage.duration
else:
processing_time += stage.duration
# Group stages by category (different categories for local vs cloud)
if log_type == 'cloud':
categories = {
'job_setup': ['job_created', 'audio_search', 'flacfetch_download', 'cloud_tasks_setup'],
'audio_worker': ['cloud_audio_worker', 'cloud_audio_gcs_download', 'cloud_modal_api',
'cloud_modal_stage1_download', 'cloud_modal_stage2_download', 'cloud_stems_upload'],
'lyrics_worker': ['cloud_lyrics_worker', 'cloud_lyrics_gcs_download', 'cloud_style_download',
'cloud_audioshake_upload', 'cloud_lyrics_correction', 'cloud_lyrics_upload'],
'screens_worker': ['cloud_screens_worker', 'cloud_title_screen', 'cloud_end_screen'],
'render_worker': ['cloud_render_worker', 'cloud_video_render', 'cloud_render_upload'],
'video_worker': ['cloud_video_worker', 'cloud_video_download', 'cloud_video_encode'],
'human_interaction': ['human_audio_select'],
}
else:
categories = {
'setup': ['flacfetch_search', 'audio_download'],
'lyrics_processing': ['lyrics_fetch_lrclib', 'lyrics_fetch_genius', 'lyrics_fetch_spotify',
'lyrics_transcription', 'lyrics_correction'],
'audio_separation': ['audio_separation_stage1', 'audio_separation_stage2', 'audio_normalization',
'modal_download_stage1', 'modal_download_stage2'],
'video_rendering': ['video_render_main', 'title_screen_gen', 'end_screen_gen'],
'packaging': ['cdg_package', 'txt_package'],
'video_encoding': ['encode_step1_remux', 'encode_step2_mp4_convert', 'encode_step3_lossless_4k',
'encode_step4_lossy_4k', 'encode_step5_mkv_flac', 'encode_step6_720p'],
'distribution': ['youtube_upload', 'discord_notification', 'rclone_copy'],
'human_interaction': ['human_track_select', 'human_lyrics_review', 'human_instrumental_select',
'human_finalise_confirm', 'human_video_check'],
}
category_totals = {}
for cat_name, stage_names in categories.items():
total = timedelta()
for sn in stage_names:
if sn in stages and stages[sn].duration:
total += stages[sn].duration
category_totals[cat_name] = total.total_seconds()
return {
'log_file': str(log_path),
'log_type': log_type,
'first_timestamp': first_timestamp.isoformat() if first_timestamp else None,
'last_timestamp': last_timestamp.isoformat() if last_timestamp else None,
'total_wall_clock_seconds': total_duration.total_seconds() if total_duration else None,
'total_human_wait_seconds': human_time.total_seconds(),
'total_processing_seconds': processing_time.total_seconds(),
'automated_processing_seconds': (total_duration.total_seconds() - human_time.total_seconds()) if total_duration else None,
'category_totals': category_totals,
'stages': {name: stage.to_dict() for name, stage in stages.items()},
}
def format_duration(seconds: Optional[float]) -> str:
"""Format seconds as human-readable duration."""
if seconds is None:
return "N/A"
minutes, secs = divmod(int(seconds), 60)
if minutes > 0:
return f"{minutes}m {secs}s"
return f"{secs}s"
def print_report(analysis: dict) -> None:
"""Print a human-readable timing report."""
print("=" * 70)
print("KARAOKE-GEN LOG TIMING ANALYSIS")
print("=" * 70)
log_type = analysis.get('log_type', 'unknown')
print(f"\nLog file: {analysis['log_file']}")
print(f"Log type: {log_type.upper()}")
print(f"Start: {analysis['first_timestamp']}")
print(f"End: {analysis['last_timestamp']}")
print("\n" + "-" * 70)
print("SUMMARY")
print("-" * 70)
print(f"Total wall-clock time: {format_duration(analysis['total_wall_clock_seconds'])}")
print(f"Human interaction time: {format_duration(analysis['total_human_wait_seconds'])}")
print(f"Automated processing time: {format_duration(analysis['automated_processing_seconds'])}")
print("\n" + "-" * 70)
print("CATEGORY BREAKDOWN")
print("-" * 70)
for cat_name, seconds in analysis['category_totals'].items():
if seconds > 0:
label = cat_name.replace('_', ' ').title()
print(f" {label:25} {format_duration(seconds):>10}")
print("\n" + "-" * 70)
print("DETAILED STAGE TIMINGS")
print("-" * 70)
# Sort stages by start time
sorted_stages = sorted(
[(name, data) for name, data in analysis['stages'].items() if data['start_time']],
key=lambda x: x[1]['start_time']
)
for name, data in sorted_stages:
duration = format_duration(data['duration_seconds'])
human_marker = " [HUMAN]" if data['is_human_wait'] else ""
label = name.replace('_', ' ').title()
print(f" {label:35} {duration:>10}{human_marker}")
print("\n" + "=" * 70)
# Performance insights
print("\nPERFORMANCE INSIGHTS")
print("-" * 70)
# Find slowest automated stages
automated_stages = [
(name, data['duration_seconds'])
for name, data in analysis['stages'].items()
if data['duration_seconds'] and not data['is_human_wait']
]
automated_stages.sort(key=lambda x: x[1], reverse=True)
print("\nSlowest automated stages:")
for name, duration in automated_stages[:5]:
label = name.replace('_', ' ').title()
print(f" {label:35} {format_duration(duration):>10}")
# Calculate encoding total
encoding_total = sum(
analysis['stages'].get(f'encode_step{i}_{suffix}', {}).get('duration_seconds', 0) or 0
for i, suffix in [(1, 'remux'), (2, 'mp4_convert'), (3, 'lossless_4k'),
(4, 'lossy_4k'), (5, 'mkv_flac'), (6, '720p')]
)
print(f"\nTotal video encoding time: {format_duration(encoding_total)}")
# Parallelizable encoding stages (steps 4, 5, 6)
parallel_steps = ['encode_step4_lossy_4k', 'encode_step5_mkv_flac', 'encode_step6_720p']
parallel_times = [
analysis['stages'].get(step, {}).get('duration_seconds', 0) or 0
for step in parallel_steps
]
current_sequential = sum(parallel_times)
potential_parallel = max(parallel_times) if parallel_times else 0
if current_sequential > 0:
print(f"\nEncoding optimization potential:")
print(f" Steps 4-6 currently run sequentially: {format_duration(current_sequential)}")
print(f" If parallelized, could take: {format_duration(potential_parallel)}")
print(f" Potential time savings: {format_duration(current_sequential - potential_parallel)}")
def main():
parser = argparse.ArgumentParser(
description='Analyze karaoke-gen log files for timing information'
)
parser.add_argument('log_file', type=Path, help='Path to log file')
parser.add_argument('--json', action='store_true', help='Output as JSON')
parser.add_argument('--verbose', '-v', action='store_true', help='Show all detected events')
args = parser.parse_args()
if not args.log_file.exists():
print(f"Error: Log file not found: {args.log_file}", file=sys.stderr)
sys.exit(1)
analysis = analyze_log(args.log_file, verbose=args.verbose)
if args.json:
print(json.dumps(analysis, indent=2))
else:
print_report(analysis)
if __name__ == '__main__':
main()
+299
View File
@@ -0,0 +1,299 @@
#!/usr/bin/env python3
"""
Isolated FFmpeg encoding benchmark.
Creates a test video and runs the same encoding commands used by karaoke-gen
to measure raw encoding performance. Can be run locally and compared with
cloud results.
Usage:
# Run locally
python scripts/benchmark_ffmpeg.py
# Compare with cloud (run from Cloud Run shell)
python scripts/benchmark_ffmpeg.py --cloud
Output:
Timing results for each encoding step
"""
import argparse
import json
import os
import subprocess
import sys
import tempfile
import time
from datetime import datetime
from pathlib import Path
def run_timed_command(description: str, command: str, timeout: int = 600) -> dict:
"""Run a command and return timing info."""
print(f"\n{'='*60}")
print(f"BENCHMARK: {description}")
print(f"{'='*60}")
print(f"Command: {command[:100]}...")
start = time.time()
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
timeout=timeout
)
elapsed = time.time() - start
success = result.returncode == 0
print(f"Result: {'SUCCESS' if success else 'FAILED'}")
print(f"Time: {elapsed:.2f}s")
if not success:
print(f"Error: {result.stderr[:500]}")
return {
"description": description,
"success": success,
"elapsed_seconds": elapsed,
"command": command,
"stderr": result.stderr[:1000] if not success else None,
}
def get_video_info(file_path: str) -> dict:
"""Get video file info using ffprobe."""
cmd = f'ffprobe -v quiet -print_format json -show_format -show_streams "{file_path}"'
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
if result.returncode == 0:
return json.loads(result.stdout)
return {}
def create_test_video(output_path: str, duration: int = 60) -> dict:
"""Create a test video similar to karaoke output (4K, ~1 minute)."""
# Generate a 4K test pattern video with audio
# This simulates the karaoke video before final encoding
command = (
f'ffmpeg -y -f lavfi -i "testsrc2=size=3840x2160:rate=30:duration={duration}" '
f'-f lavfi -i "sine=frequency=440:duration={duration}" '
f'-c:v libx264 -preset ultrafast -crf 18 -pix_fmt yuv420p '
f'-c:a pcm_s16le -ar 48000 '
f'"{output_path}"'
)
return run_timed_command(f"Create test video ({duration}s, 4K)", command)
def benchmark_lossless_4k_encode(input_file: str, output_file: str) -> dict:
"""
Benchmark Step 3: Lossless 4K MP4 encoding.
This is the most CPU-intensive step in karaoke-gen.
"""
command = (
f'ffmpeg -y -hide_banner -nostats -loglevel warning '
f'-i "{input_file}" '
f'-c:v libx264 -preset medium -crf 18 -pix_fmt yuv420p '
f'-c:a pcm_s16le -ar 48000 '
f'"{output_file}"'
)
return run_timed_command("Encode lossless 4K MP4 (Step 3 equivalent)", command)
def benchmark_720p_encode(input_file: str, output_file: str) -> dict:
"""
Benchmark Step 6: 720p encoding with scaling.
This is the second most CPU-intensive step.
"""
command = (
f'ffmpeg -y -hide_banner -nostats -loglevel warning '
f'-i "{input_file}" '
f'-c:v libx264 -vf "scale=1280:720" -b:v 2000k -preset medium -tune animation '
f'-c:a aac -ar 48000 -b:a 128k -pix_fmt yuv420p '
f'"{output_file}"'
)
return run_timed_command("Encode 720p MP4 (Step 6 equivalent)", command)
def benchmark_lossy_4k_encode(input_file: str, output_file: str) -> dict:
"""
Benchmark Step 4: Lossy 4K with AAC audio.
Mostly stream copy, should be fast.
"""
command = (
f'ffmpeg -y -hide_banner -nostats -loglevel warning '
f'-i "{input_file}" '
f'-c:v copy -c:a aac -ar 48000 -b:a 320k '
f'"{output_file}"'
)
return run_timed_command("Encode lossy 4K MP4 (Step 4 equivalent)", command)
def benchmark_mkv_flac_encode(input_file: str, output_file: str) -> dict:
"""
Benchmark Step 5: MKV with FLAC audio.
Video copy, audio re-encode to FLAC.
"""
command = (
f'ffmpeg -y -hide_banner -nostats -loglevel warning '
f'-i "{input_file}" '
f'-c:v copy -c:a flac '
f'"{output_file}"'
)
return run_timed_command("Encode MKV with FLAC (Step 5 equivalent)", command)
def benchmark_title_screen_generation(output_file: str) -> dict:
"""
Benchmark title screen generation (5 second video).
This simulates the screens worker.
"""
# Create a title screen similar to what karaoke-gen creates
command = (
f'ffmpeg -y -hide_banner -nostats -loglevel warning '
f'-f lavfi -i "color=black:s=3840x2160:d=5:r=30" '
f'-f lavfi -i "anullsrc=r=48000:cl=stereo:d=5" '
f'-vf "drawtext=text=\'Artist - Title\':fontsize=120:fontcolor=white:'
f'x=(w-text_w)/2:y=(h-text_h)/2" '
f'-c:v libx264 -preset medium -pix_fmt yuv420p '
f'-c:a pcm_s16le '
f'"{output_file}"'
)
return run_timed_command("Generate title screen (5s, 4K)", command)
def get_system_info() -> dict:
"""Get system information for context."""
info = {
"timestamp": datetime.now().isoformat(),
"python_version": sys.version,
}
# Get FFmpeg version
result = subprocess.run("ffmpeg -version", shell=True, capture_output=True, text=True)
if result.returncode == 0:
info["ffmpeg_version"] = result.stdout.split('\n')[0]
# Get CPU info
if sys.platform == "darwin":
result = subprocess.run("sysctl -n machdep.cpu.brand_string", shell=True, capture_output=True, text=True)
if result.returncode == 0:
info["cpu"] = result.stdout.strip()
result = subprocess.run("sysctl -n hw.ncpu", shell=True, capture_output=True, text=True)
if result.returncode == 0:
info["cpu_cores"] = int(result.stdout.strip())
else:
result = subprocess.run("nproc", shell=True, capture_output=True, text=True)
if result.returncode == 0:
info["cpu_cores"] = int(result.stdout.strip())
result = subprocess.run("cat /proc/cpuinfo | grep 'model name' | head -1", shell=True, capture_output=True, text=True)
if result.returncode == 0:
info["cpu"] = result.stdout.split(':')[-1].strip() if ':' in result.stdout else "Unknown"
return info
def main():
parser = argparse.ArgumentParser(description="FFmpeg encoding benchmark")
parser.add_argument("--duration", type=int, default=60, help="Test video duration in seconds")
parser.add_argument("--cloud", action="store_true", help="Running on cloud (skip some checks)")
parser.add_argument("--output-dir", type=Path, help="Output directory for results")
parser.add_argument("--existing-video", type=Path, help="Use existing video instead of creating test")
args = parser.parse_args()
# Setup output directory
if args.output_dir:
output_dir = args.output_dir
output_dir.mkdir(parents=True, exist_ok=True)
else:
output_dir = Path(tempfile.mkdtemp(prefix="ffmpeg_benchmark_"))
print("="*70)
print("FFMPEG ENCODING BENCHMARK")
print("="*70)
print(f"Output directory: {output_dir}")
print(f"Test duration: {args.duration}s")
print(f"Environment: {'Cloud' if args.cloud else 'Local'}")
# Get system info
sys_info = get_system_info()
print(f"\nSystem Info:")
for k, v in sys_info.items():
print(f" {k}: {v}")
results = {
"system_info": sys_info,
"environment": "cloud" if args.cloud else "local",
"benchmarks": [],
}
# Create or use test video
if args.existing_video and args.existing_video.exists():
test_video = str(args.existing_video)
print(f"\nUsing existing video: {test_video}")
else:
test_video = str(output_dir / "test_input.mp4")
result = create_test_video(test_video, args.duration)
results["benchmarks"].append(result)
if not result["success"]:
print("ERROR: Failed to create test video")
sys.exit(1)
# Get video info
video_info = get_video_info(test_video)
if video_info:
duration = float(video_info.get("format", {}).get("duration", args.duration))
print(f"\nTest video duration: {duration:.1f}s")
results["video_duration"] = duration
# Run benchmarks
benchmarks = [
("title_screen", benchmark_title_screen_generation, output_dir / "title_screen.mp4"),
("lossless_4k", benchmark_lossless_4k_encode, output_dir / "output_lossless_4k.mp4"),
("lossy_4k", benchmark_lossy_4k_encode, output_dir / "output_lossy_4k.mp4"),
("mkv_flac", benchmark_mkv_flac_encode, output_dir / "output_lossless_4k.mkv"),
("720p", benchmark_720p_encode, output_dir / "output_720p.mp4"),
]
for name, func, output_path in benchmarks:
if name == "title_screen":
result = func(str(output_path))
else:
result = func(test_video, str(output_path))
results["benchmarks"].append(result)
# Summary
print("\n" + "="*70)
print("BENCHMARK SUMMARY")
print("="*70)
print(f"\n{'Step':<40} {'Time':>12} {'Status':>10}")
print("-"*64)
total_time = 0
for bench in results["benchmarks"]:
status = "OK" if bench["success"] else "FAILED"
time_str = f"{bench['elapsed_seconds']:.2f}s"
print(f"{bench['description']:<40} {time_str:>12} {status:>10}")
if bench["success"]:
total_time += bench["elapsed_seconds"]
print("-"*64)
print(f"{'Total encoding time':<40} {total_time:.2f}s")
# Save results
results_file = output_dir / "benchmark_results.json"
with open(results_file, "w") as f:
json.dump(results, f, indent=2)
print(f"\nResults saved to: {results_file}")
# Cleanup temp files (keep results)
if not args.output_dir:
print(f"\nTemp files in: {output_dir}")
print("Delete manually when done reviewing")
return results
if __name__ == "__main__":
main()
+360
View File
@@ -0,0 +1,360 @@
#!/usr/bin/env python3
"""
Performance comparison script: Local vs Remote karaoke generation.
Runs the same audio file through both local and remote pipelines in
non-interactive mode, capturing detailed timing logs for analysis.
Usage:
python scripts/compare_local_vs_remote.py <audio_file> [--local-only] [--remote-only]
# Run both tests
python scripts/compare_local_vs_remote.py input/minutemen/Search.flac
# Run only local test
python scripts/compare_local_vs_remote.py input/minutemen/Search.flac --local-only
# Run only remote test (useful if local already done)
python scripts/compare_local_vs_remote.py input/minutemen/Search.flac --remote-only
Output:
- output/perf-test-{timestamp}/local/ - Local CLI output + logs
- output/perf-test-{timestamp}/remote/ - Remote CLI output + logs
- output/perf-test-{timestamp}/comparison.txt - Side-by-side timing analysis
"""
import argparse
import os
import subprocess
import sys
import time
import json
import re
from datetime import datetime
from pathlib import Path
def run_command(cmd: list[str], log_file: Path, cwd: Path) -> tuple[int, float]:
"""
Run a command and capture output to a log file.
Returns:
Tuple of (return_code, elapsed_seconds)
"""
print(f"\n{'='*60}")
print(f"Running: {' '.join(cmd)}")
print(f"Logging to: {log_file}")
print(f"{'='*60}\n")
start_time = time.time()
with open(log_file, 'w') as f:
# Write command header
f.write(f"# Command: {' '.join(cmd)}\n")
f.write(f"# Started: {datetime.now().isoformat()}\n")
f.write(f"# CWD: {cwd}\n")
f.write("#" + "=" * 79 + "\n\n")
f.flush()
# Run with real-time output to both console and file
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
cwd=cwd,
text=True,
bufsize=1,
)
for line in process.stdout:
# Add timestamp to each line for log analysis
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
timestamped_line = f"{timestamp} - {line}"
# Write to file
f.write(timestamped_line if not line.startswith("20") else line)
f.flush()
# Echo to console (without extra timestamp)
print(line, end='')
process.wait()
elapsed = time.time() - start_time
# Append timing summary to log
with open(log_file, 'a') as f:
f.write(f"\n# Completed: {datetime.now().isoformat()}\n")
f.write(f"# Return code: {process.returncode}\n")
f.write(f"# Total elapsed: {elapsed:.2f} seconds ({elapsed/60:.1f} minutes)\n")
return process.returncode, elapsed
def extract_job_id_from_log(log_file: Path) -> str | None:
"""Extract the job ID from remote CLI log output."""
content = log_file.read_text()
# Look for job ID in various formats
patterns = [
r'Job ID: ([a-f0-9-]+)',
r'job_id["\']?\s*[:=]\s*["\']?([a-f0-9-]+)',
r'Created job: ([a-f0-9-]+)',
r'/jobs/([a-f0-9-]+)',
]
for pattern in patterns:
match = re.search(pattern, content, re.IGNORECASE)
if match:
return match.group(1)
return None
def run_local_test(audio_file: Path, output_dir: Path, artist: str, title: str) -> tuple[int, float, Path]:
"""
Run local karaoke-gen CLI test.
Returns:
Tuple of (return_code, elapsed_seconds, log_file_path)
"""
print("\n" + "=" * 70)
print("RUNNING LOCAL TEST (karaoke-gen)")
print("=" * 70)
log_file = output_dir / "local_cli.log"
cmd = [
"poetry", "run", "karaoke-gen",
str(audio_file.absolute()),
artist,
title,
"--output_dir", str(output_dir.absolute()),
"--log_level", "DEBUG",
"--skip_transcription_review", # Non-interactive: skip lyrics review
"--skip_instrumental_review", # Non-interactive: skip instrumental selection
"-y", # Auto-confirm prompts
]
# Get project root for cwd
project_root = Path(__file__).parent.parent
return_code, elapsed = run_command(cmd, log_file, project_root)
return return_code, elapsed, log_file
def run_remote_test(audio_file: Path, output_dir: Path, artist: str, title: str) -> tuple[int, float, Path, str | None]:
"""
Run remote karaoke-gen-remote CLI test.
Returns:
Tuple of (return_code, elapsed_seconds, log_file_path, job_id)
"""
print("\n" + "=" * 70)
print("RUNNING REMOTE TEST (karaoke-gen-remote)")
print("=" * 70)
log_file = output_dir / "remote_cli.log"
cmd = [
"poetry", "run", "karaoke-gen-remote",
str(audio_file.absolute()),
artist,
title,
"--output_dir", str(output_dir.absolute()),
"--log_level", "DEBUG",
"--skip_transcription_review", # Non-interactive: skip lyrics review
"--skip_instrumental_review", # Non-interactive: skip instrumental selection
"-y", # Auto-confirm prompts
]
# Get project root for cwd
project_root = Path(__file__).parent.parent
return_code, elapsed = run_command(cmd, log_file, project_root)
# Try to extract job ID for fetching cloud logs
job_id = extract_job_id_from_log(log_file)
return return_code, elapsed, log_file, job_id
def analyze_logs(local_log: Path | None, remote_log: Path | None, output_dir: Path) -> None:
"""Run timing analysis on the logs and generate comparison."""
project_root = Path(__file__).parent.parent
analyzer = project_root / "scripts" / "analyze_log_timing.py"
results = {}
if local_log and local_log.exists():
print("\n" + "=" * 70)
print("ANALYZING LOCAL LOG")
print("=" * 70)
# Run analyzer with JSON output
result = subprocess.run(
["python", str(analyzer), str(local_log), "--json"],
capture_output=True,
text=True,
)
if result.returncode == 0:
try:
results['local'] = json.loads(result.stdout)
except json.JSONDecodeError:
print(f"Warning: Could not parse local log analysis")
# Also print human-readable output
subprocess.run(
["python", str(analyzer), str(local_log)],
cwd=project_root,
)
if remote_log and remote_log.exists():
print("\n" + "=" * 70)
print("ANALYZING REMOTE LOG")
print("=" * 70)
# Run analyzer with JSON output
result = subprocess.run(
["python", str(analyzer), str(remote_log), "--json"],
capture_output=True,
text=True,
)
if result.returncode == 0:
try:
results['remote'] = json.loads(result.stdout)
except json.JSONDecodeError:
print(f"Warning: Could not parse remote log analysis")
# Also print human-readable output
subprocess.run(
["python", str(analyzer), str(remote_log)],
cwd=project_root,
)
# Generate comparison summary
if results:
comparison_file = output_dir / "comparison.json"
comparison_file.write_text(json.dumps(results, indent=2))
print(f"\nComparison data saved to: {comparison_file}")
# Print comparison summary
if 'local' in results and 'remote' in results:
print("\n" + "=" * 70)
print("PERFORMANCE COMPARISON SUMMARY")
print("=" * 70)
local_total = results['local'].get('total_wall_clock_seconds', 0)
remote_total = results['remote'].get('total_wall_clock_seconds', 0)
local_auto = results['local'].get('automated_processing_seconds', 0)
remote_auto = results['remote'].get('automated_processing_seconds', 0)
print(f"\n{'Metric':<35} {'Local':>12} {'Remote':>12} {'Diff':>12}")
print("-" * 73)
if local_total and remote_total:
diff = remote_total - local_total
print(f"{'Total wall-clock time':35} {local_total:>10.1f}s {remote_total:>10.1f}s {diff:>+10.1f}s")
if local_auto and remote_auto:
diff = remote_auto - local_auto
print(f"{'Automated processing':35} {local_auto:>10.1f}s {remote_auto:>10.1f}s {diff:>+10.1f}s")
# Compare category totals
print("\nCategory breakdown:")
local_cats = results['local'].get('category_totals', {})
remote_cats = results['remote'].get('category_totals', {})
all_cats = set(local_cats.keys()) | set(remote_cats.keys())
for cat in sorted(all_cats):
local_time = local_cats.get(cat, 0)
remote_time = remote_cats.get(cat, 0)
if local_time > 0 or remote_time > 0:
diff = remote_time - local_time
cat_label = cat.replace('_', ' ').title()
print(f" {cat_label:<33} {local_time:>10.1f}s {remote_time:>10.1f}s {diff:>+10.1f}s")
def main():
parser = argparse.ArgumentParser(
description="Compare local vs remote karaoke generation performance"
)
parser.add_argument("audio_file", type=Path, help="Path to audio file to process")
parser.add_argument("--artist", default="Minutemen", help="Artist name (default: Minutemen)")
parser.add_argument("--title", default="Search", help="Track title (default: Search)")
parser.add_argument("--local-only", action="store_true", help="Only run local test")
parser.add_argument("--remote-only", action="store_true", help="Only run remote test")
parser.add_argument("--output-dir", type=Path, help="Custom output directory")
args = parser.parse_args()
# Validate audio file
if not args.audio_file.exists():
print(f"Error: Audio file not found: {args.audio_file}")
sys.exit(1)
# Create timestamped output directory
timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
if args.output_dir:
output_base = args.output_dir
else:
output_base = Path(__file__).parent.parent / "output" / f"perf-test-{timestamp}"
output_base.mkdir(parents=True, exist_ok=True)
local_output = output_base / "local"
remote_output = output_base / "remote"
print(f"\n{'='*70}")
print(f"KARAOKE GENERATION PERFORMANCE TEST")
print(f"{'='*70}")
print(f"Audio file: {args.audio_file}")
print(f"Artist: {args.artist}")
print(f"Title: {args.title}")
print(f"Output directory: {output_base}")
print(f"{'='*70}")
local_log = None
remote_log = None
# Run local test
if not args.remote_only:
local_output.mkdir(parents=True, exist_ok=True)
return_code, elapsed, local_log = run_local_test(
args.audio_file, local_output, args.artist, args.title
)
print(f"\nLocal test completed in {elapsed:.1f}s ({elapsed/60:.1f} minutes)")
print(f"Return code: {return_code}")
# Run remote test
if not args.local_only:
remote_output.mkdir(parents=True, exist_ok=True)
return_code, elapsed, remote_log, job_id = run_remote_test(
args.audio_file, remote_output, args.artist, args.title
)
print(f"\nRemote test completed in {elapsed:.1f}s ({elapsed/60:.1f} minutes)")
print(f"Return code: {return_code}")
if job_id:
print(f"Job ID: {job_id}")
print(f"\nTo fetch detailed cloud logs:")
print(f" python scripts/fetch_job_logs.py {job_id}")
# Analyze logs
analyze_logs(local_log, remote_log, output_base)
print(f"\n{'='*70}")
print(f"TEST COMPLETE")
print(f"{'='*70}")
print(f"Output directory: {output_base}")
if local_log:
print(f"Local log: {local_log}")
if remote_log:
print(f"Remote log: {remote_log}")
if __name__ == "__main__":
main()
+170
View File
@@ -0,0 +1,170 @@
#!/usr/bin/env python3
"""
Fetch cloud job logs from Firestore and save to a local file.
This script extracts worker_logs and timeline entries from a cloud job
and formats them into a log file compatible with analyze_log_timing.py.
Usage:
python scripts/fetch_job_logs.py <job_id> [output_file]
python scripts/fetch_job_logs.py 7ccfcd64
python scripts/fetch_job_logs.py 7ccfcd64 ./output/job-7ccfcd64.log
Requires:
- google-cloud-firestore
- GOOGLE_APPLICATION_CREDENTIALS or gcloud auth application-default login
"""
import sys
import json
from datetime import datetime
from pathlib import Path
from google.cloud import firestore
def get_job(job_id: str) -> dict | None:
"""Fetch job document from Firestore."""
db = firestore.Client(project='nomadkaraoke')
doc = db.collection('jobs').document(job_id).get()
if doc.exists:
return doc.to_dict()
return None
def format_worker_log(log: dict) -> str:
"""Format a worker_log entry as a log line."""
timestamp = log.get('timestamp', '')
# Handle both string and datetime timestamps
if hasattr(timestamp, 'isoformat'):
timestamp = timestamp.isoformat()
worker = log.get('worker', 'unknown')
level = log.get('level', 'INFO')
message = log.get('message', '')
# Format: TIMESTAMP [WORKER] LEVEL: MESSAGE
return f"{timestamp} [{worker}] {level}: {message}"
def format_timeline_entry(entry: dict) -> str:
"""Format a timeline entry as a log line."""
timestamp = entry.get('timestamp', '')
# Handle both string and datetime timestamps
if hasattr(timestamp, 'isoformat'):
timestamp = timestamp.isoformat()
status = entry.get('status', 'unknown')
message = entry.get('message', '')
progress = entry.get('progress', '')
# Format: TIMESTAMP [timeline] STATUS: MESSAGE (progress%)
progress_str = f" ({progress}%)" if progress else ""
return f"{timestamp} [timeline] {status}: {message}{progress_str}"
def fetch_job_logs(job_id: str, output_path: str | None = None) -> str:
"""
Fetch job logs from Firestore and save to a file.
Args:
job_id: The job ID to fetch logs for
output_path: Optional path to save logs. If None, uses ./output/job-{job_id}.log
Returns:
Path to the saved log file
"""
data = get_job(job_id)
if data is None:
print(f"Error: Job {job_id} not found", file=sys.stderr)
sys.exit(1)
# Collect all log entries with timestamps
log_entries = []
# Extract worker_logs
worker_logs = data.get('worker_logs', [])
for log in worker_logs:
timestamp = log.get('timestamp', '')
if hasattr(timestamp, 'isoformat'):
timestamp = timestamp.isoformat()
log_entries.append({
'timestamp': timestamp,
'line': format_worker_log(log)
})
# Extract timeline entries
timeline = data.get('timeline', [])
for entry in timeline:
timestamp = entry.get('timestamp', '')
if hasattr(timestamp, 'isoformat'):
timestamp = timestamp.isoformat()
log_entries.append({
'timestamp': timestamp,
'line': format_timeline_entry(entry)
})
# Sort all entries by timestamp
log_entries.sort(key=lambda x: x['timestamp'])
# Generate header with job metadata
header_lines = [
f"# Cloud Job Logs for {job_id}",
f"# Fetched at: {datetime.now().isoformat()}",
f"# Status: {data.get('status', 'unknown')}",
f"# Artist: {data.get('artist', 'unknown')}",
f"# Title: {data.get('title', 'unknown')}",
f"# Created: {data.get('created_at', 'unknown')}",
f"# Worker logs: {len(worker_logs)}",
f"# Timeline entries: {len(timeline)}",
"#" + "=" * 79,
""
]
# Combine header and log lines
all_lines = header_lines + [entry['line'] for entry in log_entries]
content = '\n'.join(all_lines)
# Determine output path
if output_path is None:
output_dir = Path('./output')
output_dir.mkdir(exist_ok=True)
output_path = output_dir / f"job-{job_id}.log"
else:
output_path = Path(output_path)
output_path.parent.mkdir(parents=True, exist_ok=True)
# Write to file
output_path.write_text(content)
return str(output_path)
def main():
if len(sys.argv) < 2:
print(__doc__)
print("\nExamples:")
print(" python scripts/fetch_job_logs.py 7ccfcd64")
print(" python scripts/fetch_job_logs.py 7ccfcd64 ./logs/my-job.log")
print("\nThe output file can be analyzed with:")
print(" python scripts/analyze_log_timing.py ./output/job-7ccfcd64.log")
sys.exit(1)
job_id = sys.argv[1]
output_path = sys.argv[2] if len(sys.argv) > 2 else None
print(f"Fetching logs for job {job_id}...", file=sys.stderr)
saved_path = fetch_job_logs(job_id, output_path)
print(f"Logs saved to: {saved_path}", file=sys.stderr)
print(f"\nTo analyze timing, run:", file=sys.stderr)
print(f" python scripts/analyze_log_timing.py {saved_path}", file=sys.stderr)
# Print the path to stdout for scripting
print(saved_path)
if __name__ == "__main__":
main()