Commit f02cc53e authored by Aryan Noshirvani's avatar Aryan Noshirvani

Add real multi-song AI remix engine

New POST /remix + GET /remix/{job_id}: takes 1-5 uploaded songs plus a
natural-language prompt, runs it as a background job (RemixJob table
tracks status/stage as it progresses), and returns a download URL when
done. Pipeline:

  1. Detect each song's BPM (librosa) and grab quick metadata via the
     existing Shazam/AcoustID identify_audio.
  2. Ask Gemini to produce a structured remix plan - it hears a real
     ~25s preview of each song (not just title/artist text) plus the
     detected BPMs, and returns which stems to pull from which song,
     at what gain/pitch, a shared target BPM, and a master effects
     chain. This replaces the old ai_remix.py's approach of faking
     "stem separation" with a sox highpass filter while literally
     telling the AI it was using Demucs.
  3. Actually run Demucs (real 4-stem separation: vocals/drums/bass/
     other), cached on disk by file content hash so re-remixing the
     same song never reprocesses it.
  4. Time-stretch selected stems to the shared target BPM (librosa
     phase vocoder), mix with per-song gain/pitch-shift, master with
     a pedalboard compressor + reverb chain, tag and export via the
     existing tag_and_convert_audio.

Removes the old /music/remix/batch and /music/remix/status mock stubs
in music.py (hardcoded fake job ids/progress) now that the real thing
exists at /remix.

This VPS's virtualized CPU exposes no SSE3/SSE4/AVX at all, which
makes PyTorch's default oneDNN backend fail ("could not create a
primitive") on Demucs's real-sized convolutions - a tiny toy conv
works fine, which is what makes this easy to miss in isolation.
torch.backends.mkldnn.enabled = False works around it. Also: Gemini
calls need this box's HTTP(S)_PROXY set to reach the network at all
(confirmed the already-running main branch's stax_backend.service has
the same gap and is likely silently failing on Gemini calls in
production right now - flagging separately, out of scope here).

numpy is pinned <2 / scipy pinned to 1.13.1: numpy>=2's default wheels
require the x86-64-v2 baseline and RuntimeError on import on this CPU.

Tested end-to-end against two synthetic multi-tone MP3s: single-song
"drop the vocals, slowed + reverb" and two-song "blend vocals of one
over the drums of the other" both produced correct, tagged, playable
MP3s (~75s for the two-song case, ~3s when stems were already cached).
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BCxXmJVvDFJVHTUi4QgNzi
parent 8d52510f
......@@ -16,3 +16,15 @@ python-multipart>=0.0.9
pytest>=8.0.0
pyrogram>=2.0.106
tgcrypto>=1.2.5
# Remix engine. Install torch CPU-only *before* this file, this VPS has no GPU:
# pip install torch --index-url https://download.pytorch.org/whl/cpu
# Otherwise pip pulls the default CUDA wheel (multiple GB, useless here).
# numpy is pinned <2: this VPS's virtualized CPU exposes no SSE3/SSE4/AVX at all,
# and numpy>=2's default wheels require the x86-64-v2 baseline and segfault/RuntimeError
# on import here. 1.26.4 is what the rest of this project already runs on successfully.
numpy==1.26.4
scipy==1.13.1
demucs>=4.0.1
librosa>=0.10.2
soundfile>=0.12.1
......@@ -2,7 +2,6 @@ import os
import shutil
import uuid
import urllib.parse
from typing import List
import asyncio
import google.generativeai as genai
......@@ -24,14 +23,6 @@ class TagResponse(BaseModel):
download_url: str
metadata: dict
class FileToRemix(BaseModel):
chat_id: int
message_id: int
class RemixBatchRequest(BaseModel):
files: List[FileToRemix]
prompt: str
@router.post("/tag", response_model=TagResponse)
async def tag_music(req: TagRequest):
return {
......@@ -45,14 +36,6 @@ async def tag_music(req: TagRequest):
}
}
@router.post("/remix/batch")
async def batch_remix(req: RemixBatchRequest):
return {"status": "accepted", "job_id": "mock_job_12345", "message": "Batch remix job accepted and processing in background."}
@router.get("/remix/status/{job_id}")
async def batch_remix_status(job_id: str):
return {"status": "processing", "job_id": job_id, "progress": 45, "message": "Applying AI crossfades..."}
@router.post("/upload", response_model=TagResponse)
async def upload_direct(file: UploadFile = File(...)):
temp_filename = f"/root/antigrav-stax-audio/temp/{uuid.uuid4()}_{file.filename}"
......
import json
import os
import shutil
import uuid
from typing import List
from fastapi import APIRouter, BackgroundTasks, Depends, File, Form, HTTPException, UploadFile
from sqlalchemy.orm import Session
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
router = APIRouter(prefix="/remix", tags=["AI Remix"])
MAX_SONGS = 5
TEMP_DIR = "/root/antigrav-stax-audio/temp"
DOWNLOAD_HOST = "http://91.234.52.134:8001"
@router.post("")
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"),
db: Session = Depends(get_db),
):
if not files:
raise HTTPException(status_code=400, detail="At least one audio file is required.")
if len(files) > MAX_SONGS:
raise HTTPException(status_code=400, detail=f"At most {MAX_SONGS} songs are supported per remix.")
input_paths = []
songs_meta = []
try:
for f in files:
temp_path = os.path.join(TEMP_DIR, f"{uuid.uuid4()}_{f.filename}")
with open(temp_path, "wb") as buffer:
shutil.copyfileobj(f.file, buffer)
input_paths.append(temp_path)
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:
for p in input_paths:
if os.path.exists(p):
os.remove(p)
raise HTTPException(status_code=500, detail=f"Failed to receive uploaded files: {e}")
job = RemixJob(status="queued", prompt=prompt, input_paths=json.dumps(input_paths))
db.add(job)
db.commit()
db.refresh(job)
background_tasks.add_task(render_remix_sync, job.id, input_paths, prompt, songs_meta)
return {"job_id": job.id, "status": job.status, "status_url": f"/remix/{job.id}"}
@router.get("/{job_id}")
async def get_remix_status(job_id: int, db: Session = Depends(get_db)):
job = db.query(RemixJob).filter(RemixJob.id == job_id).first()
if not job:
raise HTTPException(status_code=404, detail="Remix job not found.")
response = {
"job_id": job.id,
"status": job.status,
"stage_detail": job.stage_detail,
"remix_name": job.remix_name,
}
if job.plan_json:
response["plan"] = json.loads(job.plan_json)
if job.status == "done" and job.result_filename:
response["download_url"] = f"{DOWNLOAD_HOST}/downloads/{job.result_filename}"
if job.status == "error":
response["error"] = job.error
return response
......@@ -95,6 +95,20 @@ class LiveRoom(Base):
is_active = Column(Boolean, default=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class RemixJob(Base):
__tablename__ = "remix_jobs"
id = Column(Integer, primary_key=True, index=True)
status = Column(String, default="queued") # queued, planning, separating, mixing, mastering, tagging, done, error
stage_detail = Column(String, nullable=True)
prompt = Column(String)
input_paths = Column(String) # JSON-encoded list of source file paths
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)
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 get_db():
......
This diff is collapsed.
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