Commit 383b5162 authored by Aryan Noshirvani's avatar Aryan Noshirvani

Wire the remix engine into the social graph

Completed remixes were only ever written to the RemixJob row and the
downloads/ folder - invisible to /library, /social, and therefore to
"remix trees" entirely. A remix created through /remix had zero
connection to the rest of the app's social model.

- /remix now accepts library_song_ids (comma-separated LibrarySong
  IDs) as an alternative/addition to uploaded files. Using a library
  song as a source is what makes tree linkage possible - a source
  with no existing library entry has nothing to link back to. Also
  accepts an optional user_id for attribution.
- On completion, the engine now registers the output as a real
  LibrarySong (streamable, searchable, playlist-able, same as any
  other library entry) and creates a Post referencing it, so finished
  remixes actually show up in the social feed.
- parent_post_id links to the first library-sourced input's most
  recent existing Post, if any - the schema only supports one parent
  per post (a tree, not a DAG), so with multiple library-sourced
  inputs only the first is represented as the "parent."
- RemixJob gained result_song_id/result_post_id columns, surfaced in
  the GET /remix/{id} response once done. Added a lightweight
  automatic migration in database.py (create_all only creates missing
  tables, never ALTERs existing ones for new columns - this bit dev's
  own already-running database the moment these columns were added).

Also fixed two real bugs hit while testing this end-to-end against the
live Gemini API (not caught by mocked tests, since they're about the
actual shape of model output):
- gain_db came back as a per-stem dict ({"drums": -6.0, "other": 0.0})
  instead of the single float the schema asks for, when a role listed
  multiple stems - added _coerce_gain_db to average/sanitize whatever
  comes back rather than assuming schema compliance is guaranteed even
  with response_mime_type=application/json.
- Gemini occasionally returns syntactically invalid JSON outright (a
  missing comma mid-response) - added a 3-attempt retry around
  generation+parsing, the standard mitigation for this class of
  transient flakiness.

