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 ...@@ -2,12 +2,12 @@ import json
import os import os
import shutil import shutil
import uuid import uuid
from typing import List from typing import List, Optional
from fastapi import APIRouter, BackgroundTasks, Depends, File, Form, HTTPException, Request, 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 LibrarySong, RemixJob, get_db
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"])
...@@ -20,21 +20,45 @@ TEMP_DIR = "/root/antigrav-stax-audio/temp" ...@@ -20,21 +20,45 @@ TEMP_DIR = "/root/antigrav-stax-audio/temp"
async def create_remix( async def create_remix(
background_tasks: BackgroundTasks, 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'"), 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), db: Session = Depends(get_db),
): ):
# Deliberately does nothing here except fast local I/O (save the uploads) - no # Deliberately does nothing here except fast local I/O (save uploads, look up library
# identify_audio/Shazam/AcoustID calls. Those are real network calls that can take # rows) - no identify_audio/Shazam/AcoustID calls. Those are real network calls that can
# ~30s each to time out, and doing them here would block this response for # 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 # potentially minutes with multiple files. All of that happens inside the background
# job instead, where it belongs alongside the rest of the slow pipeline. # job instead, where it belongs alongside the rest of the slow pipeline.
if not files: parsed_library_ids = [s.strip() for s in (library_song_ids or "").split(",") if s.strip()]
raise HTTPException(status_code=400, detail="At least one audio file is required.") total_requested = len(parsed_library_ids) + len(files)
if len(files) > MAX_SONGS: 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.") raise HTTPException(status_code=400, detail=f"At most {MAX_SONGS} songs are supported per remix.")
input_paths = [] input_paths = []
filenames = [] 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: 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}")
...@@ -42,9 +66,10 @@ async def create_remix( ...@@ -42,9 +66,10 @@ async def create_remix(
shutil.copyfileobj(f.file, buffer) shutil.copyfileobj(f.file, buffer)
input_paths.append(temp_path) input_paths.append(temp_path)
filenames.append(f.filename) filenames.append(f.filename)
source_song_ids.append(None)
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) and p.startswith(TEMP_DIR):
os.remove(p) os.remove(p)
raise HTTPException(status_code=500, detail=f"Failed to receive uploaded files: {e}") raise HTTPException(status_code=500, detail=f"Failed to receive uploaded files: {e}")
...@@ -53,7 +78,7 @@ async def create_remix( ...@@ -53,7 +78,7 @@ 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, 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}"} 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( ...@@ -74,6 +99,8 @@ async def get_remix_status(job_id: int, request: Request, db: Session = Depends(
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"{str(request.base_url).rstrip('/')}/downloads/{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": if job.status == "error":
response["error"] = job.error response["error"] = job.error
......
...@@ -114,12 +114,41 @@ class RemixJob(Base): ...@@ -114,12 +114,41 @@ class RemixJob(Base):
plan_json = Column(String, nullable=True) # the AI-generated remix plan, once produced plan_json = Column(String, nullable=True) # the AI-generated remix plan, once produced
remix_name = Column(String, nullable=True) remix_name = Column(String, nullable=True)
result_filename = 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) error = Column(String, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) 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)) updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
Base.metadata.create_all(bind=engine) 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(): def get_db():
db = SessionLocal() db = SessionLocal()
try: try:
......
This diff is collapsed.
import io import io
import os
import tempfile
from src.api.routers import remix as remix_router from src.api.routers import remix as remix_router
from src.core.database import LibrarySong, SessionLocal
def _wav_bytes(): def _wav_bytes():
...@@ -18,9 +21,26 @@ def _wav_bytes(): ...@@ -18,9 +21,26 @@ def _wav_bytes():
return header + samples 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): def test_remix_requires_at_least_one_file(client):
response = client.post("/remix", data={"prompt": "make it slower"}, files=[]) 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): 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 ...@@ -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. # hang/raise instead of the fast, synchronous response below.
captured = {} 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["job_id"] = job_id
captured["input_paths"] = input_paths captured["input_paths"] = input_paths
captured["prompt"] = prompt captured["prompt"] = prompt
captured["filenames"] = filenames captured["filenames"] = filenames
captured["source_song_ids"] = source_song_ids
captured["user_id"] = user_id
monkeypatch.setattr(remix_router, "render_remix_sync", fake_render) monkeypatch.setattr(remix_router, "render_remix_sync", fake_render)
assert not hasattr(remix_router, "identify_audio"), ( assert not hasattr(remix_router, "identify_audio"), (
...@@ -66,6 +88,92 @@ def test_remix_does_not_call_identify_audio_before_responding(client, monkeypatc ...@@ -66,6 +88,92 @@ def test_remix_does_not_call_identify_audio_before_responding(client, monkeypatc
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 captured["filenames"] == ["song_a.wav", "song_b.wav"] 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): def test_remix_status_404_for_unknown_job(client):
......
...@@ -3,6 +3,7 @@ import os ...@@ -3,6 +3,7 @@ import os
import numpy as np import numpy as np
from src.services.remix_engine import ( from src.services.remix_engine import (
_coerce_gain_db,
_pad_add, _pad_add,
_semitone_shift_to_key, _semitone_shift_to_key,
_sidechain_gain_envelope, _sidechain_gain_envelope,
...@@ -11,6 +12,23 @@ from src.services.remix_engine import ( ...@@ -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(): def test_semitone_shift_same_key_is_zero():
assert _semitone_shift_to_key(3, 3) == 0 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