mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-30 17:21:26 +09:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
046ca69a1c | ||
|
|
efb4aa8351 | ||
|
|
d681e26b02 | ||
|
|
2003d4acc8 |
No files matched your search
@@ -1146,6 +1146,7 @@ jobs:
|
||||
|
||||
- name: Wait for service health
|
||||
id: health
|
||||
continue-on-error: true
|
||||
run: |
|
||||
SECONDARY_IP="${{ steps.config.outputs.secondary_ip }}"
|
||||
EXPECTED_VERSION="${{ steps.version_check.outputs.version }}"
|
||||
@@ -1174,6 +1175,7 @@ jobs:
|
||||
- name: Deep health check - real encode test
|
||||
if: steps.health.outputs.healthy == 'true'
|
||||
id: encode-test
|
||||
continue-on-error: true
|
||||
run: |
|
||||
SECONDARY_IP="${{ steps.config.outputs.secondary_ip }}"
|
||||
API_KEY=$(gcloud secrets versions access latest \
|
||||
@@ -1225,7 +1227,7 @@ jobs:
|
||||
exit 1
|
||||
|
||||
- name: Rollback on failure
|
||||
if: failure()
|
||||
if: steps.health.outputs.healthy != 'true' || steps.encode-test.outputs.passed == 'false'
|
||||
run: |
|
||||
SECONDARY_VM="${{ steps.config.outputs.secondary_vm }}"
|
||||
if [ -n "$SECONDARY_VM" ]; then
|
||||
|
||||
@@ -387,3 +387,128 @@ class TestScreensWorkerPrerequisites:
|
||||
|
||||
job = _make_job(state_data={"lyrics_complete": True}, artist="", title="Test")
|
||||
assert _validate_prerequisites(job) is False
|
||||
|
||||
|
||||
# ==================== GCS URI Passthrough ====================
|
||||
|
||||
class TestGCSURIPassthrough:
|
||||
"""
|
||||
Test that Stage 1 uses gcs_uri when input_gcs_uri is set on the processor.
|
||||
Fixes 413 Request Entity Too Large for large FLAC files.
|
||||
"""
|
||||
|
||||
def test_stage1_uses_gcs_uri_when_set(self):
|
||||
"""When input_gcs_uri is set, Stage 1 passes gcs_uri instead of file_path."""
|
||||
from karaoke_gen.audio_processor import AudioProcessor
|
||||
import logging
|
||||
|
||||
processor = AudioProcessor(
|
||||
logger=logging.getLogger("test"),
|
||||
log_level=logging.INFO,
|
||||
log_formatter=None,
|
||||
model_file_dir=None,
|
||||
lossless_output_format="FLAC",
|
||||
clean_instrumental_model="test.ckpt",
|
||||
backing_vocals_models=[],
|
||||
other_stems_models=[],
|
||||
ffmpeg_base_command="ffmpeg",
|
||||
)
|
||||
processor.instrumental_preset = "instrumental_clean"
|
||||
processor.karaoke_preset = None
|
||||
processor.job_id = "gcs-test-001"
|
||||
processor.input_gcs_uri = "gs://karaoke-gen-storage-nomadkaraoke/jobs/gcs-test-001/input/song.flac"
|
||||
|
||||
mock_client = Mock()
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
stems_dir = os.path.join(temp_dir, "stems")
|
||||
os.makedirs(stems_dir)
|
||||
|
||||
for name in ["gcs-test-001_mixed_vocals.flac", "gcs-test-001_mixed_instrumental.flac"]:
|
||||
with open(os.path.join(stems_dir, name), "w") as f:
|
||||
f.write("fake audio")
|
||||
|
||||
mock_client.separate_audio_and_wait.return_value = {
|
||||
"status": "completed",
|
||||
"downloaded_files": [
|
||||
os.path.join(stems_dir, "gcs-test-001_mixed_vocals.flac"),
|
||||
os.path.join(stems_dir, "gcs-test-001_mixed_instrumental.flac"),
|
||||
],
|
||||
"files": {},
|
||||
}
|
||||
|
||||
input_file = os.path.join(temp_dir, "song.flac")
|
||||
with open(input_file, "w") as f:
|
||||
f.write("fake input")
|
||||
|
||||
with patch.object(processor, '_create_stems_directory', return_value=stems_dir):
|
||||
with patch.object(processor, '_normalize_audio_files'):
|
||||
with patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient', return_value=mock_client):
|
||||
processor._process_audio_separation_remote(
|
||||
input_file, "Test - Song", temp_dir, "http://fake-api",
|
||||
)
|
||||
|
||||
# Verify gcs_uri was passed instead of file_path
|
||||
call_kwargs = mock_client.separate_audio_and_wait.call_args[1]
|
||||
assert call_kwargs["gcs_uri"] == "gs://karaoke-gen-storage-nomadkaraoke/jobs/gcs-test-001/input/song.flac"
|
||||
# Verify file_path was NOT passed as a positional arg
|
||||
call_args = mock_client.separate_audio_and_wait.call_args[0]
|
||||
assert len(call_args) == 0
|
||||
|
||||
def test_stage1_uses_file_upload_when_no_gcs_uri(self):
|
||||
"""When input_gcs_uri is not set, Stage 1 uses file upload as before."""
|
||||
from karaoke_gen.audio_processor import AudioProcessor
|
||||
import logging
|
||||
|
||||
processor = AudioProcessor(
|
||||
logger=logging.getLogger("test"),
|
||||
log_level=logging.INFO,
|
||||
log_formatter=None,
|
||||
model_file_dir=None,
|
||||
lossless_output_format="FLAC",
|
||||
clean_instrumental_model="test.ckpt",
|
||||
backing_vocals_models=[],
|
||||
other_stems_models=[],
|
||||
ffmpeg_base_command="ffmpeg",
|
||||
)
|
||||
processor.instrumental_preset = "instrumental_clean"
|
||||
processor.karaoke_preset = None
|
||||
processor.job_id = "file-test-001"
|
||||
# No input_gcs_uri set
|
||||
|
||||
mock_client = Mock()
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
stems_dir = os.path.join(temp_dir, "stems")
|
||||
os.makedirs(stems_dir)
|
||||
|
||||
for name in ["file-test-001_mixed_vocals.flac", "file-test-001_mixed_instrumental.flac"]:
|
||||
with open(os.path.join(stems_dir, name), "w") as f:
|
||||
f.write("fake audio")
|
||||
|
||||
mock_client.separate_audio_and_wait.return_value = {
|
||||
"status": "completed",
|
||||
"downloaded_files": [
|
||||
os.path.join(stems_dir, "file-test-001_mixed_vocals.flac"),
|
||||
os.path.join(stems_dir, "file-test-001_mixed_instrumental.flac"),
|
||||
],
|
||||
"files": {},
|
||||
}
|
||||
|
||||
input_file = os.path.join(temp_dir, "song.flac")
|
||||
with open(input_file, "w") as f:
|
||||
f.write("fake input")
|
||||
|
||||
with patch.object(processor, '_create_stems_directory', return_value=stems_dir):
|
||||
with patch.object(processor, '_normalize_audio_files'):
|
||||
with patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient', return_value=mock_client):
|
||||
processor._process_audio_separation_remote(
|
||||
input_file, "Test - Song", temp_dir, "http://fake-api",
|
||||
)
|
||||
|
||||
# Verify file_path was passed as positional arg (old behavior)
|
||||
call_args = mock_client.separate_audio_and_wait.call_args[0]
|
||||
assert call_args[0] == input_file
|
||||
# Verify gcs_uri was NOT in kwargs
|
||||
call_kwargs = mock_client.separate_audio_and_wait.call_args[1]
|
||||
assert "gcs_uri" not in call_kwargs
|
||||
@@ -374,6 +374,11 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
)
|
||||
audio_processor.job_id = job_id # Used as filename prefix (avoids artist/title encoding issues)
|
||||
|
||||
# Pass GCS URI so the separator can fetch directly from GCS (avoids 413 for large files)
|
||||
if job.input_media_gcs_path:
|
||||
audio_processor.input_gcs_uri = f"gs://{settings.gcs_bucket_name}/{job.input_media_gcs_path}"
|
||||
job_log.info(f" GCS URI for separator: {audio_processor.input_gcs_uri}")
|
||||
|
||||
# Store effective model names in state_data for video_worker to use in file naming
|
||||
# This ensures output filenames match local CLI behavior (e.g., "Instrumental model_bs_roformer_ep_317_sdr_12.9755.ckpt")
|
||||
effective_model_names = {
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
# Plan: Fix 413 Audio Separation Error via GCS Path Passthrough
|
||||
|
||||
**Created:** 2026-03-25
|
||||
**Branch:** feat/sess-20260325-1130-fix-413-audio-sep
|
||||
**Status:** Draft
|
||||
|
||||
## Overview
|
||||
|
||||
Audio separation fails with `413 Request Entity Too Large` when FLAC files exceed Cloud Run's 32MB request body limit. The current architecture uploads the entire audio file as a multipart POST body to the separator API. Since the file is **already in GCS** by the time the audio worker runs, we should pass the GCS path and let the separator download directly from GCS.
|
||||
|
||||
**Root cause:** `api_client.py:77,136` sends the file as `files={"file": (filename, open(file_path, "rb"))}` in a POST to `/separate`. Cloud Run rejects bodies > 32MB.
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] Audio separation works for files of any size (no HTTP body limit)
|
||||
- [ ] Backward compatible — file upload still works for non-GCS callers (CLI, tests)
|
||||
- [ ] No data duplication — separator reads from the same GCS bucket, doesn't copy
|
||||
- [ ] Stage 2 (backing vocals) still works — uses Stage 1 output which is local on the separator
|
||||
|
||||
## Technical Approach
|
||||
|
||||
**Change:** Add a `gcs_uri` parameter to the `/separate` endpoint. When provided, the separator downloads from GCS instead of expecting a file upload. The API client gains a new parameter for this.
|
||||
|
||||
Both services are in the same GCP project (`nomadkaraoke`), so the separator's service account just needs `roles/storage.objectViewer` on the `karaoke-gen-storage` bucket.
|
||||
|
||||
### Flow: Before
|
||||
```
|
||||
audio_worker → download from GCS → local file → HTTP POST (file bytes) → separator
|
||||
```
|
||||
|
||||
### Flow: After
|
||||
```
|
||||
audio_worker → pass GCS path → separator downloads from GCS directly
|
||||
```
|
||||
|
||||
Stage 2 (backing vocals) still uploads the local mixed_vocals file since it's a Stage 1 output that only exists on the separator's local disk. But Stage 2 files are small (vocals only), so no 413 risk.
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Repo 1: python-audio-separator (separate worktree)
|
||||
|
||||
1. [ ] **Server: Add `gcs_uri` parameter to `/separate` endpoint** (`audio_separator/remote/deploy_cloudrun.py`)
|
||||
- Add `gcs_uri: Optional[str] = Form(None)` parameter
|
||||
- When provided, download from GCS instead of reading `file` upload
|
||||
- Make `file` parameter optional (required only when `gcs_uri` not provided)
|
||||
- Validate: exactly one of `file` or `gcs_uri` must be provided
|
||||
|
||||
2. [ ] **Server: Add GCS download helper** (`audio_separator/remote/deploy_cloudrun.py`)
|
||||
- `download_from_gcs(gcs_uri: str, output_dir: str) -> tuple[bytes, str]`
|
||||
- Parse `gs://bucket/path` or just `bucket/path` format
|
||||
- Use `google-cloud-storage` (already a dependency for model download)
|
||||
- Return `(audio_bytes, filename)`
|
||||
|
||||
3. [ ] **Client: Add `gcs_uri` parameter** (`audio_separator/remote/api_client.py`)
|
||||
- Add `gcs_uri` param to `separate_audio()` and `separate_audio_and_wait()`
|
||||
- When `gcs_uri` is provided, send it as form data instead of file upload
|
||||
- When `gcs_uri` is provided, `file_path` becomes optional (not opened/sent)
|
||||
|
||||
4. [ ] **Tests: Add unit tests for GCS passthrough**
|
||||
- Test server accepts `gcs_uri` parameter
|
||||
- Test client sends `gcs_uri` instead of file when provided
|
||||
- Test validation (can't provide both `file` and `gcs_uri`, must provide one)
|
||||
|
||||
5. [ ] **Bump version, push, publish**
|
||||
|
||||
### Repo 2: karaoke-gen (this worktree)
|
||||
|
||||
6. [ ] **Infrastructure: Grant GCS read access to separator SA** (`infrastructure/modules/audio_separator_service.py`)
|
||||
- Add `roles/storage.objectViewer` on `karaoke-gen-storage` bucket to the `audio-separator` service account
|
||||
|
||||
7. [ ] **Audio worker: Pass GCS path to separator** (`karaoke_gen/audio_processor.py`)
|
||||
- In `_process_audio_separation_remote()`, pass `gcs_uri` for Stage 1
|
||||
- Construct URI: `gs://karaoke-gen-storage/{job.input_media_gcs_path}`
|
||||
- Stage 2 continues using local file upload (the mixed_vocals file is on separator's disk, not in GCS)
|
||||
|
||||
8. [ ] **Update audio-separator dependency** (`pyproject.toml`)
|
||||
- `poetry update audio-separator` after the new version is published
|
||||
|
||||
9. [ ] **Tests**
|
||||
- Update existing audio processor tests to verify `gcs_uri` is passed
|
||||
- Test that Stage 1 uses GCS path, Stage 2 uses file upload
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
### python-audio-separator
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `audio_separator/remote/deploy_cloudrun.py` | Modify | Add `gcs_uri` param to `/separate`, add GCS download helper |
|
||||
| `audio_separator/remote/api_client.py` | Modify | Add `gcs_uri` param to client methods |
|
||||
| `tests/unit/test_remote_api_client.py` | Modify | Add tests for GCS passthrough |
|
||||
| `pyproject.toml` | Modify | Bump version |
|
||||
|
||||
### karaoke-gen
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `infrastructure/modules/audio_separator_service.py` | Modify | Add GCS read permission |
|
||||
| `karaoke_gen/audio_processor.py` | Modify | Pass `gcs_uri` in Stage 1 |
|
||||
| `backend/workers/audio_worker.py` | Modify | Pass GCS path to audio processor |
|
||||
| `pyproject.toml` | Modify | Update audio-separator dependency |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests:** Mock GCS client in separator, verify download_from_gcs works
|
||||
- **Unit tests:** Verify API client sends gcs_uri param correctly
|
||||
- **Integration test:** Deploy separator locally, test with a real GCS file
|
||||
- **Production test:** Re-run failed job `45f9bbc0` after deployment
|
||||
|
||||
## Open Questions
|
||||
|
||||
- [ ] Should we also upload Stage 2 input (mixed_vocals) to GCS and use gcs_uri? Not needed now — vocals-only files are small — but would be more consistent.
|
||||
- [ ] Should the `gcs_uri` format be `gs://bucket/path` or just the blob path with a separate bucket param? Suggest `gs://` URI for clarity and flexibility.
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
- Revert to file upload by not passing `gcs_uri` — the parameter is optional
|
||||
- The separator still accepts file uploads as before (backward compatible)
|
||||
- No infrastructure changes needed for rollback (extra IAM permission is harmless)
|
||||
|
||||
## Execution Order
|
||||
|
||||
1. Start with python-audio-separator (steps 1-5) — this is the dependency
|
||||
2. Apply infra change (step 6) — can be done in parallel
|
||||
3. Update karaoke-gen (steps 7-9) — depends on step 5
|
||||
@@ -437,6 +437,16 @@ divebar_sync_compute_admin = gcp.projects.IAMMember(
|
||||
# Cloud Run GPU (L4) service for audio stem separation — replaces Modal
|
||||
audio_separator_resources = audio_separator_service.create_all_resources()
|
||||
|
||||
# Grant audio separator read access to main storage bucket (for GCS URI passthrough)
|
||||
gcp.storage.BucketIAMMember(
|
||||
"audio-separator-storage-reader",
|
||||
bucket=bucket.name,
|
||||
role="roles/storage.objectViewer",
|
||||
member=audio_separator_resources["service_account"].email.apply(
|
||||
lambda email: f"serviceAccount:{email}"
|
||||
),
|
||||
)
|
||||
|
||||
# ==================== Compute VMs ====================
|
||||
|
||||
# Encoding Worker VMs (blue-green pair for zero-downtime deployments)
|
||||
|
||||
@@ -185,6 +185,9 @@ def grant_github_actions_permissions(
|
||||
pool.name.apply(
|
||||
lambda pool_name: f"principalSet://iam.googleapis.com/{pool_name}/attribute.repository/nomadkaraoke/karaoke-decide"
|
||||
),
|
||||
pool.name.apply(
|
||||
lambda pool_name: f"principalSet://iam.googleapis.com/{pool_name}/attribute.repository/nomadkaraoke/python-audio-separator"
|
||||
),
|
||||
pool.name.apply(
|
||||
lambda pool_name: f"principalSet://iam.googleapis.com/{pool_name}/attribute.repository/beveradb/cryptotrader"
|
||||
),
|
||||
|
||||
@@ -96,7 +96,7 @@ echo "Creating Python virtual environment..."
|
||||
# Install base Python dependencies (wheel will add more at runtime)
|
||||
source venv/bin/activate
|
||||
pip install --upgrade pip
|
||||
pip install fastapi uvicorn google-cloud-storage aiofiles aiohttp
|
||||
pip install fastapi uvicorn google-cloud-storage aiofiles aiohttp packaging
|
||||
|
||||
# Create bootstrap script (runs via ExecStartPre before service starts)
|
||||
# This minimal script downloads the REAL startup script from GCS.
|
||||
|
||||
@@ -348,10 +348,19 @@ class AudioProcessor:
|
||||
self.logger.info(f"Stage 1: Using explicit models: {stage1_models}")
|
||||
stage1_kwargs["models"] = stage1_models
|
||||
|
||||
stage1_result = api_client.separate_audio_and_wait(
|
||||
audio_file,
|
||||
**stage1_kwargs,
|
||||
)
|
||||
# Use GCS URI for Stage 1 if available (avoids 413 for large files)
|
||||
input_gcs_uri = getattr(self, 'input_gcs_uri', None)
|
||||
if input_gcs_uri:
|
||||
self.logger.info(f"Stage 1: Using GCS URI: {input_gcs_uri}")
|
||||
stage1_kwargs["gcs_uri"] = input_gcs_uri
|
||||
stage1_result = api_client.separate_audio_and_wait(
|
||||
**stage1_kwargs,
|
||||
)
|
||||
else:
|
||||
stage1_result = api_client.separate_audio_and_wait(
|
||||
audio_file,
|
||||
**stage1_kwargs,
|
||||
)
|
||||
|
||||
if stage1_result["status"] != "completed":
|
||||
raise Exception(f"Stage 1 remote audio separation failed: {stage1_result.get('error', 'Unknown error')}")
|
||||
|
||||
Generated
+26
-4
@@ -350,14 +350,14 @@ files = [
|
||||
|
||||
[[package]]
|
||||
name = "audio-separator"
|
||||
version = "0.43.0"
|
||||
version = "0.44.0"
|
||||
description = "Easy to use audio stem separation, using various models from UVR trained primarily by @Anjok07"
|
||||
optional = false
|
||||
python-versions = ">=3.10"
|
||||
groups = ["main"]
|
||||
files = [
|
||||
{file = "audio_separator-0.43.0-py3-none-any.whl", hash = "sha256:7315f26fd0715e5cb3ddd02532565f2b63f77f208391463ad6bccd7cf4583454"},
|
||||
{file = "audio_separator-0.43.0.tar.gz", hash = "sha256:4628c2f1c43fc2d17a93e5451921bd6f5f720791d2bbf4bb6b70bda7114ac633"},
|
||||
{file = "audio_separator-0.44.0-py3-none-any.whl", hash = "sha256:750bee702eb718ea3d3848f396020e911de0679f6b153619cf9d66a4b85c1c58"},
|
||||
{file = "audio_separator-0.44.0.tar.gz", hash = "sha256:a05e5f906074414e727b3ee1acedc64f23a123436fcae0daa086817e7c91495f"},
|
||||
]
|
||||
|
||||
[package.dependencies]
|
||||
@@ -2546,6 +2546,28 @@ requests-oauthlib = ">=0.7.0"
|
||||
[package.extras]
|
||||
tool = ["click (>=6.0.0)"]
|
||||
|
||||
[[package]]
|
||||
name = "google-cloud-compute"
|
||||
version = "1.46.0"
|
||||
description = "Google Cloud Compute API client library"
|
||||
optional = false
|
||||
python-versions = ">=3.7"
|
||||
groups = ["main"]
|
||||
files = [
|
||||
{file = "google_cloud_compute-1.46.0-py3-none-any.whl", hash = "sha256:f92d9a7c32454b8a719ff937bfd46e794ee35d65e141ec5d20797aad6988dfb0"},
|
||||
{file = "google_cloud_compute-1.46.0.tar.gz", hash = "sha256:8b0f8d5a1115e8beae5fafdc7050f1ad15e922a5cdf6c634e5a745e47cb49281"},
|
||||
]
|
||||
|
||||
[package.dependencies]
|
||||
google-api-core = {version = ">=1.34.1,<2.0.dev0 || >=2.11.dev0,<3.0.0", extras = ["grpc"]}
|
||||
google-auth = ">=2.14.1,<2.24.0 || >2.24.0,<2.25.0 || >2.25.0,<3.0.0"
|
||||
grpcio = ">=1.33.2,<2.0.0"
|
||||
proto-plus = [
|
||||
{version = ">=1.25.0,<2.0.0", markers = "python_version >= \"3.13\""},
|
||||
{version = ">=1.22.3,<2.0.0"},
|
||||
]
|
||||
protobuf = ">=3.20.2,<4.21.0 || >4.21.0,<4.21.1 || >4.21.1,<4.21.2 || >4.21.2,<4.21.3 || >4.21.3,<4.21.4 || >4.21.4,<4.21.5 || >4.21.5,<7.0.0"
|
||||
|
||||
[[package]]
|
||||
name = "google-cloud-core"
|
||||
version = "2.5.0"
|
||||
@@ -10680,4 +10702,4 @@ local-whisper = ["whisper-timestamped"]
|
||||
[metadata]
|
||||
lock-version = "2.1"
|
||||
python-versions = ">=3.10,<3.14"
|
||||
content-hash = "bfb710412104ada6da5504e2afb3181da05cac4d6ed1238d08e9a712c254f22d"
|
||||
content-hash = "fd26762a0d3f754ddc150bb24dc6d1ee1a15cb8154584950b213029751315ed2"
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.151.0"
|
||||
version = "0.152.0"
|
||||
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"
|
||||
@@ -88,6 +88,7 @@ pydantic-settings = ">=2.1.0"
|
||||
httpx = ">=0.25.0"
|
||||
tenacity = "^8.2.0" # Retry logic for external service calls
|
||||
google-cloud-firestore = "2.26.0"
|
||||
google-cloud-compute = "^1.0.0"
|
||||
google-cloud-storage = "3.10.1"
|
||||
google-cloud-secret-manager = "2.26.0"
|
||||
google-cloud-monitoring = "2.29.1" # Cloud Monitoring for YouTube API quota metrics
|
||||
|
||||
Reference in new issue
Block a user