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():
......
import asyncio
import hashlib
import json
import os
import shutil
import google.generativeai as genai
import librosa
import numpy as np
import soundfile as sf
import torch
from pedalboard import Compressor, Pedalboard, PitchShift, Reverb
from src.core.config import GEMINI_API_KEY, logger
from src.core.database import RemixJob, SessionLocal
# 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
# convolutions (a tiny toy conv works fine, which is what makes this easy to miss). Disabling
# MKLDNN falls back to PyTorch's plain conv kernels, which are slower but actually run here.
torch.backends.mkldnn.enabled = False
if GEMINI_API_KEY:
genai.configure(api_key=GEMINI_API_KEY)
STEM_CACHE_DIR = "/root/antigrav-stax-audio/stem_cache"
REMIX_TEMP_DIR = "/root/antigrav-stax-audio/temp"
DOWNLOADS_DIR = "/root/antigrav-stax-audio/downloads"
STEM_NAMES = ["vocals", "drums", "bass", "other"]
os.makedirs(STEM_CACHE_DIR, exist_ok=True)
def _file_hash(file_path: str) -> str:
h = hashlib.sha256()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()[:24]
def separate_stems(file_path: str) -> dict:
"""Runs Demucs source separation, caching results by file content hash so the
same song is never separated twice."""
key = _file_hash(file_path)
cache_dir = os.path.join(STEM_CACHE_DIR, key)
stem_paths = {name: os.path.join(cache_dir, f"{name}.wav") for name in STEM_NAMES}
if all(os.path.exists(p) for p in stem_paths.values()):
return stem_paths
os.makedirs(cache_dir, exist_ok=True)
from demucs.api import Separator
separator = Separator(model="htdemucs")
_, separated = separator.separate_audio_file(file_path)
for name, tensor in separated.items():
audio = tensor.numpy().T # (channels, samples) -> (samples, channels)
sf.write(stem_paths[name], audio, separator.samplerate)
return stem_paths
def detect_bpm(file_path: str) -> float:
y, sr = librosa.load(file_path, sr=None, mono=True, duration=60)
tempo, _ = librosa.beat.beat_track(y=y, sr=sr)
tempo = float(tempo)
return tempo if 40 < tempo < 220 else 120.0
def _make_audio_preview_part(file_path: str, seconds: int = 25) -> dict:
"""Trims a short preview of the track and returns it as a Gemini inline audio part,
so the model can actually hear mood/energy/instrumentation rather than guessing from
text metadata alone."""
y, sr = librosa.load(file_path, sr=22050, mono=True, duration=seconds)
preview_path = file_path + ".preview.wav"
sf.write(preview_path, y, sr)
with open(preview_path, "rb") as f:
data = f.read()
os.remove(preview_path)
return {"mime_type": "audio/wav", "data": data}
async def plan_remix(prompt: str, songs_info: list) -> dict:
"""Asks Gemini to turn a natural-language prompt + real per-song audio/BPM data into a
structured, executable remix plan: which stems to pull from which song, at what gain,
the shared target tempo, and the master effects chain."""
if not GEMINI_API_KEY:
raise Exception("GEMINI_API_KEY not configured.")
model = genai.GenerativeModel(
"gemini-2.5-flash", generation_config={"response_mime_type": "application/json"}
)
song_lines = []
parts = []
for info in songs_info:
song_lines.append(
f"- Song index {info['index']}: \"{info['title']}\" by {info['artist']} "
f"(genre: {info.get('genre', 'unknown')}, detected BPM: {info['bpm']:.1f})"
)
parts.append(_make_audio_preview_part(info["path"]))
instructions = f"""
You are an expert remix producer and audio engineer directing a real stem-based remix
engine. You have been given {len(songs_info)} song(s) as audio previews (in the order
listed below) plus their detected tempo, and a user's natural-language request.
Songs:
{os.linesep.join(song_lines)}
User's request: "{prompt}"
Each song has already been split into 4 real isolated stems: vocals, drums, bass, other
(harmony/instrumentation). Your job is to decide, for each song, which of its stems to
include in the final mix and at what relative gain, plus a single shared target BPM that
all included stems will be time-stretched to, plus a final mastering effects chain.
Typical patterns: a "mashup" pulls vocals from one song over drums/bass/other from
another. A "remix" of a single song might drop the vocals to make an instrumental version,
or add reverb/pitch shift for a slowed-and-reverb style. Use your judgment based on the
request and what you hear in the previews.
Return a JSON object strictly following this schema:
{{
"remix_name": str (a short 2-4 word creative title for this remix, do NOT include the word 'remix'),
"target_bpm": float (the shared tempo everything will be stretched to; usually close to one of the input songs' detected BPM),
"song_roles": [
{{
"index": int (matches the song index above),
"stems": [str] (subset of "vocals", "drums", "bass", "other" to include from this song; can be empty if this song contributes nothing),
"gain_db": float (relative gain adjustment for this song's contribution, typically -6 to 3),
"pitch_shift_semitones": int (per-song pitch adjustment before mixing, typically -12 to 12, usually 0)
}}
],
"master_effects": {{
"reverb_room_size": float (0.0 to 1.0),
"compressor_threshold_db": float (typically -20 to -6),
"compressor_ratio": float (typically 1.5 to 6)
}}
}}
"""
parts.append(instructions)
response = await asyncio.to_thread(model.generate_content, parts)
plan = json.loads(response.text)
valid_indices = {info["index"] for info in songs_info}
for role in plan.get("song_roles", []):
role["stems"] = [s for s in role.get("stems", []) if s in STEM_NAMES]
plan["song_roles"] = [r for r in plan.get("song_roles", []) if r.get("index") in valid_indices]
return plan
def _time_stretch_to_bpm(audio: np.ndarray, sr: int, current_bpm: float, target_bpm: float) -> np.ndarray:
if current_bpm <= 0 or abs(current_bpm - target_bpm) < 0.5:
return audio
rate = target_bpm / current_bpm
if audio.ndim == 1:
return librosa.effects.time_stretch(audio, rate=rate)
return np.stack([librosa.effects.time_stretch(np.ascontiguousarray(ch), rate=rate) for ch in audio])
def _load_mono(path: str, sr: int) -> np.ndarray:
y, _ = librosa.load(path, sr=sr, mono=True)
return y
def render_remix_sync(job_id: int, input_paths: list, prompt: str, songs_meta: list):
"""The full synchronous remix pipeline: plan -> separate -> time-stretch -> mix -> master
-> tag. Runs in a worker thread via FastAPI's BackgroundTasks; updates the RemixJob row
in the DB as it progresses so clients can poll status."""
db = SessionLocal()
def set_status(status: str, detail: str = None):
job = db.query(RemixJob).filter(RemixJob.id == job_id).first()
job.status = status
if detail is not None:
job.stage_detail = detail
db.commit()
try:
set_status("planning", "Detecting tempo for each song")
target_sr = 44100
songs_info = []
for i, path in enumerate(input_paths):
bpm = detect_bpm(path)
meta = songs_meta[i] if i < len(songs_meta) else {}
songs_info.append({
"index": i,
"path": path,
"bpm": bpm,
"title": meta.get("title", f"Track {i + 1}"),
"artist": meta.get("artist", "Unknown Artist"),
"genre": meta.get("genre", "Unknown"),
})
set_status("planning", "Asking Gemini for a remix plan")
plan = asyncio.run(plan_remix(prompt, songs_info))
job = db.query(RemixJob).filter(RemixJob.id == job_id).first()
job.plan_json = json.dumps(plan)
job.remix_name = plan.get("remix_name", "Untitled")
db.commit()
target_bpm = float(plan.get("target_bpm") or songs_info[0]["bpm"])
set_status("separating", "Running stem separation (this is the slow part)")
mix_len = 0
stem_tracks = []
for role in plan.get("song_roles", []):
idx = role["index"]
info = songs_info[idx]
stems_wanted = role.get("stems", [])
if not stems_wanted:
continue
stem_paths = separate_stems(info["path"])
combined = None
for stem_name in stems_wanted:
y = _load_mono(stem_paths[stem_name], target_sr)
combined = y if combined is None else _pad_add(combined, y)
if combined is None:
continue
combined = _time_stretch_to_bpm(combined, target_sr, info["bpm"], target_bpm)
pitch_shift = role.get("pitch_shift_semitones", 0) or 0
gain_db = role.get("gain_db", 0) or 0
board = Pedalboard(([PitchShift(semitones=pitch_shift)] if pitch_shift else []))
if len(board) > 0:
combined = board(combined.astype(np.float32), target_sr)
combined = combined[0] if combined.ndim > 1 else combined
combined = combined * (10 ** (gain_db / 20))
stem_tracks.append(combined)
mix_len = max(mix_len, len(combined))
if not stem_tracks:
raise Exception("The remix plan didn't select any stems from any song.")
set_status("mixing", "Combining stems into the final mix")
mix = np.zeros(mix_len, dtype=np.float32)
for track in stem_tracks:
mix = _pad_add(mix, track)
peak = np.max(np.abs(mix)) or 1.0
if peak > 0.98:
mix = mix / peak * 0.98
set_status("mastering", "Applying master effects chain")
effects = plan.get("master_effects", {})
board = Pedalboard([
Compressor(
threshold_db=effects.get("compressor_threshold_db", -14),
ratio=effects.get("compressor_ratio", 3),
),
Reverb(room_size=effects.get("reverb_room_size", 0.15)),
])
mastered = board(mix, target_sr)
set_status("tagging", "Writing final MP3 and tags")
wav_path = os.path.join(REMIX_TEMP_DIR, f"remix_{job_id}.wav")
sf.write(wav_path, mastered, target_sr)
title_bits = " x ".join(s["title"] for s in songs_info)
candidate = {
"title": f"{plan.get('remix_name', 'Untitled')} ({title_bits})",
"artist": " + ".join(sorted({s['artist'] for s in songs_info})) + " (Stax AI Remix)",
}
from src.services.audio_processing import tag_and_convert_audio
final_local_name = asyncio.run(tag_and_convert_audio(wav_path, candidate))
final_filename = os.path.basename(final_local_name)
download_path = os.path.join(DOWNLOADS_DIR, final_filename)
shutil.move(final_local_name, download_path)
if os.path.exists(wav_path):
os.remove(wav_path)
job = db.query(RemixJob).filter(RemixJob.id == job_id).first()
job.status = "done"
job.stage_detail = "Complete"
job.result_filename = final_filename
db.commit()
except Exception as e:
logger.error(f"Remix job {job_id} failed: {e}")
job = db.query(RemixJob).filter(RemixJob.id == job_id).first()
if job:
job.status = "error"
job.error = str(e)
db.commit()
finally:
db.close()
def _pad_add(a: np.ndarray, b: np.ndarray) -> np.ndarray:
if len(a) < len(b):
a = np.pad(a, (0, len(b) - len(a)))
elif len(b) < len(a):
b = np.pad(b, (0, len(a) - len(b)))
return a + b
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