Commit 7d812f92 authored by Aryan Noshirvani's avatar Aryan Noshirvani

Fix /remix hanging indefinitely on submit

Root cause of the "failed to submit" report: identify_audio (real
Shazam/AcoustID network calls) was running synchronously in the POST
/remix request handler, once per uploaded file, before the response
was ever sent. Confirmed via server logs that a single Shazam call
takes ~30s to time out on a miss - with 2 files that's a minute-plus
of the browser just waiting on fetch() with nothing to show for it,
easily read as "broken."

Moved identify_audio into the background job (render_remix_sync),
where it belongs alongside the rest of the slow pipeline (BPM
detection, Gemini planning, Demucs). The API handler now only does
fast local I/O - save the uploads, create the job row, queue the
background task, return immediately.

Verified with a real headless-browser test (Playwright) driving the
actual console UI end-to-end, not just curl/pytest against the API:
submit now returns in well under a second and the job progresses
through queued -> planning -> separating -> ... -> done while the
page polls, exactly as designed.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BCxXmJVvDFJVHTUi4QgNzi
parent b1bd442b
...@@ -4,18 +4,16 @@ import shutil ...@@ -4,18 +4,16 @@ import shutil
import uuid import uuid
from typing import List from typing import List
from fastapi import APIRouter, BackgroundTasks, Depends, File, Form, HTTPException, UploadFile from fastapi import APIRouter, BackgroundTasks, Depends, File, Form, HTTPException, Request, UploadFile
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from src.core.database import RemixJob, get_db from src.core.database import RemixJob, get_db
from src.services.music_identification import identify_audio
from src.services.remix_engine import render_remix_sync from src.services.remix_engine import render_remix_sync
router = APIRouter(prefix="/remix", tags=["AI Remix"]) router = APIRouter(prefix="/remix", tags=["AI Remix"])
MAX_SONGS = 5 MAX_SONGS = 5
TEMP_DIR = "/root/antigrav-stax-audio/temp" TEMP_DIR = "/root/antigrav-stax-audio/temp"
DOWNLOAD_HOST = "http://91.234.52.134:8001"
@router.post("") @router.post("")
...@@ -25,30 +23,25 @@ async def create_remix( ...@@ -25,30 +23,25 @@ async def create_remix(
files: List[UploadFile] = File(..., description="1 to 5 audio files to remix together"), files: List[UploadFile] = File(..., description="1 to 5 audio files to remix together"),
db: Session = Depends(get_db), db: Session = Depends(get_db),
): ):
# Deliberately does nothing here except fast local I/O (save the uploads) - no
# identify_audio/Shazam/AcoustID calls. Those are real network calls that can take
# ~30s each to time out, and doing them here would block this response for
# potentially minutes with multiple files. All of that happens inside the background
# job instead, where it belongs alongside the rest of the slow pipeline.
if not files: if not files:
raise HTTPException(status_code=400, detail="At least one audio file is required.") raise HTTPException(status_code=400, detail="At least one audio file is required.")
if len(files) > MAX_SONGS: if len(files) > MAX_SONGS:
raise HTTPException(status_code=400, detail=f"At most {MAX_SONGS} songs are supported per remix.") raise HTTPException(status_code=400, detail=f"At most {MAX_SONGS} songs are supported per remix.")
input_paths = [] input_paths = []
songs_meta = [] filenames = []
try: try:
for f in files: for f in files:
temp_path = os.path.join(TEMP_DIR, f"{uuid.uuid4()}_{f.filename}") temp_path = os.path.join(TEMP_DIR, f"{uuid.uuid4()}_{f.filename}")
with open(temp_path, "wb") as buffer: with open(temp_path, "wb") as buffer:
shutil.copyfileobj(f.file, buffer) shutil.copyfileobj(f.file, buffer)
input_paths.append(temp_path) input_paths.append(temp_path)
filenames.append(f.filename)
meta = {"title": os.path.splitext(f.filename)[0], "artist": "Unknown Artist", "genre": "Unknown"}
try:
candidates = await identify_audio(temp_path)
if candidates:
meta["title"] = candidates[0].get("title", meta["title"])
meta["artist"] = candidates[0].get("artist", meta["artist"])
meta["genre"] = candidates[0].get("genre", meta["genre"])
except Exception:
pass
songs_meta.append(meta)
except Exception as e: except Exception as e:
for p in input_paths: for p in input_paths:
if os.path.exists(p): if os.path.exists(p):
...@@ -60,13 +53,13 @@ async def create_remix( ...@@ -60,13 +53,13 @@ async def create_remix(
db.commit() db.commit()
db.refresh(job) db.refresh(job)
background_tasks.add_task(render_remix_sync, job.id, input_paths, prompt, songs_meta) background_tasks.add_task(render_remix_sync, job.id, input_paths, prompt, filenames)
return {"job_id": job.id, "status": job.status, "status_url": f"/remix/{job.id}"} return {"job_id": job.id, "status": job.status, "status_url": f"/remix/{job.id}"}
@router.get("/{job_id}") @router.get("/{job_id}")
async def get_remix_status(job_id: int, db: Session = Depends(get_db)): async def get_remix_status(job_id: int, request: Request, db: Session = Depends(get_db)):
job = db.query(RemixJob).filter(RemixJob.id == job_id).first() job = db.query(RemixJob).filter(RemixJob.id == job_id).first()
if not job: if not job:
raise HTTPException(status_code=404, detail="Remix job not found.") raise HTTPException(status_code=404, detail="Remix job not found.")
...@@ -80,7 +73,7 @@ async def get_remix_status(job_id: int, db: Session = Depends(get_db)): ...@@ -80,7 +73,7 @@ async def get_remix_status(job_id: int, db: Session = Depends(get_db)):
if job.plan_json: if job.plan_json:
response["plan"] = json.loads(job.plan_json) response["plan"] = json.loads(job.plan_json)
if job.status == "done" and job.result_filename: if job.status == "done" and job.result_filename:
response["download_url"] = f"{DOWNLOAD_HOST}/downloads/{job.result_filename}" response["download_url"] = f"{str(request.base_url).rstrip('/')}/downloads/{job.result_filename}"
if job.status == "error": if job.status == "error":
response["error"] = job.error response["error"] = job.error
......
...@@ -13,6 +13,7 @@ from pedalboard import Compressor, Pedalboard, PitchShift, Reverb ...@@ -13,6 +13,7 @@ from pedalboard import Compressor, Pedalboard, PitchShift, Reverb
from src.core.config import GEMINI_API_KEY, logger from src.core.config import GEMINI_API_KEY, logger
from src.core.database import RemixJob, SessionLocal from src.core.database import RemixJob, SessionLocal
from src.services.music_identification import identify_audio
# This VPS's virtualized CPU exposes no SSE3/SSE4/AVX at all, which makes PyTorch's # This VPS's virtualized CPU exposes no SSE3/SSE4/AVX at all, which makes PyTorch's
# oneDNN (MKLDNN) backend fail with "could not create a primitive" on demucs's real-sized # oneDNN (MKLDNN) backend fail with "could not create a primitive" on demucs's real-sized
...@@ -169,10 +170,14 @@ def _load_mono(path: str, sr: int) -> np.ndarray: ...@@ -169,10 +170,14 @@ def _load_mono(path: str, sr: int) -> np.ndarray:
return y return y
def render_remix_sync(job_id: int, input_paths: list, prompt: str, songs_meta: list): def render_remix_sync(job_id: int, input_paths: list, prompt: str, filenames: list):
"""The full synchronous remix pipeline: plan -> separate -> time-stretch -> mix -> master """The full synchronous remix pipeline: identify -> plan -> separate -> time-stretch ->
-> tag. Runs in a worker thread via FastAPI's BackgroundTasks; updates the RemixJob row mix -> master -> tag. Runs in a worker thread via FastAPI's BackgroundTasks; updates the
in the DB as it progresses so clients can poll status.""" RemixJob row in the DB as it progresses so clients can poll status.
identify_audio (Shazam/AcoustID) runs here, not in the API handler - each call can take
~30s to time out on a miss, which would otherwise block the initial HTTP response for
minutes with multiple songs. The API handler only saves files and returns immediately."""
db = SessionLocal() db = SessionLocal()
def set_status(status: str, detail: str = None): def set_status(status: str, detail: str = None):
...@@ -183,19 +188,28 @@ def render_remix_sync(job_id: int, input_paths: list, prompt: str, songs_meta: l ...@@ -183,19 +188,28 @@ def render_remix_sync(job_id: int, input_paths: list, prompt: str, songs_meta: l
db.commit() db.commit()
try: try:
set_status("planning", "Detecting tempo for each song") set_status("planning", "Identifying songs and detecting tempo")
target_sr = 44100 target_sr = 44100
songs_info = [] songs_info = []
for i, path in enumerate(input_paths): for i, path in enumerate(input_paths):
bpm = detect_bpm(path) bpm = detect_bpm(path)
meta = songs_meta[i] if i < len(songs_meta) else {} fallback_title = os.path.splitext(filenames[i])[0] if i < len(filenames) else f"Track {i + 1}"
title, artist, genre = fallback_title, "Unknown Artist", "Unknown"
try:
candidates = asyncio.run(identify_audio(path))
if candidates:
title = candidates[0].get("title", title)
artist = candidates[0].get("artist", artist)
genre = candidates[0].get("genre", genre)
except Exception as e:
logger.warning(f"identify_audio failed for song {i}, using filename as title: {e}")
songs_info.append({ songs_info.append({
"index": i, "index": i,
"path": path, "path": path,
"bpm": bpm, "bpm": bpm,
"title": meta.get("title", f"Track {i + 1}"), "title": title,
"artist": meta.get("artist", "Unknown Artist"), "artist": artist,
"genre": meta.get("genre", "Unknown"), "genre": genre,
}) })
set_status("planning", "Asking Gemini for a remix plan") set_status("planning", "Asking Gemini for a remix plan")
......
...@@ -23,29 +23,31 @@ def test_remix_requires_at_least_one_file(client): ...@@ -23,29 +23,31 @@ def test_remix_requires_at_least_one_file(client):
assert response.status_code == 422 assert response.status_code == 422
async def _fake_identify_audio(path):
return []
def test_remix_rejects_more_than_five_songs(client, monkeypatch): def test_remix_rejects_more_than_five_songs(client, monkeypatch):
monkeypatch.setattr(remix_router, "render_remix_sync", lambda *a, **kw: None) monkeypatch.setattr(remix_router, "render_remix_sync", lambda *a, **kw: None)
monkeypatch.setattr(remix_router, "identify_audio", _fake_identify_audio)
files = [("files", (f"song{i}.wav", io.BytesIO(_wav_bytes()), "audio/wav")) for i in range(6)] files = [("files", (f"song{i}.wav", io.BytesIO(_wav_bytes()), "audio/wav")) for i in range(6)]
response = client.post("/remix", data={"prompt": "mashup"}, files=files) response = client.post("/remix", data={"prompt": "mashup"}, files=files)
assert response.status_code == 400 assert response.status_code == 400
def test_remix_accepts_job_and_reports_status(client, monkeypatch): def test_remix_does_not_call_identify_audio_before_responding(client, monkeypatch):
# The whole point of the earlier fix: identify_audio (real Shazam/AcoustID network
# calls, ~30s each on a miss) must never run inside the request/response cycle - only
# inside the background job. If someone re-adds it to the endpoint, this call would
# hang/raise instead of the fast, synchronous response below.
captured = {} captured = {}
def fake_render(job_id, input_paths, prompt, songs_meta): def fake_render(job_id, input_paths, prompt, filenames):
captured["job_id"] = job_id captured["job_id"] = job_id
captured["input_paths"] = input_paths captured["input_paths"] = input_paths
captured["prompt"] = prompt captured["prompt"] = prompt
captured["songs_meta"] = songs_meta captured["filenames"] = filenames
monkeypatch.setattr(remix_router, "render_remix_sync", fake_render) monkeypatch.setattr(remix_router, "render_remix_sync", fake_render)
monkeypatch.setattr(remix_router, "identify_audio", _fake_identify_audio) assert not hasattr(remix_router, "identify_audio"), (
"identify_audio got imported back into the router - it belongs in the "
"background job (remix_engine.render_remix_sync), not the request handler."
)
files = [ files = [
("files", ("song_a.wav", io.BytesIO(_wav_bytes()), "audio/wav")), ("files", ("song_a.wav", io.BytesIO(_wav_bytes()), "audio/wav")),
...@@ -63,7 +65,7 @@ def test_remix_accepts_job_and_reports_status(client, monkeypatch): ...@@ -63,7 +65,7 @@ def test_remix_accepts_job_and_reports_status(client, monkeypatch):
assert captured["job_id"] == job_id assert captured["job_id"] == job_id
assert len(captured["input_paths"]) == 2 assert len(captured["input_paths"]) == 2
assert len(captured["songs_meta"]) == 2 assert captured["filenames"] == ["song_a.wav", "song_b.wav"]
def test_remix_status_404_for_unknown_job(client): def test_remix_status_404_for_unknown_job(client):
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment