Commit b2ed559a authored by Aryan Noshirvani's avatar Aryan Noshirvani

Drop Claude, refine back to a single Gemini call

Per direction: no Claude. Merged the two-step Gemini-describes/Claude-
plans pipeline back into one Gemini call that both listens to every
song's real audio preview and produces the full structured plan
(sections, target key, sidechain, style) directly - simpler than two
model calls, and the audio-perception advantage that motivated the
two-step design in the first place only mattered when comparing
against a text-only Claude call anyway.

Tried gemini-2.5-pro for better reasoning first (background job, can
absorb the latency) - live 429 confirmed this API key's free tier has
a hard zero quota for -pro ("limit: 0", not exhausted), so reverted to
gemini-2.5-flash, which the rest of this app already runs on
successfully. Removed the anthropic dependency and ANTHROPIC_API_KEY
entirely rather than leaving unused Claude plumbing around.

Verified end-to-end against the real API: a "house remix with a big
sidechain pump and a proper build-drop structure" request produced 5
real sections (intro/build/drop/breakdown/outro) with genuinely
different stems active per section, sidechain enabled and targeting
the correct song's drums, style set to house, and a valid ~9s tagged
MP3 out the other end.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BCxXmJVvDFJVHTUi4QgNzi
parent 7c856954
Pipeline #997 passed with stage
in 12 minutes and 53 seconds
...@@ -2,10 +2,6 @@ TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here ...@@ -2,10 +2,6 @@ TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
ACOUSTID_API_KEY=your_acoustid_api_key_here ACOUSTID_API_KEY=your_acoustid_api_key_here
GEMINI_API_KEY=your_gemini_api_key_here GEMINI_API_KEY=your_gemini_api_key_here
# Used by the remix engine's planning step (src/services/remix_engine.py plan_remix) -
# Claude reasons about the user's prompt and produces the structured arrangement plan.
ANTHROPIC_API_KEY=your_anthropic_api_key_here
# Optional, used by src/telegram_bot (stem separation feature) # Optional, used by src/telegram_bot (stem separation feature)
LALAL_API_KEY=your_lalal_api_key_here LALAL_API_KEY=your_lalal_api_key_here
......
...@@ -7,7 +7,6 @@ syncedlyrics==1.0.1 ...@@ -7,7 +7,6 @@ syncedlyrics==1.0.1
pyacoustid==1.3.0 pyacoustid==1.3.0
musicbrainzngs==0.7.1 musicbrainzngs==0.7.1
google-generativeai==0.8.3 google-generativeai==0.8.3
anthropic>=0.40.0
pedalboard==0.9.8 pedalboard==0.9.8
fastapi>=0.110.0 fastapi>=0.110.0
uvicorn>=0.28.0 uvicorn>=0.28.0
......
...@@ -260,7 +260,7 @@ ...@@ -260,7 +260,7 @@
<section id="remix-section"> <section id="remix-section">
<h2>🎛 AI Remix</h2> <h2>🎛 AI Remix</h2>
<p class="desc">Upload 1&ndash;5 songs and describe the remix in plain language. Gemini listens to each track, Claude directs the arrangement (sections, harmonic key matching, sidechain, style), and Demucs does the actual stem separation before rendering.</p> <p class="desc">Upload 1&ndash;5 songs and describe the remix in plain language. Gemini listens to each track and directs the arrangement (sections, harmonic key matching, sidechain, style), and Demucs does the actual stem separation before rendering.</p>
<div class="dropzone" id="remix-drop"> <div class="dropzone" id="remix-drop">
Drop up to 5 audio files here, or click to choose Drop up to 5 audio files here, or click to choose
......
...@@ -8,7 +8,6 @@ load_dotenv() ...@@ -8,7 +8,6 @@ load_dotenv()
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN") TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
ACOUSTID_API_KEY = os.getenv("ACOUSTID_API_KEY", "8XaBELgH") ACOUSTID_API_KEY = os.getenv("ACOUSTID_API_KEY", "8XaBELgH")
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
LALAL_API_KEY = os.getenv("LALAL_API_KEY") LALAL_API_KEY = os.getenv("LALAL_API_KEY")
# Gate for the interactive API docs (/docs, /openapi.json) - HTTP Basic Auth. # Gate for the interactive API docs (/docs, /openapi.json) - HTTP Basic Auth.
......
...@@ -5,7 +5,6 @@ import os ...@@ -5,7 +5,6 @@ import os
import shutil import shutil
import threading import threading
import anthropic
import google.generativeai as genai import google.generativeai as genai
import librosa import librosa
import numpy as np import numpy as np
...@@ -23,7 +22,7 @@ from pedalboard import ( ...@@ -23,7 +22,7 @@ from pedalboard import (
) )
from scipy.signal import butter, filtfilt from scipy.signal import butter, filtfilt
from src.core.config import ANTHROPIC_API_KEY, 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 from src.services.music_identification import identify_audio
...@@ -36,8 +35,6 @@ torch.backends.mkldnn.enabled = False ...@@ -36,8 +35,6 @@ torch.backends.mkldnn.enabled = False
if GEMINI_API_KEY: if GEMINI_API_KEY:
genai.configure(api_key=GEMINI_API_KEY) genai.configure(api_key=GEMINI_API_KEY)
anthropic_client = anthropic.Anthropic(api_key=ANTHROPIC_API_KEY) if ANTHROPIC_API_KEY else None
STEM_CACHE_DIR = "/root/antigrav-stax-audio/stem_cache" STEM_CACHE_DIR = "/root/antigrav-stax-audio/stem_cache"
REMIX_TEMP_DIR = "/root/antigrav-stax-audio/temp" REMIX_TEMP_DIR = "/root/antigrav-stax-audio/temp"
DOWNLOADS_DIR = "/root/antigrav-stax-audio/downloads" DOWNLOADS_DIR = "/root/antigrav-stax-audio/downloads"
...@@ -168,54 +165,43 @@ def _make_audio_preview_part(file_path: str, seconds: int = 25) -> dict: ...@@ -168,54 +165,43 @@ def _make_audio_preview_part(file_path: str, seconds: int = 25) -> dict:
return {"mime_type": "audio/wav", "data": data} return {"mime_type": "audio/wav", "data": data}
async def describe_song_audio(file_path: str, title: str, artist: str, bpm: float, key_name: str) -> str: async def plan_remix(prompt: str, songs_info: list) -> dict:
"""Gemini listens to a real preview and writes a text description of what's actually in """Gemini listens to a real audio preview of every song plus real detected BPM/key data,
the track. This description - not raw audio - is what gets handed to Claude, since and produces the full executable plan in one call: a sectioned arrangement, harmonic
Claude's API can't take audio input.""" pitch target, sidechain routing, and a style preset - not just "pick some stems and slap
reverb on it".
gemini-2.5-pro would reason about structure better than flash, but this API key's free
tier has a hard zero quota for -pro (confirmed via a live 429: "limit: 0" - not
exhausted, actually zero allocation), so flash is what's actually usable here. The
"refinement" is in the prompt itself: real audio previews of every song, real detected
BPM/key data instead of guesses, and an explicit schema for structure/harmony/sidechain/
style that flash is quite capable of following even if it reasons less deeply than pro
would."""
if not GEMINI_API_KEY: if not GEMINI_API_KEY:
return f'"{title}" by {artist}, {bpm:.0f} BPM, key of {key_name}. (No audio description available - GEMINI_API_KEY not configured.)' raise Exception("GEMINI_API_KEY not configured.")
model = genai.GenerativeModel("gemini-2.5-flash")
audio_part = _make_audio_preview_part(file_path)
prompt = f"""
Listen to this ~25 second preview of "{title}" by {artist} (detected tempo {bpm:.0f} BPM,
detected key {key_name}). In 3-5 concrete sentences, describe: the overall mood/energy,
what the vocals sound like and what they're doing (if any vocals are present), the
prominent instrumentation and rhythmic feel, and any distinctive sonic characteristics a
remix producer would want to know about before deciding what to sample from this track.
Be specific and concrete, not generic - a producer is going to make real decisions based
on what you say.
"""
try:
response = await asyncio.to_thread(model.generate_content, [audio_part, prompt])
return response.text.strip()
except Exception as e:
logger.warning(f"describe_song_audio failed for {title}: {e}")
return f'"{title}" by {artist}, {bpm:.0f} BPM, key of {key_name}. (Audio description unavailable: {e})'
async def plan_remix(prompt: str, songs_info: list) -> dict: model = genai.GenerativeModel(
"""Claude takes the Gemini-generated descriptions, real BPM/key data, and the user's "gemini-2.5-flash", generation_config={"response_mime_type": "application/json"}
request, and produces the full executable plan: a sectioned arrangement, harmonic pitch )
targets, sidechain routing, and a style preset - not just "pick some stems and slap
reverb on it"."""
if not anthropic_client:
raise Exception("ANTHROPIC_API_KEY not configured.")
song_lines = [] song_lines = []
parts = []
for info in songs_info: for info in songs_info:
song_lines.append( song_lines.append(
f'Song {info["index"]}: "{info["title"]}" by {info["artist"]} - ' f'Song {info["index"]}: "{info["title"]}" by {info["artist"]} - '
f'{info["bpm"]:.0f} BPM, key of {info["key_name"]}.\n' f'{info["bpm"]:.0f} BPM, detected key {info["key_name"]}.'
f'What it sounds like: {info["description"]}'
) )
parts.append(_make_audio_preview_part(info["path"]))
instructions = f"""You are directing a real stem-based remix engine - every decision you make here gets executed literally by DSP code, not summarized or reinterpreted. Take the request seriously and commit to it structurally, not just with a reverb tail at the end.
instructions = f"""You are directing a real stem-based remix engine - every decision you make here gets executed literally by DSP code, not summarized or reinterpreted. Take the request seriously and commit to it structurally. You've been given {len(songs_info)} song(s) as real audio previews (in the order listed below, alongside their detected tempo and key), plus a user's natural-language request. Listen to each one before deciding anything - the mood, energy, vocal character, and instrumentation you actually hear should drive your choices, not just the title/artist text.
You have {len(songs_info)} song(s), each already split into 4 isolated stems: vocals, drums, bass, other (harmony/instrumentation). The engine can: Each song has already been split into 4 isolated stems: vocals, drums, bass, other (harmony/instrumentation). The engine can:
- Include/exclude any stem from any song, at any gain, in any section. - Include/exclude any stem from any song, at any gain, in any section.
- Time-stretch everything to one shared target BPM. - Time-stretch everything to one shared target BPM.
- Pitch-shift each song by a whole number of semitones to harmonically match a shared target key (the engine computes the exact semitone value from real detected keys - you only choose which detected key to target). - Pitch-shift each song by a whole number of semitones to harmonically match a shared target key (the engine computes the exact semitone value from the real detected keys above - you only choose which detected key to target).
- Apply sidechain ducking: one song's drums stem can rhythmically duck the volume of everything else - the "pump" that makes a mix groove. Use this when it fits the request (e.g. anything upbeat/electronic/danceable), not by default. - Apply sidechain ducking: one song's drums stem can rhythmically duck the volume of everything else - the "pump" that makes a mix groove. Use this when it fits the request (e.g. anything upbeat/electronic/danceable), not by default.
- Render distinct SECTIONS across the timeline (e.g. intro / build / drop / breakdown / outro), each with a different combination of active stems - this is what makes the result an actual arrangement instead of every stem playing for the whole duration. Use at least 2 sections for anything but the simplest single-song requests. - Render distinct SECTIONS across the timeline (e.g. intro / build / drop / breakdown / outro), each with a different combination of active stems - this is what makes the result an actual arrangement instead of every stem playing for the whole duration. Use at least 2 sections for anything but the simplest single-song requests.
- Apply a named style preset that shapes the final tone: "lofi" (filtered, warm, saturated), "trap" (heavy low end, punchy), "house" (clean, driving), or "none". - Apply a named style preset that shapes the final tone: "lofi" (filtered, warm, saturated), "trap" (heavy low end, punchy), "house" (clean, driving), or "none".
...@@ -227,7 +213,7 @@ User's request: "{prompt}" ...@@ -227,7 +213,7 @@ User's request: "{prompt}"
If they ask for a specific genre/style, pick sections, stems, sidechain, and the style preset that actually reads as that genre - don't just rely on the style preset alone to do all the work. If they ask for a mashup, make sure both songs meaningfully contribute across different sections rather than one being wallpaper under the other's vocal for the whole duration. If they ask for a specific genre/style, pick sections, stems, sidechain, and the style preset that actually reads as that genre - don't just rely on the style preset alone to do all the work. If they ask for a mashup, make sure both songs meaningfully contribute across different sections rather than one being wallpaper under the other's vocal for the whole duration.
Return ONLY a JSON object, no other text, strictly following this schema: Return a JSON object strictly following this schema:
{{ {{
"remix_name": str (2-4 word creative title, do NOT include the word "remix"), "remix_name": str (2-4 word creative title, do NOT include the word "remix"),
"target_bpm": float, "target_bpm": float,
...@@ -253,18 +239,9 @@ Return ONLY a JSON object, no other text, strictly following this schema: ...@@ -253,18 +239,9 @@ Return ONLY a JSON object, no other text, 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.""" 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."""
response = await asyncio.to_thread( parts.append(instructions)
anthropic_client.messages.create, response = await asyncio.to_thread(model.generate_content, parts)
model="claude-sonnet-5", plan = json.loads(response.text)
max_tokens=2000,
messages=[{"role": "user", "content": instructions}],
)
text = response.content[0].text.strip()
if text.startswith("```"):
text = text.strip("`")
if text.startswith("json"):
text = text[4:]
plan = json.loads(text.strip())
valid_indices = {info["index"] for info in songs_info} valid_indices = {info["index"] for info in songs_info}
for section in plan.get("sections", []): for section in plan.get("sections", []):
...@@ -355,9 +332,10 @@ def _apply_style_preset(audio: np.ndarray, sr: int, style: str) -> np.ndarray: ...@@ -355,9 +332,10 @@ def _apply_style_preset(audio: np.ndarray, sr: int, style: str) -> np.ndarray:
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
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):
"""The full remix pipeline: identify -> detect BPM/key -> describe (Gemini) -> plan """The full remix pipeline: identify -> detect BPM/key -> plan (Gemini, listens to real
(Claude) -> separate (Demucs) -> stretch/pitch-match each stem once -> render each audio previews and directs the whole arrangement) -> separate (Demucs) -> stretch/
section of the arrangement -> sidechain -> style preset -> master -> tag. pitch-match each stem once -> render each section of the arrangement -> sidechain ->
style preset -> master -> tag.
Runs in a worker thread via FastAPI's BackgroundTasks; updates the RemixJob row in the 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 DB as it progresses so clients can poll status. identify_audio and the AI calls run here
...@@ -393,13 +371,7 @@ def render_remix_sync(job_id: int, input_paths: list, prompt: str, filenames: li ...@@ -393,13 +371,7 @@ def render_remix_sync(job_id: int, input_paths: list, prompt: str, filenames: li
"title": title, "artist": artist, "title": title, "artist": artist,
}) })
set_status("planning", "Listening to each song (Gemini)") set_status("planning", "Listening to each song and directing the arrangement (Gemini)")
for info in songs_info:
info["description"] = asyncio.run(
describe_song_audio(info["path"], info["title"], info["artist"], info["bpm"], info["key_name"])
)
set_status("planning", "Directing the arrangement (Claude)")
plan = asyncio.run(plan_remix(prompt, songs_info)) plan = asyncio.run(plan_remix(prompt, songs_info))
job = db.query(RemixJob).filter(RemixJob.id == job_id).first() job = db.query(RemixJob).filter(RemixJob.id == job_id).first()
......
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