Verified end-to-end against the real API: submitted a remix using two
pre-existing library songs (one with an existing social Post), and
confirmed GET /social/posts/{id}/tree shows the finished remix as a
real child post with the correct caption and parent linkage.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BCxXmJVvDFJVHTUi4QgNzi
parent 242f03ef
Pipeline #1001 passed with stage
in 7 minutes and 44 seconds
......@@ -2,12 +2,12 @@ import json
import os
import shutil
import uuid
from typing import List
from typing import List, Optional
from fastapi import APIRouter, BackgroundTasks, Depends, File, Form, HTTPException, Request, UploadFile
from sqlalchemy.orm import Session
from src.core.database import RemixJob, get_db
from src.core.database import LibrarySong, RemixJob, get_db
from src.services.remix_engine import render_remix_sync
router = APIRouter(prefix="/remix", tags=["AI Remix"])
......@@ -20,21 +20,45 @@ TEMP_DIR = "/root/antigrav-stax-audio/temp"
async def create_remix(
background_tasks: BackgroundTasks,
prompt: str = Form(..., description="Natural-language description of the remix you want, e.g. 'blend the vocals of the first song over the beat of the second, slowed down and dreamy'"),
files: List[UploadFile] = File(..., description="1 to 5 audio files to remix together"),
files: List[UploadFile] = File(default=[], description="Audio files to remix together"),
library_song_ids: Optional[str] = Form(None, description="Comma-separated LibrarySong IDs to use as sources instead of (or alongside) uploaded files - using library songs is what lets the finished remix link back into the social/remix-tree graph"),
user_id: Optional[int] = Form(None, description="Attributes the resulting library entry and social post to this user"),
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
# Deliberately does nothing here except fast local I/O (save uploads, look up library
# rows) - 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:
raise HTTPException(status_code=400, detail="At least one audio file is required.")
if len(files) > MAX_SONGS:
parsed_library_ids = [s.strip() for s in (library_song_ids or "").split(",") if s.strip()]
total_requested = len(parsed_library_ids) + len(files)
if total_requested == 0:
raise HTTPException(status_code=400, detail="At least one audio file or library_song_id is required.")
if total_requested > MAX_SONGS:
raise HTTPException(status_code=400, detail=f"At most {MAX_SONGS} songs are supported per remix.")
input_paths = []
filenames = []
source_song_ids = [] # parallel to input_paths: LibrarySong.id if this source came from
# the library (so the finished remix's Post can link back to it),
# None for a fresh upload with no existing library entry.
if library_song_ids:
for raw_id in library_song_ids.split(","):
raw_id = raw_id.strip()
if not raw_id:
continue
try:
song_id = int(raw_id)
except ValueError:
raise HTTPException(status_code=400, detail=f"Invalid library_song_ids value: {raw_id!r}")
song = db.query(LibrarySong).filter(LibrarySong.id == song_id).first()
if not song or not song.file_path or not os.path.exists(song.file_path):
raise HTTPException(status_code=400, detail=f"Library song {song_id} not found or its file is missing.")
input_paths.append(song.file_path)
filenames.append(song.title or os.path.basename(song.file_path))
source_song_ids.append(song.id)
try:
for f in files:
temp_path = os.path.join(TEMP_DIR, f"{uuid.uuid4()}_{f.filename}")
......@@ -42,9 +66,10 @@ async def create_remix(
shutil.copyfileobj(f.file, buffer)
input_paths.append(temp_path)
filenames.append(f.filename)
source_song_ids.append(None)
except Exception as e:
for p in input_paths:
if os.path.exists(p):
if os.path.exists(p) and p.startswith(TEMP_DIR):
os.remove(p)
raise HTTPException(status_code=500, detail=f"Failed to receive uploaded files: {e}")
......@@ -53,7 +78,7 @@ async def create_remix(
db.commit()
db.refresh(job)
background_tasks.add_task(render_remix_sync, job.id, input_paths, prompt, filenames)
background_tasks.add_task(render_remix_sync, job.id, input_paths, prompt, filenames, source_song_ids, user_id)
return {"job_id": job.id, "status": job.status, "status_url": f"/remix/{job.id}"}
......@@ -74,6 +99,8 @@ async def get_remix_status(job_id: int, request: Request, db: Session = Depends(
response["plan"] = json.loads(job.plan_json)
if job.status == "done" and job.result_filename:
response["download_url"] = f"{str(request.base_url).rstrip('/')}/downloads/{job.result_filename}"
response["library_song_id"] = job.result_song_id
response["post_id"] = job.result_post_id
if job.status == "error":
response["error"] = job.error
......
......@@ -114,12 +114,41 @@ class RemixJob(Base):
plan_json = Column(String, nullable=True) # the AI-generated remix plan, once produced
remix_name = Column(String, nullable=True)
result_filename = Column(String, nullable=True)
result_song_id = Column(Integer, ForeignKey("library_songs.id"), nullable=True) # set once the finished remix is registered in the library
result_post_id = Column(Integer, ForeignKey("posts.id"), nullable=True) # set once the finished remix is posted to the social feed
error = Column(String, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
Base.metadata.create_all(bind=engine)
def _run_lightweight_migrations():
"""create_all() only creates tables that don't exist yet - it never ALTERs an existing
table to add new columns, so a schema change like RemixJob.result_song_id above would
silently break on any database file created before this change. This is a stopgap (not
a real migration framework like Alembic) that adds any missing columns to already-
existing tables, safe to run on every startup."""
from sqlalchemy import inspect, text
inspector = inspect(engine)
existing_tables = set(inspector.get_table_names())
for table in Base.metadata.sorted_tables:
if table.name not in existing_tables:
continue
existing_columns = {col["name"] for col in inspector.get_columns(table.name)}
for column in table.columns:
if column.name in existing_columns:
continue
col_type = column.type.compile(engine.dialect)
with engine.begin() as conn:
conn.execute(text(f'ALTER TABLE "{table.name}" ADD COLUMN "{column.name}" {col_type}'))
_run_lightweight_migrations()
def get_db():
db = SessionLocal()
try:
......
......@@ -23,7 +23,7 @@ from pedalboard import (
from scipy.signal import butter, filtfilt
from src.core.config import GEMINI_API_KEY, logger
from src.core.database import RemixJob, SessionLocal
from src.core.database import LibrarySong, Post, 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
......@@ -150,9 +150,8 @@ def _semitone_shift_to_key(from_tonic: int, to_tonic: int) -> int:
# ---------------------------------------------------------------------------
# AI pipeline: Gemini perceives the audio, Claude reasons about the request.
# Split this way because Claude's API has no audio input at all, while Gemini's fast/cheap
# tier is not its strongest reasoner - each model does the part it's actually best at.
# AI pipeline: a single Gemini call both perceives the audio (real previews of every
# song) and reasons about the request, producing the full structured plan.
# ---------------------------------------------------------------------------
def _make_audio_preview_part(file_path: str, seconds: int = 25) -> dict:
......@@ -165,6 +164,21 @@ def _make_audio_preview_part(file_path: str, seconds: int = 25) -> dict:
return {"mime_type": "audio/wav", "data": data}
def _coerce_gain_db(value) -> float:
"""The schema asks Gemini for a single float gain_db per song_role, but it has been
observed returning a per-stem breakdown instead (e.g. {"drums": -6.0, "other": 0.0})
when a role has multiple stems - even with response_mime_type=application/json
constraining valid JSON syntax, the *shape* of a field isn't guaranteed. Rather than
tightening the prompt and hoping it never recurs, this coerces whatever comes back into
a single usable float: a dict's values are averaged, anything else falls back to 0."""
if isinstance(value, dict):
numbers = [v for v in value.values() if isinstance(v, (int, float))]
return float(sum(numbers) / len(numbers)) if numbers else 0.0
if isinstance(value, (int, float)):
return float(value)
return 0.0
async def plan_remix(prompt: str, songs_info: list) -> dict:
"""Gemini listens to a real audio preview of every song plus real detected BPM/key data,
and produces the full executable plan in one call: a sectioned arrangement, harmonic
......@@ -226,7 +240,7 @@ Return a JSON object strictly following this schema:
"start_fraction": float (0.0-1.0, position in the overall timeline),
"end_fraction": float (0.0-1.0, greater than start_fraction),
"song_roles": [
{{"index": int, "stems": [str, subset of "vocals"/"drums"/"bass"/"other"], "gain_db": float}}
{{"index": int, "stems": [str, subset of "vocals"/"drums"/"bass"/"other"], "gain_db": float (a single overall number for this role, e.g. -3.0 - NOT a per-stem breakdown/object, even if multiple stems are listed)}}
]
}}
],
......@@ -240,13 +254,28 @@ Return a JSON object strictly following this schema:
sections must be contiguous and cover start_fraction 0.0 through end_fraction 1.0 with no gaps or overlaps, at least 1 section and no more than 6."""
parts.append(instructions)
# Gemini occasionally returns syntactically invalid JSON despite
# response_mime_type=application/json constraining the output format (seen live: a
# missing comma partway through a large structured response) - a plain retry is the
# standard, effective mitigation for this class of transient generation flakiness.
last_error = None
for attempt in range(3):
response = await asyncio.to_thread(model.generate_content, parts)
try:
plan = json.loads(response.text)
break
except json.JSONDecodeError as e:
last_error = e
logger.warning(f"plan_remix: invalid JSON on attempt {attempt + 1}/3: {e}. Raw response: {response.text[:500]}")
else:
raise Exception(f"Gemini returned invalid JSON for the remix plan after 3 attempts: {last_error}")
valid_indices = {info["index"] for info in songs_info}
for section in plan.get("sections", []):
for role in section.get("song_roles", []):
role["stems"] = [s for s in role.get("stems", []) if s in STEM_NAMES]
role["gain_db"] = _coerce_gain_db(role.get("gain_db", 0.0))
section["song_roles"] = [r for r in section.get("song_roles", []) if r.get("index") in valid_indices]
if not plan.get("sections"):
......@@ -331,17 +360,24 @@ def _apply_style_preset(audio: np.ndarray, sr: int, style: str) -> np.ndarray:
# Main pipeline
# ---------------------------------------------------------------------------
def render_remix_sync(job_id: int, input_paths: list, prompt: str, filenames: list):
def render_remix_sync(job_id: int, input_paths: list, prompt: str, filenames: list, source_song_ids: list = None, user_id: int = None):
"""The full remix pipeline: identify -> detect BPM/key -> plan (Gemini, listens to real
audio previews and directs the whole arrangement) -> separate (Demucs) -> stretch/
pitch-match each stem once -> render each section of the arrangement -> sidechain ->
style preset -> master -> tag.
style preset -> master -> tag -> register in the library and post to the social feed.
Runs in a worker thread via FastAPI's BackgroundTasks; updates the RemixJob row in the
DB as it progresses so clients can poll status. identify_audio and the AI calls run here
(not in the API handler) because they're slow, unpredictable-latency network calls that
would otherwise block the initial HTTP response for a long time."""
would otherwise block the initial HTTP response for a long time.
source_song_ids is parallel to input_paths: a LibrarySong.id for any source that came
from the library (skips the redundant identify_audio call and lets the finished remix's
Post link back to that song's existing Post, if any - this is what makes a "remix tree"
reflect an actual remix instead of only manual /social/posts calls), or None for a
source with no existing library entry (a fresh upload)."""
db = SessionLocal()
source_song_ids = source_song_ids or [None] * len(input_paths)
def set_status(status: str, detail: str = None):
job = db.query(RemixJob).filter(RemixJob.id == job_id).first()
......@@ -358,6 +394,14 @@ def render_remix_sync(job_id: int, input_paths: list, prompt: str, filenames: li
key = detect_key(path)
fallback_title = os.path.splitext(filenames[i])[0] if i < len(filenames) else f"Track {i + 1}"
title, artist = fallback_title, "Unknown Artist"
existing_song_id = source_song_ids[i] if i < len(source_song_ids) else None
if existing_song_id is not None:
existing = db.query(LibrarySong).filter(LibrarySong.id == existing_song_id).first()
if existing:
title = existing.title or title
artist = existing.artist or artist
else:
try:
candidates = asyncio.run(identify_audio(path))
if candidates:
......@@ -365,6 +409,7 @@ def render_remix_sync(job_id: int, input_paths: list, prompt: str, filenames: li
artist = candidates[0].get("artist", artist)
except Exception as e:
logger.warning(f"identify_audio failed for song {i}, using filename as title: {e}")
songs_info.append({
"index": i, "path": path, "bpm": bpm,
"key_tonic": key["tonic"], "key_name": key["name"],
......@@ -431,7 +476,7 @@ def render_remix_sync(job_id: int, input_paths: list, prompt: str, filenames: li
stems_wanted = role.get("stems", [])
if not stems_wanted or idx not in prepared_stems:
continue
gain = 10 ** ((role.get("gain_db", 0) or 0) / 20)
gain = 10 ** (_coerce_gain_db(role.get("gain_db", 0)) / 20)
for stem_name in stems_wanted:
full = prepared_stems[idx].get(stem_name)
......@@ -494,10 +539,46 @@ def render_remix_sync(job_id: int, input_paths: list, prompt: str, filenames: li
if os.path.exists(wav_path):
os.remove(wav_path)
set_status("tagging", "Registering in library and social feed")
library_song = LibrarySong(
user_id=user_id,
title=candidate["title"],
artist=candidate["artist"],
genre=plan.get("style") if plan.get("style") and plan.get("style") != "none" else None,
file_path=download_path,
)
db.add(library_song)
db.commit()
db.refresh(library_song)
# The schema only supports one parent per post (a tree, not a DAG) - with multiple
# library-sourced inputs, only the first one's most recent post is linked. Sources
# with no existing library entry (fresh uploads) have nothing to link to.
parent_post_id = None
for sid in source_song_ids:
if sid is None:
continue
parent_post = db.query(Post).filter(Post.song_id == sid).order_by(Post.created_at.desc()).first()
if parent_post:
parent_post_id = parent_post.id
break
post = Post(
user_id=user_id,
song_id=library_song.id,
parent_post_id=parent_post_id,
caption=f"{plan.get('remix_name', 'Untitled')} - {prompt}",
)
db.add(post)
db.commit()
db.refresh(post)
job = db.query(RemixJob).filter(RemixJob.id == job_id).first()
job.status = "done"
job.stage_detail = "Complete"
job.result_filename = final_filename
job.result_song_id = library_song.id
job.result_post_id = post.id
db.commit()
except Exception as e:
......
import io
import os
import tempfile
from src.api.routers import remix as remix_router
from src.core.database import LibrarySong, SessionLocal
def _wav_bytes():
......@@ -18,9 +21,26 @@ def _wav_bytes():
return header + samples
def _make_library_song(**overrides):
fd, path = tempfile.mkstemp(suffix=".wav", dir="/tmp")
with os.fdopen(fd, "wb") as f:
f.write(_wav_bytes())
defaults = dict(title="Library Song", artist="Library Artist", file_path=path)
defaults.update(overrides)
db = SessionLocal()
try:
song = LibrarySong(**defaults)
db.add(song)
db.commit()
db.refresh(song)
return song.id, path
finally:
db.close()
def test_remix_requires_at_least_one_file(client):
response = client.post("/remix", data={"prompt": "make it slower"}, files=[])
assert response.status_code == 422
assert response.status_code == 400
def test_remix_rejects_more_than_five_songs(client, monkeypatch):
......@@ -37,11 +57,13 @@ def test_remix_does_not_call_identify_audio_before_responding(client, monkeypatc
# hang/raise instead of the fast, synchronous response below.
captured = {}
def fake_render(job_id, input_paths, prompt, filenames):
def fake_render(job_id, input_paths, prompt, filenames, source_song_ids=None, user_id=None):
captured["job_id"] = job_id
captured["input_paths"] = input_paths
captured["prompt"] = prompt
captured["filenames"] = filenames
captured["source_song_ids"] = source_song_ids
captured["user_id"] = user_id
monkeypatch.setattr(remix_router, "render_remix_sync", fake_render)
assert not hasattr(remix_router, "identify_audio"), (
......@@ -66,6 +88,92 @@ def test_remix_does_not_call_identify_audio_before_responding(client, monkeypatc
assert captured["job_id"] == job_id
assert len(captured["input_paths"]) == 2
assert captured["filenames"] == ["song_a.wav", "song_b.wav"]
assert captured["source_song_ids"] == [None, None]
assert captured["user_id"] is None
def test_remix_accepts_library_song_ids(client, monkeypatch):
song_id, path = _make_library_song()
try:
captured = {}
def fake_render(job_id, input_paths, prompt, filenames, source_song_ids=None, user_id=None):
captured["input_paths"] = input_paths
captured["filenames"] = filenames
captured["source_song_ids"] = source_song_ids
captured["user_id"] = user_id
monkeypatch.setattr(remix_router, "render_remix_sync", fake_render)
response = client.post(
"/remix",
data={"prompt": "remix this", "library_song_ids": str(song_id), "user_id": "7"},
)
assert response.status_code == 200
assert captured["input_paths"] == [path]
assert captured["filenames"] == ["Library Song"]
assert captured["source_song_ids"] == [song_id]
assert captured["user_id"] == 7
finally:
os.remove(path)
def test_remix_rejects_unknown_library_song_id(client, monkeypatch):
monkeypatch.setattr(remix_router, "render_remix_sync", lambda *a, **kw: None)
response = client.post("/remix", data={"prompt": "remix this", "library_song_ids": "999999"})
assert response.status_code == 400
def test_remix_mixes_library_songs_and_uploads(client, monkeypatch):
song_id, path = _make_library_song(title="From Library")
try:
captured = {}
def fake_render(job_id, input_paths, prompt, filenames, source_song_ids=None, user_id=None):
captured["source_song_ids"] = source_song_ids
captured["filenames"] = filenames
monkeypatch.setattr(remix_router, "render_remix_sync", fake_render)
files = [("files", ("uploaded.wav", io.BytesIO(_wav_bytes()), "audio/wav"))]
response = client.post(
"/remix",
data={"prompt": "mashup", "library_song_ids": str(song_id)},
files=files,
)
assert response.status_code == 200
assert captured["source_song_ids"] == [song_id, None]
assert captured["filenames"] == ["From Library", "uploaded.wav"]
finally:
os.remove(path)
def test_remix_status_surfaces_library_and_post_ids_when_done(client, monkeypatch):
from src.core.database import RemixJob, SessionLocal as SL
def fake_render(job_id, input_paths, prompt, filenames, source_song_ids=None, user_id=None):
db = SL()
try:
job = db.query(RemixJob).filter(RemixJob.id == job_id).first()
job.status = "done"
job.result_filename = "fake.mp3"
job.result_song_id = 123
job.result_post_id = 456
db.commit()
finally:
db.close()
monkeypatch.setattr(remix_router, "render_remix_sync", fake_render)
files = [("files", ("song.wav", io.BytesIO(_wav_bytes()), "audio/wav"))]
response = client.post("/remix", data={"prompt": "test"}, files=files)
job_id = response.json()["job_id"]
status_response = client.get(f"/remix/{job_id}")
body = status_response.json()
assert body["status"] == "done"
assert body["library_song_id"] == 123
assert body["post_id"] == 456
def test_remix_status_404_for_unknown_job(client):
......
......@@ -3,6 +3,7 @@ import os
import numpy as np
from src.services.remix_engine import (
_coerce_gain_db,
_pad_add,
_semitone_shift_to_key,
_sidechain_gain_envelope,
......@@ -11,6 +12,23 @@ from src.services.remix_engine import (
)
def test_coerce_gain_db_passes_through_numbers():
assert _coerce_gain_db(-3.0) == -3.0
assert _coerce_gain_db(0) == 0.0
def test_coerce_gain_db_averages_per_stem_dict():
# Observed live from Gemini: a per-stem breakdown instead of the single float the
# schema asks for, when a song_role lists multiple stems.
assert _coerce_gain_db({"drums": -6.0, "other": 0.0}) == -3.0
def test_coerce_gain_db_falls_back_to_zero_for_junk():
assert _coerce_gain_db(None) == 0.0
assert _coerce_gain_db("loud") == 0.0
assert _coerce_gain_db({}) == 0.0
def test_semitone_shift_same_key_is_zero():
assert _semitone_shift_to_key(3, 3) == 0
......
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