mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-27 01:18:42 +09:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
03c0e0954b | ||
|
|
2e71dc3158 | ||
|
|
03a7d573f5 |
No files matched your search
@@ -25,6 +25,7 @@ from backend.models.requests import (
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.worker_service import get_worker_service
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.theme_service import get_theme_service
|
||||
from backend.config import get_settings
|
||||
from backend.api.dependencies import require_admin, require_auth, require_instrumental_auth
|
||||
from backend.services.auth_service import UserType, AuthResult
|
||||
@@ -93,11 +94,22 @@ async def create_job(
|
||||
settings = get_settings()
|
||||
effective_enable_youtube_upload = request.enable_youtube_upload if request.enable_youtube_upload is not None else settings.default_enable_youtube_upload
|
||||
|
||||
# Apply default theme - all jobs require a theme
|
||||
theme_service = get_theme_service()
|
||||
effective_theme_id = theme_service.get_default_theme_id()
|
||||
if not effective_theme_id:
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail="No default theme configured. Please contact support or specify a theme_id."
|
||||
)
|
||||
logger.info(f"Applying default theme: {effective_theme_id}")
|
||||
|
||||
# Create job with all preferences
|
||||
job_create = JobCreate(
|
||||
url=str(request.url),
|
||||
artist=request.artist,
|
||||
title=request.title,
|
||||
theme_id=effective_theme_id, # Required - all jobs must have a theme
|
||||
enable_cdg=request.enable_cdg,
|
||||
enable_txt=request.enable_txt,
|
||||
enable_youtube_upload=effective_enable_youtube_upload,
|
||||
|
||||
@@ -32,7 +32,9 @@ from backend.models.user import (
|
||||
from backend.services.user_service import get_user_service, UserService, USERS_COLLECTION
|
||||
from backend.services.email_service import get_email_service, EmailService
|
||||
from backend.services.stripe_service import get_stripe_service, StripeService, CREDIT_PACKAGES
|
||||
from backend.services.theme_service import get_theme_service
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.api.routes.file_upload import _prepare_theme_for_job
|
||||
from backend.services.auth_service import UserType
|
||||
from backend.utils.test_data import is_test_email
|
||||
|
||||
@@ -434,6 +436,12 @@ async def _handle_done_for_you_order(
|
||||
worker_service = get_worker_service()
|
||||
storage_service = StorageService()
|
||||
|
||||
# Apply default theme (Nomad) - same as audio_search endpoint
|
||||
theme_service = get_theme_service()
|
||||
effective_theme_id = theme_service.get_default_theme_id()
|
||||
if effective_theme_id:
|
||||
logger.info(f"Applying default theme '{effective_theme_id}' for done-for-you order")
|
||||
|
||||
# Create job for the customer
|
||||
# Note: done-for-you jobs should NOT be non_interactive - Andrew needs to review
|
||||
job_create = JobCreate(
|
||||
@@ -441,6 +449,7 @@ async def _handle_done_for_you_order(
|
||||
artist=artist,
|
||||
title=title,
|
||||
user_email=customer_email, # Customer owns the job
|
||||
theme_id=effective_theme_id, # Apply default theme
|
||||
non_interactive=False, # Andrew will review lyrics/instrumental
|
||||
# Set audio search fields for search-based orders
|
||||
audio_search_artist=artist if not youtube_url else None,
|
||||
@@ -452,6 +461,23 @@ async def _handle_done_for_you_order(
|
||||
|
||||
logger.info(f"Created done-for-you job {job_id} for {customer_email}")
|
||||
|
||||
# Prepare theme style assets for the job (same as audio_search endpoint)
|
||||
if effective_theme_id:
|
||||
try:
|
||||
style_params_path, theme_style_assets, youtube_desc = _prepare_theme_for_job(
|
||||
job_id, effective_theme_id, None # No color overrides for done-for-you
|
||||
)
|
||||
theme_update = {
|
||||
'style_params_gcs_path': style_params_path,
|
||||
'style_assets': theme_style_assets,
|
||||
}
|
||||
if youtube_desc:
|
||||
theme_update['youtube_description_template'] = youtube_desc
|
||||
job_manager.update_job(job_id, theme_update)
|
||||
logger.info(f"Applied theme '{effective_theme_id}' to done-for-you job {job_id}")
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to prepare theme for done-for-you job {job_id}: {e}")
|
||||
|
||||
# Mark session as processed for idempotency
|
||||
# Note: Using internal method since this isn't a credit transaction
|
||||
user_service._mark_stripe_session_processed(
|
||||
|
||||
@@ -25,6 +25,11 @@ from backend.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Retry configuration for handling transient failures (e.g., worker restarts)
|
||||
MAX_RETRIES = 3
|
||||
INITIAL_BACKOFF_SECONDS = 2.0
|
||||
MAX_BACKOFF_SECONDS = 10.0
|
||||
|
||||
|
||||
class EncodingService:
|
||||
"""Service for dispatching encoding jobs to GCE worker."""
|
||||
@@ -68,6 +73,81 @@ class EncodingService:
|
||||
"""Check if GCE preview encoding is enabled and configured."""
|
||||
return self.settings.use_gce_preview_encoding and self.is_configured
|
||||
|
||||
async def _request_with_retry(
|
||||
self,
|
||||
method: str,
|
||||
url: str,
|
||||
headers: Dict[str, str],
|
||||
json_payload: Optional[Dict[str, Any]] = None,
|
||||
timeout: float = 30.0,
|
||||
job_id: str = "unknown",
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Make an HTTP request with retry logic for transient failures.
|
||||
|
||||
This handles connection errors that occur when the GCE worker is
|
||||
restarting (e.g., during deployments) by retrying with exponential backoff.
|
||||
|
||||
Args:
|
||||
method: HTTP method (GET, POST)
|
||||
url: Request URL
|
||||
headers: Request headers
|
||||
json_payload: JSON body for POST requests
|
||||
timeout: Request timeout in seconds
|
||||
job_id: Job ID for logging
|
||||
|
||||
Returns:
|
||||
Dict with keys:
|
||||
- status (int): HTTP status code
|
||||
- json (Any): Parsed JSON response body (if status 200, else None)
|
||||
- text (str): Raw response text (if status != 200, else None)
|
||||
|
||||
Raises:
|
||||
aiohttp.ClientConnectorError: If all retries fail due to connection errors
|
||||
aiohttp.ServerDisconnectedError: If all retries fail due to server disconnect
|
||||
asyncio.TimeoutError: If all retries fail due to timeout
|
||||
"""
|
||||
last_exception = None
|
||||
backoff = INITIAL_BACKOFF_SECONDS
|
||||
|
||||
for attempt in range(MAX_RETRIES + 1):
|
||||
try:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
if method.upper() == "POST":
|
||||
async with session.post(
|
||||
url, json=json_payload, headers=headers, timeout=timeout
|
||||
) as resp:
|
||||
# Return a copy of the response data since we exit the context
|
||||
return {
|
||||
"status": resp.status,
|
||||
"json": await resp.json() if resp.status == 200 else None,
|
||||
"text": await resp.text() if resp.status != 200 else None,
|
||||
}
|
||||
else: # GET
|
||||
async with session.get(
|
||||
url, headers=headers, timeout=timeout
|
||||
) as resp:
|
||||
return {
|
||||
"status": resp.status,
|
||||
"json": await resp.json() if resp.status == 200 else None,
|
||||
"text": await resp.text() if resp.status != 200 else None,
|
||||
}
|
||||
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError, asyncio.TimeoutError) as e:
|
||||
last_exception = e
|
||||
if attempt < MAX_RETRIES:
|
||||
logger.warning(
|
||||
f"[job:{job_id}] GCE worker connection failed (attempt {attempt + 1}/{MAX_RETRIES + 1}): {e}. "
|
||||
f"Retrying in {backoff:.1f}s..."
|
||||
)
|
||||
await asyncio.sleep(backoff)
|
||||
backoff = min(backoff * 2, MAX_BACKOFF_SECONDS)
|
||||
else:
|
||||
logger.error(
|
||||
f"[job:{job_id}] GCE worker connection failed after {MAX_RETRIES + 1} attempts: {e}"
|
||||
)
|
||||
|
||||
raise last_exception
|
||||
|
||||
async def submit_encoding_job(
|
||||
self,
|
||||
job_id: str,
|
||||
@@ -106,17 +186,23 @@ class EncodingService:
|
||||
|
||||
logger.info(f"[job:{job_id}] Submitting encoding job to GCE worker: {url}")
|
||||
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.post(url, json=payload, headers=headers, timeout=30) as resp:
|
||||
if resp.status == 401:
|
||||
raise RuntimeError("Invalid API key for encoding worker")
|
||||
if resp.status == 409:
|
||||
raise RuntimeError(f"Encoding job {job_id} already exists")
|
||||
if resp.status != 200:
|
||||
text = await resp.text()
|
||||
raise RuntimeError(f"Failed to submit encoding job: {resp.status} - {text}")
|
||||
resp = await self._request_with_retry(
|
||||
method="POST",
|
||||
url=url,
|
||||
headers=headers,
|
||||
json_payload=payload,
|
||||
timeout=30.0,
|
||||
job_id=job_id,
|
||||
)
|
||||
|
||||
return await resp.json()
|
||||
if resp["status"] == 401:
|
||||
raise RuntimeError("Invalid API key for encoding worker")
|
||||
if resp["status"] == 409:
|
||||
raise RuntimeError(f"Encoding job {job_id} already exists")
|
||||
if resp["status"] != 200:
|
||||
raise RuntimeError(f"Failed to submit encoding job: {resp['status']} - {resp['text']}")
|
||||
|
||||
return resp["json"]
|
||||
|
||||
async def get_job_status(self, job_id: str) -> Dict[str, Any]:
|
||||
"""
|
||||
@@ -136,17 +222,22 @@ class EncodingService:
|
||||
url = f"{self._url}/status/{job_id}"
|
||||
headers = {"X-API-Key": self._api_key}
|
||||
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(url, headers=headers, timeout=30) as resp:
|
||||
if resp.status == 401:
|
||||
raise RuntimeError("Invalid API key for encoding worker")
|
||||
if resp.status == 404:
|
||||
raise RuntimeError(f"Encoding job {job_id} not found")
|
||||
if resp.status != 200:
|
||||
text = await resp.text()
|
||||
raise RuntimeError(f"Failed to get job status: {resp.status} - {text}")
|
||||
resp = await self._request_with_retry(
|
||||
method="GET",
|
||||
url=url,
|
||||
headers=headers,
|
||||
timeout=30.0,
|
||||
job_id=job_id,
|
||||
)
|
||||
|
||||
return await resp.json()
|
||||
if resp["status"] == 401:
|
||||
raise RuntimeError("Invalid API key for encoding worker")
|
||||
if resp["status"] == 404:
|
||||
raise RuntimeError(f"Encoding job {job_id} not found")
|
||||
if resp["status"] != 200:
|
||||
raise RuntimeError(f"Failed to get job status: {resp['status']} - {resp['text']}")
|
||||
|
||||
return resp["json"]
|
||||
|
||||
async def wait_for_completion(
|
||||
self,
|
||||
@@ -296,17 +387,23 @@ class EncodingService:
|
||||
|
||||
logger.info(f"[job:{job_id}] Submitting preview encoding job to GCE worker: {url}")
|
||||
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.post(url, json=payload, headers=headers, timeout=30) as resp:
|
||||
if resp.status == 401:
|
||||
raise RuntimeError("Invalid API key for encoding worker")
|
||||
if resp.status == 409:
|
||||
raise RuntimeError(f"Preview encoding job {job_id} already exists")
|
||||
if resp.status != 200:
|
||||
text = await resp.text()
|
||||
raise RuntimeError(f"Failed to submit preview encoding job: {resp.status} - {text}")
|
||||
resp = await self._request_with_retry(
|
||||
method="POST",
|
||||
url=url,
|
||||
headers=headers,
|
||||
json_payload=payload,
|
||||
timeout=30.0,
|
||||
job_id=job_id,
|
||||
)
|
||||
|
||||
return await resp.json()
|
||||
if resp["status"] == 401:
|
||||
raise RuntimeError("Invalid API key for encoding worker")
|
||||
if resp["status"] == 409:
|
||||
raise RuntimeError(f"Preview encoding job {job_id} already exists")
|
||||
if resp["status"] != 200:
|
||||
raise RuntimeError(f"Failed to submit preview encoding job: {resp['status']} - {resp['text']}")
|
||||
|
||||
return resp["json"]
|
||||
|
||||
async def encode_preview_video(
|
||||
self,
|
||||
|
||||
@@ -34,10 +34,21 @@ class JobManager:
|
||||
def create_job(self, job_create: JobCreate) -> Job:
|
||||
"""
|
||||
Create a new job with initial state PENDING.
|
||||
|
||||
|
||||
Jobs start in PENDING state and transition to DOWNLOADING
|
||||
when a worker picks them up.
|
||||
|
||||
Raises:
|
||||
ValueError: If theme_id is not provided (all jobs require a theme)
|
||||
"""
|
||||
# Enforce theme requirement - all jobs must have a theme
|
||||
# This prevents unstyled videos from ever being generated
|
||||
if not job_create.theme_id:
|
||||
raise ValueError(
|
||||
"theme_id is required for all jobs. "
|
||||
"Use get_theme_service().get_default_theme_id() to get the default theme."
|
||||
)
|
||||
|
||||
job_id = str(uuid.uuid4())[:8]
|
||||
|
||||
now = datetime.utcnow()
|
||||
|
||||
@@ -39,6 +39,24 @@ os.environ["ADMIN_TOKENS"] = "test-admin-token"
|
||||
|
||||
# Only import app if emulators are running
|
||||
if emulators_running():
|
||||
from unittest.mock import Mock
|
||||
|
||||
# Mock theme service BEFORE importing app to ensure all jobs get theme_id="nomad"
|
||||
_mock_theme_service = Mock()
|
||||
_mock_theme_service.get_default_theme_id.return_value = "nomad"
|
||||
_mock_theme_service.get_theme.return_value = None
|
||||
|
||||
# Apply patch at module load time (before app imports the service)
|
||||
_theme_patches = [
|
||||
patch("backend.services.theme_service.get_theme_service", return_value=_mock_theme_service),
|
||||
patch("backend.api.routes.audio_search.get_theme_service", return_value=_mock_theme_service),
|
||||
patch("backend.api.routes.file_upload.get_theme_service", return_value=_mock_theme_service),
|
||||
patch("backend.api.routes.users.get_theme_service", return_value=_mock_theme_service),
|
||||
patch("backend.api.routes.jobs.get_theme_service", return_value=_mock_theme_service),
|
||||
]
|
||||
for p in _theme_patches:
|
||||
p.start()
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.main import app
|
||||
else:
|
||||
@@ -76,7 +94,10 @@ def mock_worker_service():
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def client(mock_worker_service):
|
||||
"""Create FastAPI test client with mocked workers."""
|
||||
"""Create FastAPI test client with mocked workers.
|
||||
|
||||
Theme service is mocked at module load time (see above).
|
||||
"""
|
||||
with patch("backend.api.routes.file_upload.worker_service", mock_worker_service):
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@@ -33,13 +33,28 @@ def job_manager(mock_firestore_service):
|
||||
|
||||
class TestJobCreation:
|
||||
"""Test job creation logic."""
|
||||
|
||||
|
||||
def test_create_job_requires_theme_id(self, job_manager, mock_firestore_service):
|
||||
"""Test that jobs without theme_id are rejected."""
|
||||
job_create = JobCreate(
|
||||
artist="Test Artist",
|
||||
title="Test Song"
|
||||
# No theme_id - should fail
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="theme_id is required"):
|
||||
job_manager.create_job(job_create)
|
||||
|
||||
# Verify Firestore was NOT called
|
||||
mock_firestore_service.create_job.assert_not_called()
|
||||
|
||||
def test_create_job_with_url(self, job_manager, mock_firestore_service):
|
||||
"""Test creating a job with YouTube URL."""
|
||||
job_create = JobCreate(
|
||||
url="https://youtube.com/watch?v=test",
|
||||
artist="Test Artist",
|
||||
title="Test Song"
|
||||
title="Test Song",
|
||||
theme_id="nomad" # Required for all jobs
|
||||
)
|
||||
|
||||
# The actual create_job method creates the job and returns it
|
||||
@@ -59,7 +74,8 @@ class TestJobCreation:
|
||||
"""Test creating a job without URL (for file upload)."""
|
||||
job_create = JobCreate(
|
||||
artist="Test Artist",
|
||||
title="Test Song"
|
||||
title="Test Song",
|
||||
theme_id="nomad" # Required for all jobs
|
||||
)
|
||||
|
||||
job = job_manager.create_job(job_create)
|
||||
@@ -70,8 +86,8 @@ class TestJobCreation:
|
||||
|
||||
def test_create_job_generates_unique_id(self, job_manager, mock_firestore_service):
|
||||
"""Test that each job gets a unique ID."""
|
||||
job_create = JobCreate()
|
||||
|
||||
job_create = JobCreate(theme_id="nomad") # Required for all jobs
|
||||
|
||||
# Create multiple jobs
|
||||
ids = []
|
||||
for i in range(5):
|
||||
@@ -89,8 +105,8 @@ class TestJobCreation:
|
||||
|
||||
def test_create_job_sets_initial_status(self, job_manager, mock_firestore_service):
|
||||
"""Test that new jobs start with PENDING status."""
|
||||
job_create = JobCreate()
|
||||
|
||||
job_create = JobCreate(theme_id="nomad") # Required for all jobs
|
||||
|
||||
mock_firestore_service.create_job.return_value = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.PENDING,
|
||||
@@ -105,13 +121,14 @@ class TestJobCreation:
|
||||
|
||||
def test_create_job_with_distribution_settings(self, job_manager, mock_firestore_service):
|
||||
"""Test that distribution settings are passed from JobCreate to Job.
|
||||
|
||||
|
||||
This was a bug where brand_prefix, dropbox_path, gdrive_folder_id, and
|
||||
discord_webhook_url were NOT being passed to the Job constructor.
|
||||
"""
|
||||
job_create = JobCreate(
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
theme_id="nomad", # Required for all jobs
|
||||
brand_prefix="NOMAD",
|
||||
discord_webhook_url="https://discord.com/webhook/test",
|
||||
dropbox_path="/Karaoke/Tracks-Organized",
|
||||
|
||||
@@ -50,7 +50,16 @@ def mock_worker_service():
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(mock_job_manager, mock_worker_service):
|
||||
def mock_theme_service():
|
||||
"""Create a mock ThemeService that returns 'nomad' as default theme."""
|
||||
service = MagicMock()
|
||||
service.get_default_theme_id.return_value = "nomad"
|
||||
service.get_theme.return_value = None
|
||||
return service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(mock_job_manager, mock_worker_service, mock_theme_service):
|
||||
"""Create TestClient with mocked dependencies."""
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
@@ -63,6 +72,7 @@ def client(mock_job_manager, mock_worker_service):
|
||||
# Also patch JobManager class used in dependencies.py for auth checks
|
||||
with patch('backend.api.routes.jobs.job_manager', mock_job_manager), \
|
||||
patch('backend.api.routes.jobs.worker_service', mock_worker_service), \
|
||||
patch('backend.api.routes.jobs.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.services.job_manager.JobManager', mock_job_manager_factory), \
|
||||
patch('backend.services.firestore_service.firestore'), \
|
||||
patch('backend.services.storage_service.storage'), \
|
||||
|
||||
@@ -218,26 +218,36 @@ async def generate_screens(job_id: str) -> bool:
|
||||
def _validate_prerequisites(job) -> bool:
|
||||
"""
|
||||
Validate that both audio and lyrics processing are complete.
|
||||
|
||||
|
||||
Single Responsibility: Validation logic separated from main flow.
|
||||
|
||||
|
||||
Args:
|
||||
job: Job object
|
||||
|
||||
|
||||
Returns:
|
||||
True if prerequisites met, False otherwise
|
||||
"""
|
||||
# SAFETY NET: Enforce theme requirement at processing time
|
||||
# This catches any jobs that somehow bypassed JobManager.create_job() validation
|
||||
if not job.theme_id:
|
||||
logger.error(
|
||||
f"Job {job.job_id}: CRITICAL - No theme_id configured. "
|
||||
"All jobs must have a theme to generate styled videos. "
|
||||
"This job should have been rejected at creation time."
|
||||
)
|
||||
return False
|
||||
|
||||
audio_complete = job.state_data.get('audio_complete', False)
|
||||
lyrics_complete = job.state_data.get('lyrics_complete', False)
|
||||
|
||||
|
||||
if not audio_complete:
|
||||
logger.error(f"Job {job.job_id}: Audio processing not complete")
|
||||
return False
|
||||
|
||||
|
||||
if not lyrics_complete:
|
||||
logger.error(f"Job {job.job_id}: Lyrics processing not complete")
|
||||
return False
|
||||
|
||||
|
||||
if not job.artist or not job.title:
|
||||
logger.error(f"Job {job.job_id}: Missing artist or title")
|
||||
return False
|
||||
|
||||
@@ -30,9 +30,10 @@
|
||||
│ (jobs) │ │ (files) │ │ (API keys) │ │ Worker (*) │
|
||||
└──────────┘ └──────────┘ └──────────────┘ └──────────────┘
|
||||
|
||||
(*) GCE Encoding Worker: C4-standard-8 VM with Intel Granite Rapids for
|
||||
high-performance FFmpeg encoding. Used for both final video encoding and
|
||||
preview video generation. Uses LocalEncodingService via GCS wheel deployment.
|
||||
(*) GCE Encoding Worker: c4d-highcpu-32 VM with AMD EPYC 9B45 (Turin) for
|
||||
high-performance FFmpeg encoding (4.92x faster than previous c4-standard-8).
|
||||
Used for both final video encoding and preview video generation.
|
||||
Uses LocalEncodingService via GCS wheel deployment.
|
||||
```
|
||||
|
||||
## Processing Pipeline
|
||||
|
||||
@@ -76,6 +76,37 @@ Audio separation and lyrics transcription run in parallel:
|
||||
|
||||
**Debugging**: Use `scripts/compare_local_vs_remote.py` to benchmark local vs cloud performance.
|
||||
|
||||
### GCE Instance Type Selection for FFmpeg Encoding
|
||||
|
||||
**Problem**: GCE encoding worker (c4-standard-8 Intel) was 1.75x slower than a MacBook Pro M3 Max for CPU-bound FFmpeg encoding with libass subtitle rendering. GPU acceleration is NOT an option because libass is CPU-only.
|
||||
|
||||
**Investigation methodology**:
|
||||
1. Created benchmark scripts (`scripts/benchmark_encoding.py`, `scripts/benchmark_encoding_gce.sh`) using actual production data
|
||||
2. Tested actual code paths (not duplicated FFmpeg commands)
|
||||
3. Benchmarked multiple GCE instance types head-to-head
|
||||
|
||||
**Key finding**: AMD EPYC vastly outperforms Intel Xeon for this workload.
|
||||
|
||||
| Instance | CPU | Total Time | vs Baseline |
|
||||
|----------|-----|------------|-------------|
|
||||
| c4-standard-8 (baseline) | Intel Xeon 8581C | 666s | 1.00x |
|
||||
| c4-highcpu-16 | Intel Xeon 8581C | 309s | 2.16x |
|
||||
| c4a-highcpu-16 | Google Axion (ARM) | 248s | 2.69x |
|
||||
| c4d-highcpu-16 | AMD EPYC 9B45 | 220s | 3.03x |
|
||||
| **c4d-highcpu-32** | **AMD EPYC 9B45** | **135s** | **4.92x** |
|
||||
|
||||
**Why AMD wins for this workload**:
|
||||
- Better single-thread performance (critical for libass, which is not fully parallelized)
|
||||
- Superior AVX-512 implementation for video encoding
|
||||
- Better memory bandwidth
|
||||
- Near-linear scaling with cores for FFmpeg (16→32 cores = 1.63x faster)
|
||||
|
||||
**Lesson**: Don't assume Intel is faster. For CPU-bound media workloads (especially with libass/libx264), benchmark actual instance types. AMD EPYC Turin (C4D series) significantly outperforms Intel Granite Rapids (C4 series) at similar price points.
|
||||
|
||||
**Important**: C4D instances require `hyperdisk-balanced` disk type, not `pd-balanced`.
|
||||
|
||||
**Scripts**: See `scripts/benchmark_candidates.sh` for multi-instance benchmarking orchestration.
|
||||
|
||||
## Common Gotchas
|
||||
|
||||
### Verify Active Worktree Before Making Changes
|
||||
@@ -159,6 +190,105 @@ if effective_theme_id is None:
|
||||
|
||||
The backend approach is more robust - it ensures correct behavior regardless of which client (web, CLI, API) makes the request.
|
||||
|
||||
### Defense in Depth: Enforce Critical Requirements at Multiple Layers
|
||||
|
||||
**Problem**: Despite backend logic to apply a default theme, a job created via the done-for-you webhook was created without a theme_id. The webhook handler didn't include the theme application logic that other endpoints had.
|
||||
|
||||
**Symptoms**:
|
||||
- Job had `theme_id: None` and generated unstyled videos (black background, no branding)
|
||||
- Only affected one code path (done-for-you webhook), others worked correctly
|
||||
- Discovered only after customer received output
|
||||
|
||||
**Root cause**: Multiple job creation endpoints (POST /jobs, audio search, file upload, webhook) all needed to apply the default theme, but the logic was duplicated rather than centralized. The webhook endpoint was added later and missed this requirement.
|
||||
|
||||
**Solution**: Defense in depth with two enforcement layers:
|
||||
|
||||
1. **Reject at creation** (JobManager.create_job):
|
||||
```python
|
||||
def create_job(self, job_create: JobCreate) -> Job:
|
||||
if not job_create.theme_id:
|
||||
raise ValueError(
|
||||
"theme_id is required for all jobs. "
|
||||
"Use get_theme_service().get_default_theme_id() to get the default theme."
|
||||
)
|
||||
```
|
||||
|
||||
2. **Safety net at processing** (screens_worker._validate_prerequisites):
|
||||
```python
|
||||
if not job.theme_id:
|
||||
logger.error(
|
||||
f"Job {job.job_id}: CRITICAL - No theme_id configured. "
|
||||
"This job should have been rejected at creation time."
|
||||
)
|
||||
return False # Fail fast before generating assets
|
||||
```
|
||||
|
||||
**Key insight**: Critical requirements should be enforced at the lowest possible level, with fail-fast behavior that prevents partial work. Multiple enforcement points (defense in depth) catch issues that slip through higher layers.
|
||||
|
||||
**Benefits**:
|
||||
- New code paths automatically get validation (via JobManager)
|
||||
- Jobs fail at creation, not after minutes of processing
|
||||
- Safety net catches any edge cases that bypass JobManager
|
||||
- Clear error messages tell developers exactly what's missing
|
||||
|
||||
**Lesson**: When a requirement is truly mandatory (like theme for styled videos), don't rely on each endpoint to remember to enforce it. Centralize validation in the core data layer and add safety nets at processing time.
|
||||
|
||||
### Retry Logic for Transient External Service Failures
|
||||
|
||||
**Problem**: E2E test job (b099c91b) failed during encoding with "Cannot connect to host 136.119.50.148:8080 ssl:default". Investigation showed the GCE encoding worker had restarted (likely during a deployment) at the exact moment the job tried to connect.
|
||||
|
||||
**Symptoms**:
|
||||
- Job failed at encoding stage with connection error
|
||||
- GCE worker was healthy before and after the failure
|
||||
- Worker logs showed restart at the time of failure
|
||||
- Failure was timing-dependent (hit during brief restart window)
|
||||
|
||||
**Root cause**: The GCE encoding worker runs on a VM that can restart during deployments. During the ~10-30 second restart window, HTTP connections fail immediately rather than being retried.
|
||||
|
||||
**Solution**: Add retry logic with exponential backoff for transient failures:
|
||||
|
||||
```python
|
||||
MAX_RETRIES = 3
|
||||
INITIAL_BACKOFF_SECONDS = 2.0
|
||||
MAX_BACKOFF_SECONDS = 10.0
|
||||
|
||||
async def _request_with_retry(
|
||||
self,
|
||||
method: str,
|
||||
url: str,
|
||||
headers: Dict[str, str],
|
||||
json_payload: Optional[Dict[str, Any]] = None,
|
||||
timeout: float = 30.0,
|
||||
job_id: str = "unknown",
|
||||
) -> Dict[str, Any]:
|
||||
last_exception = None
|
||||
backoff = INITIAL_BACKOFF_SECONDS
|
||||
|
||||
for attempt in range(MAX_RETRIES + 1):
|
||||
try:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
# Make request...
|
||||
return {"status": resp.status, "json": ..., "text": ...}
|
||||
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError, asyncio.TimeoutError) as e:
|
||||
last_exception = e
|
||||
if attempt < MAX_RETRIES:
|
||||
logger.warning(f"[job:{job_id}] Connection failed (attempt {attempt + 1}): {e}. Retrying in {backoff:.1f}s...")
|
||||
await asyncio.sleep(backoff)
|
||||
backoff = min(backoff * 2, MAX_BACKOFF_SECONDS)
|
||||
else:
|
||||
logger.error(f"[job:{job_id}] Connection failed after {MAX_RETRIES + 1} attempts: {e}")
|
||||
|
||||
raise last_exception
|
||||
```
|
||||
|
||||
**Key design decisions**:
|
||||
- Retry only on connection-level errors (`ClientConnectorError`, `ServerDisconnectedError`, `TimeoutError`)
|
||||
- Don't retry on HTTP errors (4xx, 5xx) - those indicate real problems
|
||||
- Exponential backoff (2s → 4s → 8s) with cap to avoid excessive delays
|
||||
- Log each retry attempt for debugging
|
||||
|
||||
**Lesson**: Any HTTP call to an external service that might restart (VMs, containers, serverless) should have retry logic for transient connection failures. The total retry time (~14s with 3 retries) should be less than the typical restart window of the service.
|
||||
|
||||
### Cross-Domain localStorage Isolation
|
||||
|
||||
**Problem**: Auth tokens stored in localStorage on one subdomain are invisible to other subdomains.
|
||||
|
||||
+5
-1
@@ -28,7 +28,7 @@
|
||||
| Beta tester program | Working |
|
||||
| Admin dashboard | Working |
|
||||
| CI/CD self-hosted runner | Working (GCP) |
|
||||
| E2E happy path test | Working (38 min full pipeline) |
|
||||
| E2E happy path test | Working (~20-25 min full pipeline) |
|
||||
|
||||
## Known Issues
|
||||
|
||||
@@ -40,6 +40,10 @@
|
||||
|
||||
## Recent Changes
|
||||
|
||||
- **Encoding Worker Infrastructure Upgrade** (2026-01-08): Upgraded GCE encoding worker from c4-standard-8 (Intel) to c4d-highcpu-32 (AMD EPYC 9B45 Turin). Benchmarking showed **4.92x faster encoding** (135s vs 666s total). Key improvements: With Vocals 4K rendering 6x faster (54s vs 324s), 720p downscale 4.6x faster (11s vs 50s). Reduces total encoding time from ~11 min to ~2.3 min per job. See [archive/2026-01-08-performance-investigation.md](archive/2026-01-08-performance-investigation.md) for full benchmark methodology and results.
|
||||
|
||||
- **Theme Enforcement & Encoding Resilience** (2026-01-08): Added defense-in-depth theme enforcement - jobs without theme_id are now rejected at creation (JobManager) with a safety net at processing time (screens_worker). Fixed done-for-you webhook to apply default theme. Added retry logic with exponential backoff (3 retries, 2s→4s→8s) to GCE encoding service for transient connection failures during worker restarts. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#defense-in-depth-enforce-critical-requirements-at-multiple-layers).
|
||||
|
||||
- **Comprehensive Performance Optimization** (2026-01-08): Reduced lyrics processing from **16+ minutes to ~5 minutes** through multiple optimizations. Key changes: (1) NLTK cmudict preloading at startup saves 100-150s, (2) Langfuse callback handler preloading saves 200s, (3) Model warmup in `AgenticCorrector.from_model()` prevents parallel initialization race, (4) Parallel anchor sequence search (4 workers) reduces n-gram processing from 38s to ~10s. Added `/health/preload-status` endpoint for deployment verification. PR #236. See [archive/2026-01-08-performance-investigation.md](archive/2026-01-08-performance-investigation.md) and [LESSONS-LEARNED.md](LESSONS-LEARNED.md#preloading-heavy-resources-at-container-startup).
|
||||
|
||||
- **UI Simplification & Brand Accessibility** (2026-01-08): Simplified the "Create Karaoke Video" form by hiding advanced options (theme settings now admin-only, "Display As" behind toggle). Improved audio search dialog UX by hiding technical tracker names and showing user-friendly availability badges. Fixed brand pink color contrast for accessibility - swapped default/hover values so white text on pink buttons meets WCAG contrast ratio. See [BRAND-STYLE-GUIDE.md](BRAND-STYLE-GUIDE.md) v1.2.
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
# Performance Investigation: Karaoke Generation Pipeline
|
||||
|
||||
**Date**: 2026-01-08
|
||||
**Status**: Phase 1 Complete, Validated in Production
|
||||
**Status**: Phase 2 In Progress - Encoding Infrastructure Benchmarking
|
||||
**Goal**: Reduce total karaoke generation time from ~30 minutes to ~10 minutes
|
||||
|
||||
## Executive Summary
|
||||
|
||||
We achieved a **~50% reduction in lyrics processing time** (from ~13 min to ~6.5 min) through preloading optimizations. However, the overall pipeline still takes ~25-30 minutes. Further optimization is needed to reach the 10-minute target.
|
||||
|
||||
**Phase 2 Focus**: Encoding infrastructure optimization. Benchmarking confirms the current GCE encoding worker (c4-standard-8) is **1.75x slower** than an M3 Max MacBook Pro, validating the need for infrastructure upgrades.
|
||||
|
||||
### Key Achievements (PR #236)
|
||||
|
||||
| Optimization | Before | After | Savings |
|
||||
@@ -252,6 +254,172 @@ curl https://api.nomadkaraoke.com/api/health/preload-status
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Encoding Infrastructure Benchmarking
|
||||
|
||||
### Motivation
|
||||
|
||||
The GCE encoding worker (final encoding stage) currently takes ~9-11 minutes. User hypothesis: the current c4-standard-8 instance is underperforming compared to modern hardware (e.g., M3 MacBook Pro).
|
||||
|
||||
**Important constraint**: GPU encoding (NVENC) is NOT viable because:
|
||||
1. We deliberately use `libx264` for quality
|
||||
2. `libass` subtitle rendering is CPU-only and cannot use GPU
|
||||
3. The heaviest operations (4K ASS overlay) require CPU
|
||||
|
||||
### Benchmark Methodology
|
||||
|
||||
Created `scripts/benchmark_encoding.py` and `scripts/benchmark_encoding_gce.sh` to measure actual encoding operations using the same test data (job `fddad04d` - "piri - dog"):
|
||||
|
||||
**Test files**:
|
||||
- `karaoke.ass` - ASS subtitle file
|
||||
- `vocals.flac` / `instrumental_clean.flac` - Audio stems
|
||||
- `title.mov` / `end.mov` - Title/end screen videos
|
||||
- `background.png` - Nomad theme 4K background
|
||||
- `font.ttf` - AvenirNext-Bold font
|
||||
|
||||
**Benchmark stages** (matching actual production code paths):
|
||||
1. Preview Video (480x270 with ASS overlay) - `LocalPreviewEncodingService`
|
||||
2. With Vocals Video (4K with ASS overlay) - `VideoGenerator.generate_video`
|
||||
3. Remux with Instrumental - `LocalEncodingService.remux_with_instrumental`
|
||||
4. Convert Title/End MOV to MP4 - `LocalEncodingService.convert_mov_to_mp4`
|
||||
5. Lossless 4K Concat - `LocalEncodingService.encode_lossless_mp4`
|
||||
6. Lossy 4K (AAC audio) - `LocalEncodingService.encode_lossy_mp4`
|
||||
7. MKV (FLAC audio) - `LocalEncodingService.encode_lossless_mkv`
|
||||
8. 720p Downscale - `LocalEncodingService.encode_720p`
|
||||
|
||||
### Benchmark Results: Current Infrastructure
|
||||
|
||||
#### System Specifications
|
||||
|
||||
| Spec | M3 Max MacBook Pro | GCE c4-standard-8 |
|
||||
|------|-------------------|-------------------|
|
||||
| CPU | Apple M3 Max | Intel Xeon Platinum 8581C @ 2.30GHz |
|
||||
| Cores | 14 (10P + 4E) | 8 vCPUs (4 physical + HT) |
|
||||
| Memory | 36 GB | 29 GB |
|
||||
| FFmpeg | 8.0.1 (Homebrew) | 7.0.2-static (John Van Sickle) |
|
||||
| Architecture | ARM64 (Apple Silicon) | x86_64 |
|
||||
|
||||
#### Detailed Results
|
||||
|
||||
| Stage | M3 Max | GCE c4-standard-8 | Ratio |
|
||||
|-------|--------|-------------------|-------|
|
||||
| Preview (480x270 ASS) | 50.12s | 110.36s | **2.2x slower** |
|
||||
| **With Vocals (4K ASS)** | 200.71s | 324.16s | **1.6x slower** |
|
||||
| Remux with Instrumental | 0.21s | 0.24s | ~same |
|
||||
| Convert Title MOV→MP4 | 1.87s | 3.58s | 1.9x slower |
|
||||
| Convert End MOV→MP4 | 1.72s | 3.54s | 2.1x slower |
|
||||
| **Lossless 4K Concat** | 90.95s | 164.86s | **1.8x slower** |
|
||||
| Lossy 4K (AAC) | 7.03s | 8.85s | 1.3x slower |
|
||||
| MKV (FLAC) | 0.54s | 0.40s | ~same |
|
||||
| **720p Downscale** | 27.74s | 50.20s | **1.8x slower** |
|
||||
| **TOTAL** | **380.91s (6.3 min)** | **666.19s (11.1 min)** | **1.75x slower** |
|
||||
|
||||
#### Key Findings
|
||||
|
||||
1. **Overall**: GCE c4-standard-8 is **1.75x slower** than M3 Max MacBook Pro
|
||||
|
||||
2. **Heaviest operations** (CPU-bound libx264 + libass):
|
||||
- With Vocals (4K ASS): 324s GCE vs 201s Mac (61% of GCE total)
|
||||
- Lossless 4K Concat: 165s GCE vs 91s Mac (25% of GCE total)
|
||||
- These two operations account for **73%** of total GCE encoding time
|
||||
|
||||
3. **Root causes**:
|
||||
- Apple M3 Max has significantly better single-threaded performance
|
||||
- More CPU cores (14 vs 8)
|
||||
- Better memory bandwidth and cache architecture
|
||||
- libass subtitle rendering is particularly demanding
|
||||
|
||||
### Optimization Opportunities
|
||||
|
||||
Since GPU is NOT an option (libass limitation), focus on:
|
||||
|
||||
1. **More powerful CPU instance types**:
|
||||
- More cores for parallel FFmpeg operations
|
||||
- Higher clock speeds for single-threaded libass rendering
|
||||
- Better memory bandwidth
|
||||
|
||||
2. **FFmpeg optimizations**:
|
||||
- Explicit thread count tuning
|
||||
- Preset adjustments where quality loss is acceptable
|
||||
- Parallel output format encoding
|
||||
|
||||
3. **Alternative machine families**:
|
||||
- c3/c3d (Intel Sapphire Rapids, higher clocks)
|
||||
- c4a (AMD EPYC Genoa, high core count)
|
||||
- n2/n2d (balanced performance/cost)
|
||||
- t2a (Arm-based Ampere Altra, potentially better perf/watt)
|
||||
|
||||
### Next Steps: Infrastructure Testing
|
||||
|
||||
After researching latest GCP compute options (C4, C4A, C4D, C3, C3D series), selected 5 candidates focusing on:
|
||||
- High single-thread performance (critical for libass subtitle rendering)
|
||||
- Good multi-thread scaling (for libx264 encoding)
|
||||
- Latest generation CPUs with highest clock speeds
|
||||
|
||||
#### Selected Candidates
|
||||
|
||||
| # | Instance Type | vCPUs | CPU | Clock Speed | Memory | Hypothesis |
|
||||
|---|--------------|-------|-----|-------------|--------|------------|
|
||||
| **Baseline** | c4-standard-8 | 8 | Intel Emerald Rapids | 2.3/3.9 GHz | 30 GB | Current production |
|
||||
| 1 | **c4d-highcpu-16** | 16 | AMD EPYC Turin (5th gen) | 4.1 GHz turbo | 30 GB | **Newest, fastest CPU** |
|
||||
| 2 | **c4-highcpu-16** | 16 | Intel Granite Rapids (6th gen) | 3.9/4.2 GHz | 32 GB | 2x cores, same vendor |
|
||||
| 3 | **c4-highcpu-32** | 32 | Intel Granite Rapids (6th gen) | 3.9/4.2 GHz | 64 GB | 4x cores, max parallelism |
|
||||
| 4 | **c3d-highcpu-30** | 30 | AMD EPYC Genoa (4th gen) | 3.3 GHz | 59 GB | AMD high core count |
|
||||
| 5 | **c4a-highcpu-16** | 16 | Google Axion (ARM Neoverse V2) | - | 32 GB | ARM architecture test |
|
||||
|
||||
**Rationale**:
|
||||
- **C4D**: Latest AMD Turin with 4.1GHz max boost - likely best single-thread perf
|
||||
- **C4 16/32**: Intel Granite Rapids scaling test - same arch as current, more cores
|
||||
- **C3D**: AMD Genoa known for excellent multi-thread - test FFmpeg scaling
|
||||
- **C4A**: ARM Axion to test if Apple Silicon-like performance translates to GCP ARM
|
||||
|
||||
**Benchmark scripts**:
|
||||
- `scripts/benchmark_encoding_gce.sh` - Shell script for GCE VMs
|
||||
- `scripts/benchmark_candidates.sh` - Orchestrates multi-VM testing
|
||||
|
||||
#### Candidate Test Results
|
||||
|
||||
| Instance Type | CPU | Total Time | vs Baseline | With Vocals (4K) | Lossless Concat | 720p | Status |
|
||||
|--------------|-----|------------|-------------|------------------|-----------------|------|--------|
|
||||
| c4-standard-8 (baseline) | Intel Xeon 8581C | 666.19s | 1.00x | 324.16s | 164.86s | 50.20s | ✅ Complete |
|
||||
| **c4d-highcpu-32** | **AMD EPYC 9B45 (Turin)** | **135.27s** | **4.92x** | **53.89s** | **33.97s** | **10.84s** | ✅ **WINNER** |
|
||||
| c4d-highcpu-16 | AMD EPYC 9B45 (Turin) | 220.00s | 3.03x | 93.73s | 57.99s | 19.94s | ✅ Complete |
|
||||
| c4a-highcpu-16 | Google Axion (ARM) | 248.07s | 2.69x | 114.13s | 59.54s | 19.26s | ✅ Complete |
|
||||
| c4-highcpu-16 | Intel Xeon 8581C | 308.89s | 2.16x | 135.38s | 81.10s | 24.93s | ✅ Complete |
|
||||
| M3 Max MacBook (reference) | Apple M3 Max | 380.91s | 1.75x | 200.71s | 90.95s | 27.74s | ✅ Complete |
|
||||
| c4-highcpu-32 | Intel Xeon 8581C | - | - | - | - | - | ❌ Quota limit |
|
||||
| c3d-highcpu-30 | AMD EPYC Genoa | - | - | - | - | - | ❌ Quota limit |
|
||||
|
||||
#### Key Findings
|
||||
|
||||
1. **c4d-highcpu-32 (AMD EPYC 9B45 Turin) is the clear winner**:
|
||||
- **4.92x faster** than baseline (135s vs 666s)
|
||||
- **6.01x faster** on the heaviest operation (With Vocals 4K ASS: 54s vs 324s)
|
||||
- Even faster than M3 Max MacBook Pro by 2.8x!
|
||||
- Doubling cores 16→32 gave 1.63x additional speedup (220s → 135s)
|
||||
|
||||
2. **Scaling analysis**:
|
||||
- c4d-highcpu-16: 220s (3.03x faster)
|
||||
- c4d-highcpu-32: 135s (4.92x faster)
|
||||
- Near-linear scaling for this workload - FFmpeg efficiently uses all 32 cores
|
||||
|
||||
3. **AMD dominates Intel for this workload**:
|
||||
- c4d-highcpu-16 (AMD): 220s
|
||||
- c4-highcpu-16 (Intel): 309s
|
||||
- AMD is 1.4x faster at same core count
|
||||
|
||||
4. **ARM (Axion) competitive but not optimal**:
|
||||
- c4a-highcpu-16: 248s (2.69x faster)
|
||||
- Good performance but AMD x86 still wins
|
||||
|
||||
#### Recommendation
|
||||
|
||||
**Deploy c4d-highcpu-32 as the new encoding worker**:
|
||||
- Reduces encoding time from ~11 min to ~2.3 min (4.92x faster)
|
||||
- Overall job time reduction: ~9 min saved per job
|
||||
- Cost is justified by GCP free credits and dramatically improved UX
|
||||
|
||||
---
|
||||
|
||||
## Target Timeline to 10-Minute Goal
|
||||
|
||||
| Phase | Optimization | Cumulative Time |
|
||||
|
||||
@@ -8,7 +8,7 @@ including static IP and firewall rules.
|
||||
import pulumi
|
||||
from pulumi_gcp import compute, serviceaccount
|
||||
|
||||
from config import REGION, ZONE, PROJECT_ID, MachineTypes, DiskSizes
|
||||
from config import REGION, ENCODING_WORKER_ZONE, PROJECT_ID, MachineTypes, DiskSizes
|
||||
from .startup_scripts import read_script
|
||||
|
||||
|
||||
@@ -36,7 +36,8 @@ def create_encoding_worker_vm(
|
||||
Create the encoding worker VM instance.
|
||||
|
||||
This VM runs video encoding jobs with high CPU/memory resources.
|
||||
Uses hyperdisk-balanced for fast I/O during encoding.
|
||||
Uses c4d-highcpu-32 (AMD EPYC 9B45 Turin, 32 vCPU) for 4.92x faster
|
||||
encoding vs c4-standard-8. Uses hyperdisk-balanced for fast I/O.
|
||||
|
||||
Uses a custom Packer-built image with Python 3.13, FFmpeg, and fonts
|
||||
pre-installed to reduce startup time from ~10 minutes to ~30 seconds.
|
||||
@@ -60,7 +61,7 @@ def create_encoding_worker_vm(
|
||||
"encoding-worker",
|
||||
name="encoding-worker",
|
||||
machine_type=MachineTypes.ENCODING_WORKER,
|
||||
zone=ZONE,
|
||||
zone=ENCODING_WORKER_ZONE,
|
||||
boot_disk=compute.InstanceBootDiskArgs(
|
||||
initialize_params=compute.InstanceBootDiskInitializeParamsArgs(
|
||||
image=custom_image,
|
||||
|
||||
@@ -33,6 +33,10 @@ def get_project_number() -> str:
|
||||
REGION = "us-central1"
|
||||
ZONE = f"{REGION}-a"
|
||||
|
||||
# Encoding worker zone - uses us-central1-c due to c4d-highcpu-32 availability
|
||||
# (us-central1-a and us-central1-b often lack capacity for high-end C4D instances)
|
||||
ENCODING_WORKER_ZONE = f"{REGION}-c"
|
||||
|
||||
# Pulumi config accessor
|
||||
config = pulumi.Config()
|
||||
|
||||
@@ -41,7 +45,7 @@ class MachineTypes:
|
||||
"""Machine type configurations for GCE instances."""
|
||||
|
||||
GITHUB_RUNNER = "e2-standard-4" # 4 vCPU, 16GB RAM
|
||||
ENCODING_WORKER = "c4-standard-8" # 8 vCPU, Intel Granite Rapids 3.9 GHz
|
||||
ENCODING_WORKER = "c4d-highcpu-32" # 32 vCPU, AMD EPYC 9B45 Turin - 4.92x faster than c4-standard-8
|
||||
FLACFETCH = "e2-small" # 0.5 vCPU, 2GB RAM
|
||||
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.99.0"
|
||||
version = "0.99.2"
|
||||
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"
|
||||
|
||||
Executable
+245
@@ -0,0 +1,245 @@
|
||||
#!/bin/bash
|
||||
# Benchmark Candidate GCE Instance Types
|
||||
#
|
||||
# This script creates temporary VMs with different instance types,
|
||||
# runs the encoding benchmark on each, and collects results.
|
||||
#
|
||||
# Usage:
|
||||
# ./scripts/benchmark_candidates.sh [candidate_number]
|
||||
#
|
||||
# # Run specific candidate (1-5)
|
||||
# ./scripts/benchmark_candidates.sh 1
|
||||
#
|
||||
# # Run all candidates
|
||||
# ./scripts/benchmark_candidates.sh all
|
||||
|
||||
set -e
|
||||
|
||||
PROJECT="nomadkaraoke"
|
||||
ZONE="us-central1-a"
|
||||
BENCHMARK_SCRIPT="benchmark_encoding_gce.sh"
|
||||
RESULTS_DIR="benchmark_results"
|
||||
|
||||
# Candidate configurations
|
||||
# Format: "name:machine_type"
|
||||
CANDIDATES=(
|
||||
"c4d-highcpu-16:c4d-highcpu-16"
|
||||
"c4-highcpu-16:c4-highcpu-16"
|
||||
"c4-highcpu-32:c4-highcpu-32"
|
||||
"c3d-highcpu-30:c3d-highcpu-30"
|
||||
"c4a-highcpu-16:c4a-highcpu-16"
|
||||
"c4d-highcpu-32:c4d-highcpu-32"
|
||||
)
|
||||
|
||||
# Create results directory
|
||||
mkdir -p "$RESULTS_DIR"
|
||||
|
||||
# Function to create a benchmark VM
|
||||
create_vm() {
|
||||
local name=$1
|
||||
local machine_type=$2
|
||||
local vm_name="benchmark-${name}"
|
||||
|
||||
echo "Creating VM: $vm_name ($machine_type)..."
|
||||
|
||||
# Determine disk type based on machine type
|
||||
# C4, C4D, C4A all require hyperdisk-balanced
|
||||
local disk_type="pd-balanced"
|
||||
if [[ "$machine_type" == c4* ]]; then
|
||||
disk_type="hyperdisk-balanced"
|
||||
fi
|
||||
|
||||
# Check if ARM (c4a) - needs different image
|
||||
if [[ "$machine_type" == c4a* ]]; then
|
||||
# ARM-based instance needs ARM image
|
||||
gcloud compute instances create "$vm_name" \
|
||||
--project="$PROJECT" \
|
||||
--zone="$ZONE" \
|
||||
--machine-type="$machine_type" \
|
||||
--image-family="debian-12-arm64" \
|
||||
--image-project="debian-cloud" \
|
||||
--boot-disk-size="100GB" \
|
||||
--boot-disk-type="$disk_type" \
|
||||
--scopes="storage-ro" \
|
||||
--metadata="startup-script=apt-get update && apt-get install -y python3 wget && wget -q https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-arm64-static.tar.xz -O /tmp/ffmpeg.tar.xz && tar -xf /tmp/ffmpeg.tar.xz -C /tmp && cp /tmp/ffmpeg-*-arm64-static/ffmpeg /usr/local/bin/ && cp /tmp/ffmpeg-*-arm64-static/ffprobe /usr/local/bin/"
|
||||
else
|
||||
# x86 instance
|
||||
gcloud compute instances create "$vm_name" \
|
||||
--project="$PROJECT" \
|
||||
--zone="$ZONE" \
|
||||
--machine-type="$machine_type" \
|
||||
--image-family="debian-12" \
|
||||
--image-project="debian-cloud" \
|
||||
--boot-disk-size="100GB" \
|
||||
--boot-disk-type="$disk_type" \
|
||||
--scopes="storage-ro" \
|
||||
--metadata="startup-script=apt-get update && apt-get install -y python3 wget && wget -q 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/"
|
||||
fi
|
||||
|
||||
echo "Waiting for VM to be ready..."
|
||||
sleep 30
|
||||
|
||||
# Wait for FFmpeg to be installed
|
||||
local max_attempts=20
|
||||
local attempt=0
|
||||
while ! gcloud compute ssh "$vm_name" --zone="$ZONE" --project="$PROJECT" --command="which ffmpeg" &>/dev/null; do
|
||||
attempt=$((attempt + 1))
|
||||
if [ $attempt -ge $max_attempts ]; then
|
||||
echo "ERROR: FFmpeg not ready after $max_attempts attempts"
|
||||
return 1
|
||||
fi
|
||||
echo " Waiting for FFmpeg installation... (attempt $attempt/$max_attempts)"
|
||||
sleep 15
|
||||
done
|
||||
|
||||
echo "VM ready: $vm_name"
|
||||
}
|
||||
|
||||
# Function to run benchmark on a VM
|
||||
run_benchmark() {
|
||||
local name=$1
|
||||
local vm_name="benchmark-${name}"
|
||||
local result_file="$RESULTS_DIR/${name}_results.txt"
|
||||
|
||||
echo ""
|
||||
echo "============================================================"
|
||||
echo "Running benchmark on: $vm_name"
|
||||
echo "============================================================"
|
||||
|
||||
# Copy benchmark script to VM
|
||||
gcloud compute scp "scripts/$BENCHMARK_SCRIPT" "${vm_name}:/tmp/" \
|
||||
--zone="$ZONE" --project="$PROJECT"
|
||||
|
||||
# Run benchmark and capture output
|
||||
gcloud compute ssh "$vm_name" --zone="$ZONE" --project="$PROJECT" \
|
||||
--command="bash /tmp/$BENCHMARK_SCRIPT" | tee "$result_file"
|
||||
|
||||
echo ""
|
||||
echo "Results saved to: $result_file"
|
||||
}
|
||||
|
||||
# Function to delete a VM
|
||||
delete_vm() {
|
||||
local name=$1
|
||||
local vm_name="benchmark-${name}"
|
||||
|
||||
echo "Deleting VM: $vm_name..."
|
||||
gcloud compute instances delete "$vm_name" \
|
||||
--zone="$ZONE" --project="$PROJECT" --quiet || true
|
||||
}
|
||||
|
||||
# Function to run a single candidate
|
||||
run_candidate() {
|
||||
local index=$1
|
||||
local candidate="${CANDIDATES[$index]}"
|
||||
local name="${candidate%%:*}"
|
||||
local machine_type="${candidate##*:}"
|
||||
|
||||
echo ""
|
||||
echo "########################################################"
|
||||
echo "# Candidate $((index + 1)): $name ($machine_type)"
|
||||
echo "########################################################"
|
||||
|
||||
# Create VM
|
||||
if ! create_vm "$name" "$machine_type"; then
|
||||
echo "ERROR: Failed to create VM for $name"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Run benchmark
|
||||
if ! run_benchmark "$name"; then
|
||||
echo "ERROR: Benchmark failed for $name"
|
||||
delete_vm "$name"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Delete VM
|
||||
delete_vm "$name"
|
||||
|
||||
echo ""
|
||||
echo "Candidate $name completed successfully!"
|
||||
}
|
||||
|
||||
# Function to parse results and create summary
|
||||
create_summary() {
|
||||
echo ""
|
||||
echo "============================================================"
|
||||
echo "BENCHMARK SUMMARY"
|
||||
echo "============================================================"
|
||||
echo ""
|
||||
echo "Instance Type | Total Time | vs Baseline | With Vocals | Concat | 720p"
|
||||
echo "------------------------|------------|-------------|-------------|--------|------"
|
||||
|
||||
# Baseline (from existing encoding-worker)
|
||||
echo "c4-standard-8 (baseline)| 666.19s | 1.00x | 324.16s | 164.86s| 50.20s"
|
||||
|
||||
# Parse each result file
|
||||
for candidate in "${CANDIDATES[@]}"; do
|
||||
local name="${candidate%%:*}"
|
||||
local result_file="$RESULTS_DIR/${name}_results.txt"
|
||||
|
||||
if [ -f "$result_file" ]; then
|
||||
# Extract total time
|
||||
local total=$(grep "TOTAL" "$result_file" | awk '{print $NF}' | tr -d 's')
|
||||
# Extract individual stage times
|
||||
local with_vocals=$(grep "Stage 2:" "$result_file" | awk -F'|' '{print $2}' | tr -d 's ' 2>/dev/null || echo "-")
|
||||
local concat=$(grep "Stage 5:" "$result_file" | awk -F'|' '{print $2}' | tr -d 's ' 2>/dev/null || echo "-")
|
||||
local p720=$(grep "Stage 8:" "$result_file" | awk -F'|' '{print $2}' | tr -d 's ' 2>/dev/null || echo "-")
|
||||
|
||||
if [ -n "$total" ]; then
|
||||
local ratio=$(python3 -c "print(f'{666.19 / float(\"$total\"):.2f}x')" 2>/dev/null || echo "-")
|
||||
printf "%-24s|%11ss |%12s |%12ss |%7ss|%6ss\n" "$name" "$total" "$ratio" "$with_vocals" "$concat" "$p720"
|
||||
else
|
||||
printf "%-24s| - | - | - | - | -\n" "$name"
|
||||
fi
|
||||
else
|
||||
printf "%-24s| - | - | - | - | - (no results)\n" "$name"
|
||||
fi
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "Results saved to: $RESULTS_DIR/"
|
||||
}
|
||||
|
||||
# Main
|
||||
main() {
|
||||
local target="${1:-help}"
|
||||
|
||||
case "$target" in
|
||||
1|2|3|4|5|6)
|
||||
run_candidate $((target - 1))
|
||||
;;
|
||||
all)
|
||||
echo "Running all 5 candidates..."
|
||||
for i in {0..4}; do
|
||||
run_candidate $i
|
||||
done
|
||||
create_summary
|
||||
;;
|
||||
summary)
|
||||
create_summary
|
||||
;;
|
||||
help|*)
|
||||
echo "Usage: $0 [candidate_number|all|summary]"
|
||||
echo ""
|
||||
echo "Candidates:"
|
||||
for i in "${!CANDIDATES[@]}"; do
|
||||
local candidate="${CANDIDATES[$i]}"
|
||||
local name="${candidate%%:*}"
|
||||
local machine_type="${candidate##*:}"
|
||||
echo " $((i + 1)): $name ($machine_type)"
|
||||
done
|
||||
echo ""
|
||||
echo "Commands:"
|
||||
echo " 1-5 Run specific candidate"
|
||||
echo " all Run all candidates sequentially"
|
||||
echo " summary Show results summary"
|
||||
echo ""
|
||||
echo "Example:"
|
||||
echo " $0 1 # Run c4d-highcpu-16"
|
||||
echo " $0 all # Run all candidates"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
main "$@"
|
||||
@@ -0,0 +1,554 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Encoding Performance Benchmark Script
|
||||
|
||||
This script benchmarks the actual encoding operations used in karaoke generation
|
||||
by importing and using the real code paths from LyricsTranscriber and karaoke-gen.
|
||||
|
||||
Usage:
|
||||
# Download test files and run benchmark locally
|
||||
python scripts/benchmark_encoding.py --download --run
|
||||
|
||||
# Run benchmark on already-downloaded files
|
||||
python scripts/benchmark_encoding.py --run
|
||||
|
||||
Test data source:
|
||||
Job fddad04d (piri - dog) from GCS
|
||||
|
||||
Benchmark stages (using actual code):
|
||||
1. Preview video (480x270 with ASS) - LocalPreviewEncodingService
|
||||
2. Full "With Vocals" video (4K with ASS) - LyricsTranscriber VideoGenerator
|
||||
3. Remux with instrumental - LocalEncodingService
|
||||
4. Lossless 4K concat (title + karaoke + end) - LocalEncodingService
|
||||
5. Lossy 4K (AAC audio) - LocalEncodingService
|
||||
6. MKV (FLAC audio) - LocalEncodingService
|
||||
7. 720p downscale - LocalEncodingService
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
# Add project root to path for imports
|
||||
PROJECT_ROOT = Path(__file__).parent.parent
|
||||
sys.path.insert(0, str(PROJECT_ROOT))
|
||||
|
||||
# Test job ID (piri - dog)
|
||||
TEST_JOB_ID = "fddad04d"
|
||||
GCS_BUCKET = "karaoke-gen-storage-nomadkaraoke"
|
||||
GCS_JOB_PATH = f"gs://{GCS_BUCKET}/jobs/{TEST_JOB_ID}"
|
||||
GCS_THEME_PATH = f"gs://{GCS_BUCKET}/themes/nomad/assets"
|
||||
|
||||
# Local benchmark directory
|
||||
BENCHMARK_DIR = Path("benchmark_data")
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class BenchmarkResult:
|
||||
"""Result of a single benchmark operation."""
|
||||
name: str
|
||||
duration_seconds: float
|
||||
success: bool
|
||||
output_size_mb: float = 0.0
|
||||
error: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class SystemInfo:
|
||||
"""System information for the benchmark."""
|
||||
platform: str
|
||||
platform_version: str
|
||||
cpu_model: str
|
||||
cpu_count: int
|
||||
memory_gb: float
|
||||
ffmpeg_version: str
|
||||
hostname: str
|
||||
|
||||
|
||||
def get_system_info() -> SystemInfo:
|
||||
"""Collect system information."""
|
||||
cpu_model = "Unknown"
|
||||
if platform.system() == "Darwin":
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["sysctl", "-n", "machdep.cpu.brand_string"],
|
||||
capture_output=True, text=True
|
||||
)
|
||||
cpu_model = result.stdout.strip()
|
||||
except Exception:
|
||||
pass
|
||||
elif platform.system() == "Linux":
|
||||
try:
|
||||
with open("/proc/cpuinfo") as f:
|
||||
for line in f:
|
||||
if line.startswith("model name"):
|
||||
cpu_model = line.split(":")[1].strip()
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
memory_gb = 0.0
|
||||
if platform.system() == "Darwin":
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["sysctl", "-n", "hw.memsize"],
|
||||
capture_output=True, text=True
|
||||
)
|
||||
memory_gb = int(result.stdout.strip()) / (1024**3)
|
||||
except Exception:
|
||||
pass
|
||||
elif platform.system() == "Linux":
|
||||
try:
|
||||
with open("/proc/meminfo") as f:
|
||||
for line in f:
|
||||
if line.startswith("MemTotal"):
|
||||
mem_kb = int(line.split()[1])
|
||||
memory_gb = mem_kb / (1024**2)
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ffmpeg_version = "Unknown"
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["ffmpeg", "-version"],
|
||||
capture_output=True, text=True
|
||||
)
|
||||
ffmpeg_version = result.stdout.split("\n")[0]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
hostname = platform.node()
|
||||
|
||||
return SystemInfo(
|
||||
platform=platform.system(),
|
||||
platform_version=platform.release(),
|
||||
cpu_model=cpu_model,
|
||||
cpu_count=os.cpu_count() or 0,
|
||||
memory_gb=round(memory_gb, 1),
|
||||
ffmpeg_version=ffmpeg_version,
|
||||
hostname=hostname,
|
||||
)
|
||||
|
||||
|
||||
def download_test_files(benchmark_dir: Path) -> bool:
|
||||
"""Download test files from GCS."""
|
||||
print(f"\n{'='*60}")
|
||||
print("Downloading test files from GCS...")
|
||||
print(f"{'='*60}")
|
||||
|
||||
benchmark_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
files_to_download = [
|
||||
# Lyrics/subtitles
|
||||
(f"{GCS_JOB_PATH}/lyrics/karaoke.ass", benchmark_dir / "karaoke.ass"),
|
||||
# Screens
|
||||
(f"{GCS_JOB_PATH}/screens/title.mov", benchmark_dir / "title.mov"),
|
||||
(f"{GCS_JOB_PATH}/screens/end.mov", benchmark_dir / "end.mov"),
|
||||
# Audio
|
||||
(f"{GCS_JOB_PATH}/stems/instrumental_clean.flac", benchmark_dir / "instrumental_clean.flac"),
|
||||
(f"{GCS_JOB_PATH}/stems/vocals_clean.flac", benchmark_dir / "vocals.flac"),
|
||||
# Theme assets
|
||||
(f"{GCS_THEME_PATH}/karaoke-background-image-nomad-4k.png", benchmark_dir / "background.png"),
|
||||
(f"{GCS_THEME_PATH}/AvenirNext-Bold.ttf", benchmark_dir / "font.ttf"),
|
||||
]
|
||||
|
||||
for gcs_path, local_path in files_to_download:
|
||||
if local_path.exists():
|
||||
print(f" [cached] {local_path.name}")
|
||||
continue
|
||||
|
||||
print(f" Downloading {local_path.name}...")
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["gsutil", "-q", "cp", gcs_path, str(local_path)],
|
||||
capture_output=True, text=True, timeout=300
|
||||
)
|
||||
if result.returncode != 0:
|
||||
print(f" ERROR: {result.stderr}")
|
||||
return False
|
||||
except subprocess.TimeoutExpired:
|
||||
print(f" ERROR: Download timed out")
|
||||
return False
|
||||
|
||||
print(" All files downloaded successfully.")
|
||||
return True
|
||||
|
||||
|
||||
def time_operation(func, name: str) -> BenchmarkResult:
|
||||
"""Time a function and return a BenchmarkResult."""
|
||||
print(f"\n Running: {name}")
|
||||
start_time = time.perf_counter()
|
||||
|
||||
try:
|
||||
result = func()
|
||||
duration = time.perf_counter() - start_time
|
||||
|
||||
# Get output size if result is a path
|
||||
output_size_mb = 0.0
|
||||
if isinstance(result, (str, Path)):
|
||||
result_path = Path(result)
|
||||
if result_path.exists():
|
||||
output_size_mb = result_path.stat().st_size / (1024 * 1024)
|
||||
|
||||
print(f" Duration: {duration:.2f}s, Output: {output_size_mb:.1f}MB")
|
||||
return BenchmarkResult(
|
||||
name=name,
|
||||
duration_seconds=duration,
|
||||
success=True,
|
||||
output_size_mb=output_size_mb,
|
||||
)
|
||||
except Exception as e:
|
||||
duration = time.perf_counter() - start_time
|
||||
print(f" FAILED: {e}")
|
||||
return BenchmarkResult(
|
||||
name=name,
|
||||
duration_seconds=duration,
|
||||
success=False,
|
||||
error=str(e),
|
||||
)
|
||||
|
||||
|
||||
def run_benchmarks(benchmark_dir: Path, output_dir: Path) -> List[BenchmarkResult]:
|
||||
"""Run all encoding benchmarks using actual code paths."""
|
||||
from backend.services.local_encoding_service import LocalEncodingService, EncodingConfig
|
||||
from backend.services.local_preview_encoding_service import (
|
||||
LocalPreviewEncodingService, PreviewEncodingConfig
|
||||
)
|
||||
from lyrics_transcriber_temp.lyrics_transcriber.output.video import VideoGenerator
|
||||
|
||||
results = []
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
cache_dir = output_dir / "cache"
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Input files
|
||||
ass_file = str(benchmark_dir / "karaoke.ass")
|
||||
vocals_audio = str(benchmark_dir / "vocals.flac")
|
||||
instrumental_audio = str(benchmark_dir / "instrumental_clean.flac")
|
||||
title_mov = str(benchmark_dir / "title.mov")
|
||||
end_mov = str(benchmark_dir / "end.mov")
|
||||
background_image = str(benchmark_dir / "background.png")
|
||||
font_file = str(benchmark_dir / "font.ttf")
|
||||
|
||||
# Verify input files exist
|
||||
required_files = [ass_file, vocals_audio, instrumental_audio, title_mov, end_mov, background_image]
|
||||
for f in required_files:
|
||||
if not Path(f).exists():
|
||||
print(f"ERROR: Missing required file: {f}")
|
||||
return results
|
||||
|
||||
print(f"\n{'='*60}")
|
||||
print("Running Encoding Benchmarks (using actual code paths)")
|
||||
print(f"{'='*60}")
|
||||
|
||||
# ============================================================
|
||||
# Stage 1: Preview video (480x270 with ASS overlay)
|
||||
# Uses: LocalPreviewEncodingService
|
||||
# ============================================================
|
||||
preview_output = str(output_dir / "preview.mp4")
|
||||
preview_service = LocalPreviewEncodingService(logger=logger)
|
||||
preview_config = PreviewEncodingConfig(
|
||||
ass_path=ass_file,
|
||||
audio_path=vocals_audio,
|
||||
output_path=preview_output,
|
||||
background_image_path=background_image,
|
||||
background_color="black",
|
||||
font_path=font_file,
|
||||
)
|
||||
|
||||
def run_preview():
|
||||
result = preview_service.encode_preview(preview_config)
|
||||
if not result.success:
|
||||
raise RuntimeError(result.error)
|
||||
return result.output_path
|
||||
|
||||
results.append(time_operation(run_preview, "Stage 1: Preview Video (480x270 ASS)"))
|
||||
|
||||
# ============================================================
|
||||
# Stage 2: Full "With Vocals" video (4K with ASS overlay)
|
||||
# Uses: LyricsTranscriber VideoGenerator._build_ffmpeg_command
|
||||
# This is the HEAVIEST operation - full 4K render with libass
|
||||
# ============================================================
|
||||
with_vocals_output = str(output_dir / "with_vocals.mkv")
|
||||
|
||||
# Create VideoGenerator with realistic styles config
|
||||
styles = {
|
||||
"karaoke": {
|
||||
"background_image": background_image,
|
||||
"background_color": "black",
|
||||
"font_path": font_file,
|
||||
}
|
||||
}
|
||||
video_gen = VideoGenerator(
|
||||
output_dir=str(output_dir),
|
||||
cache_dir=str(cache_dir),
|
||||
video_resolution=(3840, 2160), # 4K
|
||||
styles=styles,
|
||||
logger=logger,
|
||||
)
|
||||
|
||||
def run_with_vocals():
|
||||
# Use the actual generate_video method
|
||||
return video_gen.generate_video(ass_file, vocals_audio, "benchmark")
|
||||
|
||||
results.append(time_operation(run_with_vocals, "Stage 2: With Vocals Video (4K ASS) - HEAVIEST"))
|
||||
|
||||
# Get the actual output path from VideoGenerator
|
||||
with_vocals_actual = str(output_dir / "benchmark (With Vocals).mkv")
|
||||
if not Path(with_vocals_actual).exists():
|
||||
print(f" ERROR: With Vocals video not generated at {with_vocals_actual}")
|
||||
# Try to find it
|
||||
for f in output_dir.glob("*.mkv"):
|
||||
print(f" Found: {f}")
|
||||
with_vocals_actual = str(f)
|
||||
break
|
||||
|
||||
# ============================================================
|
||||
# Stage 3: Remux with instrumental audio
|
||||
# Uses: LocalEncodingService.remux_with_instrumental
|
||||
# ============================================================
|
||||
karaoke_mp4 = str(output_dir / "karaoke.mp4")
|
||||
encoding_service = LocalEncodingService(logger=logger)
|
||||
|
||||
def run_remux():
|
||||
success = encoding_service.remux_with_instrumental(
|
||||
with_vocals_actual,
|
||||
instrumental_audio,
|
||||
karaoke_mp4,
|
||||
)
|
||||
if not success:
|
||||
raise RuntimeError("Remux failed")
|
||||
return karaoke_mp4
|
||||
|
||||
results.append(time_operation(run_remux, "Stage 3: Remux with Instrumental"))
|
||||
|
||||
# ============================================================
|
||||
# Stage 4: Convert title/end MOV to MP4 (needed for concat)
|
||||
# Uses: LocalEncodingService.convert_mov_to_mp4
|
||||
# ============================================================
|
||||
title_mp4 = str(output_dir / "title.mp4")
|
||||
end_mp4 = str(output_dir / "end.mp4")
|
||||
|
||||
def run_title_convert():
|
||||
success = encoding_service.convert_mov_to_mp4(title_mov, title_mp4)
|
||||
if not success:
|
||||
raise RuntimeError("Title convert failed")
|
||||
return title_mp4
|
||||
|
||||
def run_end_convert():
|
||||
success = encoding_service.convert_mov_to_mp4(end_mov, end_mp4)
|
||||
if not success:
|
||||
raise RuntimeError("End convert failed")
|
||||
return end_mp4
|
||||
|
||||
results.append(time_operation(run_title_convert, "Stage 4a: Convert Title MOV to MP4"))
|
||||
results.append(time_operation(run_end_convert, "Stage 4b: Convert End MOV to MP4"))
|
||||
|
||||
# ============================================================
|
||||
# Stage 5: Lossless 4K concatenation (title + karaoke + end)
|
||||
# Uses: LocalEncodingService.encode_lossless_mp4
|
||||
# ============================================================
|
||||
lossless_4k = str(output_dir / "final_lossless_4k.mp4")
|
||||
|
||||
def run_lossless_concat():
|
||||
success = encoding_service.encode_lossless_mp4(
|
||||
title_mp4,
|
||||
karaoke_mp4,
|
||||
lossless_4k,
|
||||
end_mp4,
|
||||
)
|
||||
if not success:
|
||||
raise RuntimeError("Lossless concat failed")
|
||||
return lossless_4k
|
||||
|
||||
results.append(time_operation(run_lossless_concat, "Stage 5: Lossless 4K Concat (title+karaoke+end)"))
|
||||
|
||||
# ============================================================
|
||||
# Stage 6: Lossy 4K with AAC audio
|
||||
# Uses: LocalEncodingService.encode_lossy_mp4
|
||||
# ============================================================
|
||||
lossy_4k = str(output_dir / "final_lossy_4k.mp4")
|
||||
|
||||
def run_lossy():
|
||||
success = encoding_service.encode_lossy_mp4(lossless_4k, lossy_4k)
|
||||
if not success:
|
||||
raise RuntimeError("Lossy 4K failed")
|
||||
return lossy_4k
|
||||
|
||||
if Path(lossless_4k).exists():
|
||||
results.append(time_operation(run_lossy, "Stage 6: Lossy 4K (AAC audio)"))
|
||||
|
||||
# ============================================================
|
||||
# Stage 7: MKV with FLAC audio
|
||||
# Uses: LocalEncodingService.encode_lossless_mkv
|
||||
# ============================================================
|
||||
lossless_mkv = str(output_dir / "final_lossless_4k.mkv")
|
||||
|
||||
def run_mkv():
|
||||
success = encoding_service.encode_lossless_mkv(lossless_4k, lossless_mkv)
|
||||
if not success:
|
||||
raise RuntimeError("MKV failed")
|
||||
return lossless_mkv
|
||||
|
||||
if Path(lossless_4k).exists():
|
||||
results.append(time_operation(run_mkv, "Stage 7: MKV (FLAC audio)"))
|
||||
|
||||
# ============================================================
|
||||
# Stage 8: 720p downscale
|
||||
# Uses: LocalEncodingService.encode_720p
|
||||
# ============================================================
|
||||
lossy_720p = str(output_dir / "final_lossy_720p.mp4")
|
||||
|
||||
def run_720p():
|
||||
success = encoding_service.encode_720p(lossless_4k, lossy_720p)
|
||||
if not success:
|
||||
raise RuntimeError("720p failed")
|
||||
return lossy_720p
|
||||
|
||||
if Path(lossless_4k).exists():
|
||||
results.append(time_operation(run_720p, "Stage 8: 720p Downscale"))
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def print_results(system_info: SystemInfo, results: List[BenchmarkResult]):
|
||||
"""Print benchmark results."""
|
||||
print(f"\n{'='*60}")
|
||||
print("BENCHMARK RESULTS")
|
||||
print(f"{'='*60}")
|
||||
|
||||
print(f"\nSystem Information:")
|
||||
print(f" Hostname: {system_info.hostname}")
|
||||
print(f" Platform: {system_info.platform} {system_info.platform_version}")
|
||||
print(f" CPU: {system_info.cpu_model}")
|
||||
print(f" CPU Count: {system_info.cpu_count}")
|
||||
print(f" Memory: {system_info.memory_gb} GB")
|
||||
print(f" FFmpeg: {system_info.ffmpeg_version}")
|
||||
|
||||
print(f"\nResults:")
|
||||
print(f"{'Operation':<55} {'Duration':>10} {'Size':>10} {'Status':>10}")
|
||||
print("-" * 85)
|
||||
|
||||
total_time = 0.0
|
||||
for r in results:
|
||||
status = "OK" if r.success else "FAILED"
|
||||
duration_str = f"{r.duration_seconds:.2f}s"
|
||||
size_str = f"{r.output_size_mb:.1f}MB" if r.output_size_mb > 0 else "-"
|
||||
print(f"{r.name:<55} {duration_str:>10} {size_str:>10} {status:>10}")
|
||||
if r.success:
|
||||
total_time += r.duration_seconds
|
||||
if not r.success and r.error:
|
||||
print(f" Error: {r.error[:80]}")
|
||||
|
||||
print("-" * 85)
|
||||
print(f"{'TOTAL (successful operations)':<55} {total_time:.2f}s")
|
||||
|
||||
# Calculate key metrics
|
||||
with_vocals = next((r for r in results if "With Vocals" in r.name), None)
|
||||
lossless_concat = next((r for r in results if "Lossless 4K Concat" in r.name), None)
|
||||
downscale_720p = next((r for r in results if "720p Downscale" in r.name), None)
|
||||
|
||||
print(f"\nKey Metrics:")
|
||||
if with_vocals and with_vocals.success:
|
||||
print(f" With Vocals (4K ASS render): {with_vocals.duration_seconds:.2f}s <- HEAVIEST OPERATION")
|
||||
if lossless_concat and lossless_concat.success:
|
||||
print(f" Lossless 4K concatenation: {lossless_concat.duration_seconds:.2f}s")
|
||||
if downscale_720p and downscale_720p.success:
|
||||
print(f" 720p downscale: {downscale_720p.duration_seconds:.2f}s")
|
||||
|
||||
|
||||
def save_results(system_info: SystemInfo, results: List[BenchmarkResult], output_path: Path):
|
||||
"""Save results to JSON file."""
|
||||
data = {
|
||||
"system": {
|
||||
"hostname": system_info.hostname,
|
||||
"platform": system_info.platform,
|
||||
"platform_version": system_info.platform_version,
|
||||
"cpu_model": system_info.cpu_model,
|
||||
"cpu_count": system_info.cpu_count,
|
||||
"memory_gb": system_info.memory_gb,
|
||||
"ffmpeg_version": system_info.ffmpeg_version,
|
||||
},
|
||||
"results": [
|
||||
{
|
||||
"name": r.name,
|
||||
"duration_seconds": r.duration_seconds,
|
||||
"success": r.success,
|
||||
"output_size_mb": r.output_size_mb,
|
||||
"error": r.error,
|
||||
}
|
||||
for r in results
|
||||
],
|
||||
"total_time": sum(r.duration_seconds for r in results if r.success),
|
||||
}
|
||||
|
||||
with open(output_path, "w") as f:
|
||||
json.dump(data, f, indent=2)
|
||||
print(f"\nResults saved to: {output_path}")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Encoding Performance Benchmark")
|
||||
parser.add_argument("--download", action="store_true", help="Download test files from GCS")
|
||||
parser.add_argument("--run", action="store_true", help="Run benchmarks locally")
|
||||
parser.add_argument("--output", type=str, default="benchmark_results.json", help="Output JSON file")
|
||||
parser.add_argument("--data-dir", type=str, default="benchmark_data", help="Directory for test data")
|
||||
parser.add_argument("--output-dir", type=str, default=None, help="Directory for output files (default: temp)")
|
||||
args = parser.parse_args()
|
||||
|
||||
benchmark_dir = Path(args.data_dir)
|
||||
|
||||
if not any([args.download, args.run]):
|
||||
parser.print_help()
|
||||
print("\nExample usage:")
|
||||
print(" python scripts/benchmark_encoding.py --download --run")
|
||||
sys.exit(1)
|
||||
|
||||
if args.download:
|
||||
if not download_test_files(benchmark_dir):
|
||||
print("ERROR: Failed to download test files")
|
||||
sys.exit(1)
|
||||
|
||||
if args.run:
|
||||
# Check for required files
|
||||
required = ["karaoke.ass", "title.mov", "end.mov", "instrumental_clean.flac", "vocals.flac", "background.png"]
|
||||
missing = [f for f in required if not (benchmark_dir / f).exists()]
|
||||
if missing:
|
||||
print(f"ERROR: Missing files: {missing}")
|
||||
print("Run with --download first")
|
||||
sys.exit(1)
|
||||
|
||||
system_info = get_system_info()
|
||||
|
||||
# Use temp directory or specified output directory
|
||||
if args.output_dir:
|
||||
output_dir = Path(args.output_dir)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
results = run_benchmarks(benchmark_dir, output_dir)
|
||||
print_results(system_info, results)
|
||||
save_results(system_info, results, Path(args.output))
|
||||
else:
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
output_dir = Path(tmpdir)
|
||||
results = run_benchmarks(benchmark_dir, output_dir)
|
||||
print_results(system_info, results)
|
||||
save_results(system_info, results, Path(args.output))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+203
@@ -0,0 +1,203 @@
|
||||
#!/bin/bash
|
||||
# GCE Encoding Benchmark Script
|
||||
# Run on the encoding-worker VM to benchmark FFmpeg encoding performance
|
||||
#
|
||||
# Usage:
|
||||
# gcloud compute scp scripts/benchmark_encoding_gce.sh encoding-worker:/tmp/ --zone=us-central1-a --project=nomadkaraoke
|
||||
# gcloud compute ssh encoding-worker --zone=us-central1-a --project=nomadkaraoke --command="bash /tmp/benchmark_encoding_gce.sh"
|
||||
|
||||
set -e
|
||||
|
||||
echo "============================================================"
|
||||
echo "GCE Encoding Performance Benchmark"
|
||||
echo "============================================================"
|
||||
|
||||
# System info
|
||||
echo ""
|
||||
echo "System Information:"
|
||||
echo " Hostname: $(hostname)"
|
||||
echo " Platform: $(uname -s) $(uname -r)"
|
||||
echo " CPU: $(grep 'model name' /proc/cpuinfo | head -1 | cut -d: -f2 | xargs)"
|
||||
echo " CPU Count: $(nproc)"
|
||||
echo " Memory: $(free -h | grep Mem | awk '{print $2}')"
|
||||
echo " FFmpeg: $(ffmpeg -version 2>&1 | head -1)"
|
||||
|
||||
# Setup directories
|
||||
BENCHMARK_DIR="/tmp/benchmark_data"
|
||||
OUTPUT_DIR="/tmp/benchmark_output"
|
||||
GCS_BUCKET="karaoke-gen-storage-nomadkaraoke"
|
||||
TEST_JOB_ID="fddad04d"
|
||||
|
||||
mkdir -p "$BENCHMARK_DIR" "$OUTPUT_DIR"
|
||||
rm -rf "$OUTPUT_DIR"/*
|
||||
|
||||
# Download test files
|
||||
echo ""
|
||||
echo "============================================================"
|
||||
echo "Downloading test files from GCS..."
|
||||
echo "============================================================"
|
||||
|
||||
download_if_missing() {
|
||||
local gcs_path=$1
|
||||
local local_path=$2
|
||||
if [ -f "$local_path" ]; then
|
||||
echo " [cached] $(basename $local_path)"
|
||||
else
|
||||
echo " Downloading $(basename $local_path)..."
|
||||
gsutil -q cp "$gcs_path" "$local_path"
|
||||
fi
|
||||
}
|
||||
|
||||
download_if_missing "gs://$GCS_BUCKET/jobs/$TEST_JOB_ID/lyrics/karaoke.ass" "$BENCHMARK_DIR/karaoke.ass"
|
||||
download_if_missing "gs://$GCS_BUCKET/jobs/$TEST_JOB_ID/screens/title.mov" "$BENCHMARK_DIR/title.mov"
|
||||
download_if_missing "gs://$GCS_BUCKET/jobs/$TEST_JOB_ID/screens/end.mov" "$BENCHMARK_DIR/end.mov"
|
||||
download_if_missing "gs://$GCS_BUCKET/jobs/$TEST_JOB_ID/stems/instrumental_clean.flac" "$BENCHMARK_DIR/instrumental_clean.flac"
|
||||
download_if_missing "gs://$GCS_BUCKET/jobs/$TEST_JOB_ID/stems/vocals_clean.flac" "$BENCHMARK_DIR/vocals.flac"
|
||||
download_if_missing "gs://$GCS_BUCKET/themes/nomad/assets/karaoke-background-image-nomad-4k.png" "$BENCHMARK_DIR/background.png"
|
||||
download_if_missing "gs://$GCS_BUCKET/themes/nomad/assets/AvenirNext-Bold.ttf" "$BENCHMARK_DIR/font.ttf"
|
||||
|
||||
echo " All files downloaded successfully."
|
||||
|
||||
# Time a command and report results (using python3 for math since bc not available)
|
||||
benchmark() {
|
||||
local name=$1
|
||||
shift
|
||||
echo ""
|
||||
echo " Running: $name"
|
||||
local start=$(date +%s%N)
|
||||
|
||||
if "$@" > /dev/null 2>&1; then
|
||||
local end=$(date +%s%N)
|
||||
local duration=$(python3 -c "print(f'{($end - $start) / 1000000000:.2f}')")
|
||||
local output_file=$(echo "$@" | grep -oP '(?<= )[^ ]+$' || echo "")
|
||||
local size="0"
|
||||
if [ -f "$output_file" ]; then
|
||||
local bytes=$(stat -c%s "$output_file" 2>/dev/null || echo "0")
|
||||
size=$(python3 -c "print(f'{$bytes / 1048576:.1f}')")
|
||||
fi
|
||||
echo " Duration: ${duration}s, Output: ${size}MB - OK"
|
||||
echo "$name|$duration|$size|OK" >> "$OUTPUT_DIR/results.txt"
|
||||
else
|
||||
local end=$(date +%s%N)
|
||||
local duration=$(python3 -c "print(f'{($end - $start) / 1000000000:.2f}')")
|
||||
echo " Duration: ${duration}s - FAILED"
|
||||
echo "$name|$duration|0|FAILED" >> "$OUTPUT_DIR/results.txt"
|
||||
fi
|
||||
}
|
||||
|
||||
echo ""
|
||||
echo "============================================================"
|
||||
echo "Running Encoding Benchmarks"
|
||||
echo "============================================================"
|
||||
|
||||
# Stage 1: Preview Video (480x270 with ASS overlay)
|
||||
# Matches LocalPreviewEncodingService settings
|
||||
benchmark "Stage 1: Preview Video (480x270 ASS)" \
|
||||
ffmpeg -y -hide_banner -loglevel error -r 24 \
|
||||
-loop 1 -i "$BENCHMARK_DIR/background.png" \
|
||||
-i "$BENCHMARK_DIR/vocals.flac" \
|
||||
-vf "scale=480:270:force_original_aspect_ratio=decrease,pad=480:270:(ow-iw)/2:(oh-ih)/2,ass=$BENCHMARK_DIR/karaoke.ass" \
|
||||
-c:a aac -b:a 96k \
|
||||
-c:v libx264 -preset superfast -crf 28 \
|
||||
-pix_fmt yuv420p -movflags +faststart -threads 0 -shortest \
|
||||
"$OUTPUT_DIR/preview.mp4"
|
||||
|
||||
# Stage 2: With Vocals Video (4K with ASS overlay)
|
||||
# This is the HEAVIEST operation - matches VideoGenerator._build_ffmpeg_command
|
||||
benchmark "Stage 2: With Vocals Video (4K ASS) - HEAVIEST" \
|
||||
ffmpeg -y -hide_banner -loglevel error -r 30 \
|
||||
-loop 1 -i "$BENCHMARK_DIR/background.png" \
|
||||
-i "$BENCHMARK_DIR/vocals.flac" \
|
||||
-c:a flac \
|
||||
-vf "scale=3840:2160:force_original_aspect_ratio=decrease,pad=3840:2160:(ow-iw)/2:(oh-ih)/2,ass=$BENCHMARK_DIR/karaoke.ass" \
|
||||
-c:v libx264 -preset fast -b:v 5000k -minrate 5000k -maxrate 20000k -bufsize 10000k \
|
||||
-shortest \
|
||||
"$OUTPUT_DIR/with_vocals.mkv"
|
||||
|
||||
# Stage 3: Remux with Instrumental
|
||||
# Matches LocalEncodingService.remux_with_instrumental
|
||||
benchmark "Stage 3: Remux with Instrumental" \
|
||||
ffmpeg -y -hide_banner -loglevel error \
|
||||
-i "$OUTPUT_DIR/with_vocals.mkv" \
|
||||
-i "$BENCHMARK_DIR/instrumental_clean.flac" \
|
||||
-map 0:v -map 1:a -c copy \
|
||||
-movflags +faststart \
|
||||
"$OUTPUT_DIR/karaoke.mp4"
|
||||
|
||||
# Stage 4a: Convert Title MOV to MP4
|
||||
# Matches LocalEncodingService.convert_mov_to_mp4
|
||||
benchmark "Stage 4a: Convert Title MOV to MP4" \
|
||||
ffmpeg -y -hide_banner -loglevel error \
|
||||
-i "$BENCHMARK_DIR/title.mov" \
|
||||
-c:v libx264 -c:a copy -movflags +faststart \
|
||||
"$OUTPUT_DIR/title.mp4"
|
||||
|
||||
# Stage 4b: Convert End MOV to MP4
|
||||
benchmark "Stage 4b: Convert End MOV to MP4" \
|
||||
ffmpeg -y -hide_banner -loglevel error \
|
||||
-i "$BENCHMARK_DIR/end.mov" \
|
||||
-c:v libx264 -c:a copy -movflags +faststart \
|
||||
"$OUTPUT_DIR/end.mp4"
|
||||
|
||||
# Stage 5: Lossless 4K Concat
|
||||
# Matches LocalEncodingService.encode_lossless_mp4
|
||||
benchmark "Stage 5: Lossless 4K Concat (title+karaoke+end)" \
|
||||
ffmpeg -y -hide_banner -loglevel error \
|
||||
-i "$OUTPUT_DIR/title.mp4" \
|
||||
-i "$OUTPUT_DIR/karaoke.mp4" \
|
||||
-i "$OUTPUT_DIR/end.mp4" \
|
||||
-filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0][2:v:0][2:a:0]concat=n=3:v=1:a=1[outv][outa]" \
|
||||
-map "[outv]" -map "[outa]" \
|
||||
-c:v libx264 -c:a pcm_s16le \
|
||||
-movflags +faststart \
|
||||
"$OUTPUT_DIR/final_lossless_4k.mp4"
|
||||
|
||||
# Stage 6: Lossy 4K
|
||||
# Matches LocalEncodingService.encode_lossy_mp4
|
||||
benchmark "Stage 6: Lossy 4K (AAC audio)" \
|
||||
ffmpeg -y -hide_banner -loglevel error \
|
||||
-i "$OUTPUT_DIR/final_lossless_4k.mp4" \
|
||||
-c:v copy -c:a aac -ar 48000 -b:a 320k \
|
||||
-movflags +faststart \
|
||||
"$OUTPUT_DIR/final_lossy_4k.mp4"
|
||||
|
||||
# Stage 7: MKV with FLAC
|
||||
# Matches LocalEncodingService.encode_lossless_mkv
|
||||
benchmark "Stage 7: MKV (FLAC audio)" \
|
||||
ffmpeg -y -hide_banner -loglevel error \
|
||||
-i "$OUTPUT_DIR/final_lossless_4k.mp4" \
|
||||
-c:v copy -c:a flac \
|
||||
"$OUTPUT_DIR/final_lossless_4k.mkv"
|
||||
|
||||
# Stage 8: 720p Downscale
|
||||
# Matches LocalEncodingService.encode_720p
|
||||
benchmark "Stage 8: 720p Downscale" \
|
||||
ffmpeg -y -hide_banner -loglevel error \
|
||||
-i "$OUTPUT_DIR/final_lossless_4k.mp4" \
|
||||
-c:v libx264 -vf "scale=1280:720" -b:v 2000k -preset medium -tune animation \
|
||||
-c:a aac -ar 48000 -b:a 128k \
|
||||
-movflags +faststart \
|
||||
"$OUTPUT_DIR/final_lossy_720p.mp4"
|
||||
|
||||
# Print results
|
||||
echo ""
|
||||
echo "============================================================"
|
||||
echo "BENCHMARK RESULTS"
|
||||
echo "============================================================"
|
||||
echo ""
|
||||
echo "Operation Duration Size Status"
|
||||
echo "---------------------------------------------------------------------------------"
|
||||
|
||||
total_time="0"
|
||||
while IFS='|' read -r name duration size status; do
|
||||
printf "%-50s %8ss %8sMB %s\n" "$name" "$duration" "$size" "$status"
|
||||
if [ "$status" = "OK" ]; then
|
||||
total_time=$(python3 -c "print(f'{float(\"$total_time\") + float(\"$duration\"):.2f}')")
|
||||
fi
|
||||
done < "$OUTPUT_DIR/results.txt"
|
||||
|
||||
echo "---------------------------------------------------------------------------------"
|
||||
printf "%-50s %8ss\n" "TOTAL (successful operations)" "$total_time"
|
||||
|
||||
echo ""
|
||||
echo "Results saved to: $OUTPUT_DIR/results.txt"
|
||||
Reference in new issue
Block a user