Commit b1eab28c authored by Aryan Noshirvani's avatar Aryan Noshirvani

Real creative transformation: key matching, sections, sidechain, style

The old engine picked stems and slapped a static reverb+compressor on
top for the full duration - "change pitch and speed and call it a
day," per the ask. This is a genuine rewrite of the DSP core:

- Real key detection (Krumhansl-Kessler chroma-profile correlation)
  replaces AI-guessed pitch shifts. Semitone shifts are now computed
  from actual detected keys, so combined stems from different songs
  are harmonically correct instead of an arbitrary number the model
  picked with no data behind it.
- Section-based arrangement: the plan now describes real structure
  (intro/build/drop/etc.) with different stems active per section
  instead of one static combination playing for the whole duration.
  Every stem is stretched/pitch-matched once and cached in memory;
  sections slice and sum from that shared pool with short crossfades
  at boundaries.
- Sidechain ducking: one song's drums can rhythmically duck everything
  else (the "pump" that makes a mix actually groove), via a vectorized
  lowpass-filtered envelope follower - not a per-sample Python loop,
  which would be far too slow on this CPU's unaccelerated math.
- Style presets (lofi/trap/house) apply genre-appropriate processing
  chains instead of one generic effects chain for every request.

Two-step AI pipeline, split by what each model actually can/can't do:
Gemini listens to a real audio preview of each song and writes a text
description (mood, energy, instrumentation) - Claude's API has no
audio input at all, so this is the only way it gets that context.
Claude then takes those descriptions plus real BPM/key data and the
user's prompt and directs the actual arrangement: sections, target
key, sidechain routing, style. Perception on Gemini, instruction-
following and structured reasoning on Claude - not asking one model
to do both.

Needs ANTHROPIC_API_KEY to actually run plan_remix - not yet set in
this environment, so the full pipeline is implemented and unit-tested
but not yet verified end-to-end. All DSP pieces (key detection,
semitone math, sidechain envelope, tiling) have deterministic unit
tests against a committed fixture (tests/fixtures/tone.wav, plain
numpy+soundfile, no ffmpeg dependency).
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BCxXmJVvDFJVHTUi4QgNzi
parent 83b9fafc
Pipeline #995 failed with stage
in 113 minutes and 54 seconds
......@@ -2,6 +2,10 @@ TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
ACOUSTID_API_KEY=your_acoustid_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)
LALAL_API_KEY=your_lalal_api_key_here
......
......@@ -7,6 +7,7 @@ syncedlyrics==1.0.1
pyacoustid==1.3.0
musicbrainzngs==0.7.1
google-generativeai==0.8.3
anthropic>=0.40.0
pedalboard==0.9.8
fastapi>=0.110.0
uvicorn>=0.28.0
......
......@@ -163,6 +163,23 @@
.result-card h3 { margin: 0 0 10px 0; font-size: 15px; color: var(--accent); }
.result-card .row { display: flex; justify-content: space-between; font-size: 12.5px; padding: 3px 0; color: var(--text-dim); }
.result-card .row b { color: var(--text); font-weight: 500; }
.section-row {
background: var(--panel);
border: 1px solid var(--border);
border-radius: 8px;
padding: 8px 10px;
margin-top: 6px;
font-size: 12px;
}
.section-row .section-name {
color: var(--accent);
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.03em;
font-size: 10.5px;
}
.section-row .section-range { color: var(--text-dim); margin-left: 6px; }
.section-row .section-roles { color: var(--text-dim); margin-top: 2px; }
audio { width: 100%; margin-top: 12px; }
.status-line { margin-top: 10px; font-size: 12.5px; color: var(--text-dim); min-height: 16px; }
.status-line.error { color: var(--bad); }
......@@ -243,7 +260,7 @@
<section id="remix-section">
<h2>🎛 AI Remix</h2>
<p class="desc">Upload 1&ndash;5 songs and describe the remix in plain language. Gemini listens to each track, plans which stems to pull from which song, and Demucs does the actual separation before mixing/mastering.</p>
<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>
<div class="dropzone" id="remix-drop">
Drop up to 5 audio files here, or click to choose
......@@ -269,7 +286,10 @@
<div class="result-card" id="remix-result">
<h3 id="remix-result-name"></h3>
<div class="row"><span>Target BPM</span><b id="remix-result-bpm"></b></div>
<div class="row"><span>Song roles</span><b id="remix-result-roles"></b></div>
<div class="row"><span>Target key</span><b id="remix-result-key"></b></div>
<div class="row"><span>Style</span><b id="remix-result-style"></b></div>
<div class="row"><span>Sidechain</span><b id="remix-result-sidechain"></b></div>
<div id="remix-result-sections" style="margin-top:10px;"></div>
<audio controls id="remix-result-audio"></audio>
</div>
</section>
......@@ -408,9 +428,26 @@ $('#remix-submit').addEventListener('click', async () => {
$('#remix-submit').disabled = false;
$('#remix-result-name').textContent = data.remix_name || 'Remix';
if (data.plan) {
$('#remix-result-bpm').textContent = data.plan.target_bpm ?? '—';
const roles = (data.plan.song_roles || []).map(r => `#${r.index}: ${(r.stems||[]).join('+') || 'none'}`).join(' · ');
$('#remix-result-roles').textContent = roles || '—';
const p = data.plan;
const noteNames = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B'];
$('#remix-result-bpm').textContent = p.target_bpm ?? '—';
$('#remix-result-key').textContent = (p.target_key_tonic !== undefined) ? noteNames[p.target_key_tonic] : '—';
$('#remix-result-style').textContent = p.style && p.style !== 'none' ? p.style : 'none';
$('#remix-result-sidechain').textContent = (p.sidechain && p.sidechain.enabled)
? `on (song #${p.sidechain.source_index} drums, ${Math.round((p.sidechain.amount||0)*100)}%)`
: 'off';
const sectionsEl = $('#remix-result-sections');
sectionsEl.innerHTML = '';
(p.sections || []).forEach(section => {
const row = document.createElement('div');
row.className = 'section-row';
const roles = (section.song_roles || [])
.map(r => `#${r.index}: ${(r.stems || []).join('+') || 'none'}`)
.join(' · ');
row.innerHTML = `<span class="section-name">${section.name}</span><span class="section-range">${Math.round(section.start_fraction*100)}%&ndash;${Math.round(section.end_fraction*100)}%</span><div class="section-roles">${roles || 'nothing active'}</div>`;
sectionsEl.appendChild(row);
});
}
$('#remix-result-audio').src = data.download_url;
resultEl.classList.add('show');
......
......@@ -8,6 +8,7 @@ load_dotenv()
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
ACOUSTID_API_KEY = os.getenv("ACOUSTID_API_KEY", "8XaBELgH")
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
LALAL_API_KEY = os.getenv("LALAL_API_KEY")
# Gate for the interactive API docs (/docs, /openapi.json) - HTTP Basic Auth.
......
......@@ -5,14 +5,25 @@ import os
import shutil
import threading
import anthropic
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 pedalboard import (
Compressor,
Distortion,
HighpassFilter,
LowpassFilter,
LowShelfFilter,
Pedalboard,
PitchShift,
Reverb,
)
from scipy.signal import butter, filtfilt
from src.core.config import ANTHROPIC_API_KEY, GEMINI_API_KEY, logger
from src.core.database import RemixJob, SessionLocal
from src.services.music_identification import identify_audio
......@@ -25,10 +36,13 @@ torch.backends.mkldnn.enabled = False
if 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"
REMIX_TEMP_DIR = "/root/antigrav-stax-audio/temp"
DOWNLOADS_DIR = "/root/antigrav-stax-audio/downloads"
STEM_NAMES = ["vocals", "drums", "bass", "other"]
TARGET_SR = 44100
os.makedirs(STEM_CACHE_DIR, exist_ok=True)
......@@ -41,6 +55,10 @@ def _file_hash(file_path: str) -> str:
return h.hexdigest()[:24]
# ---------------------------------------------------------------------------
# Stem separation (Demucs)
# ---------------------------------------------------------------------------
_separator = None
_separator_lock = threading.Lock()
......@@ -57,13 +75,10 @@ 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.
Guarded by a process-wide lock: with two remix jobs submitted close together, both
landed in this function around the same time and hung indefinitely (no CPU activity,
no progress) instead of erroring - almost certainly concurrent access to demucs/the
HF Hub model cache, which isn't documented as thread-safe. On this VPS's weak,
no-AVX CPU, running two Demucs passes concurrently would thrash anyway, so
serializing here fixes both the hang and the resource contention in one move: only
one separation runs at a time, others block until it's done."""
Guarded by a process-wide lock: concurrent calls into demucs/the HF Hub model cache
hung indefinitely in testing (not documented as thread-safe), and this VPS's weak,
no-AVX CPU would thrash running two Demucs passes concurrently anyway - serializing
fixes both at once."""
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}
......@@ -84,6 +99,10 @@ def separate_stems(file_path: str) -> dict:
return stem_paths
# ---------------------------------------------------------------------------
# Tempo & key detection - real analysis, not AI guesswork
# ---------------------------------------------------------------------------
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)
......@@ -91,10 +110,55 @@ def detect_bpm(file_path: str) -> float:
return tempo if 40 < tempo < 220 else 120.0
PITCH_CLASSES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
# Krumhansl-Kessler key profiles: relative weight of each scale degree in a listener's
# sense of a major/minor key. Correlating a track's chroma vector against all 24 rotations
# of these is a standard, well-established key-estimation technique.
_MAJOR_PROFILE = np.array([6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88])
_MINOR_PROFILE = np.array([6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17])
def detect_key(file_path: str) -> dict:
"""Estimates musical key via chroma features + Krumhansl-Kessler profile correlation.
Returns {"tonic": 0-11 pitch class, "mode": "major"|"minor", "name": "C major"}.
This exists so pitch-shift decisions are computed from real harmonic data instead of
an AI guessing a semitone number with nothing to back it - see _semitone_shift_to_key."""
y, sr = librosa.load(file_path, sr=22050, mono=True, duration=60)
chroma = librosa.feature.chroma_cqt(y=y, sr=sr)
chroma_mean = chroma.mean(axis=1)
total = chroma_mean.sum()
if total > 0:
chroma_mean = chroma_mean / total
best_score, best_tonic, best_mode = -np.inf, 0, "major"
for tonic in range(12):
for mode, profile in (("major", _MAJOR_PROFILE), ("minor", _MINOR_PROFILE)):
rotated = np.roll(profile, tonic)
score = np.corrcoef(chroma_mean, rotated)[0, 1]
if score > best_score:
best_score, best_tonic, best_mode = score, tonic, mode
return {"tonic": best_tonic, "mode": best_mode, "name": f"{PITCH_CLASSES[best_tonic]} {best_mode}"}
def _semitone_shift_to_key(from_tonic: int, to_tonic: int) -> int:
"""Smallest-magnitude semitone shift, in [-6, 6], that moves from_tonic to to_tonic
(mod-12 circular distance) - minimizes audible pitch-shift artifacts while still
landing exactly on the target key."""
diff = (to_tonic - from_tonic) % 12
if diff > 6:
diff -= 12
return int(diff)
# ---------------------------------------------------------------------------
# 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.
# ---------------------------------------------------------------------------
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)
......@@ -104,100 +168,201 @@ def _make_audio_preview_part(file_path: str, seconds: int = 25) -> dict:
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."""
async def describe_song_audio(file_path: str, title: str, artist: str, bpm: float, key_name: str) -> str:
"""Gemini listens to a real preview and writes a text description of what's actually in
the track. This description - not raw audio - is what gets handed to Claude, since
Claude's API can't take audio input."""
if not GEMINI_API_KEY:
raise Exception("GEMINI_API_KEY not configured.")
return f'"{title}" by {artist}, {bpm:.0f} BPM, key of {key_name}. (No audio description available - 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})'
model = genai.GenerativeModel(
"gemini-2.5-flash", generation_config={"response_mime_type": "application/json"}
)
async def plan_remix(prompt: str, songs_info: list) -> dict:
"""Claude takes the Gemini-generated descriptions, real BPM/key data, and the user's
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 = []
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})"
f'Song {info["index"]}: "{info["title"]}" by {info["artist"]} - '
f'{info["bpm"]:.0f} BPM, key of {info["key_name"]}.\n'
f'What it sounds like: {info["description"]}'
)
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)
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 have {len(songs_info)} song(s), each already 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.
- 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).
- 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.
- Apply a named style preset that shapes the final tone: "lofi" (filtered, warm, saturated), "trap" (heavy low end, punchy), "house" (clean, driving), or "none".
Songs:
{os.linesep.join(song_lines)}
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.
Return ONLY a JSON object, no other text, strictly following this schema:
{{
"remix_name": str (2-4 word creative title, do NOT include the word "remix"),
"target_bpm": float,
"target_key_tonic": int (0-11, pitch class: 0=C, 1=C#, 2=D, 3=D#, 4=E, 5=F, 6=F#, 7=G, 8=G#, 9=A, 10=A#, 11=B - pick one of the songs' detected tonics, or a musically related one),
"style": str, one of "none", "lofi", "trap", "house",
"sidechain": {{"enabled": bool, "source_index": int (which song's drums stem drives the pump), "amount": float (0.0-1.0)}},
"sections": [
{{
"name": str (e.g. "intro", "build", "drop", "breakdown", "outro"),
"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}}
]
}}
],
"master_effects": {{
"reverb_room_size": float (0.0-1.0),
"compressor_threshold_db": float (-20 to -6),
"compressor_ratio": float (1.5 to 6)
}}
"""
}}
parts.append(instructions)
response = await asyncio.to_thread(model.generate_content, parts)
plan = json.loads(response.text)
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(
anthropic_client.messages.create,
model="claude-sonnet-5",
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}
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]
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]
section["song_roles"] = [r for r in section.get("song_roles", []) if r.get("index") in valid_indices]
if not plan.get("sections"):
plan["sections"] = [{
"name": "full",
"start_fraction": 0.0,
"end_fraction": 1.0,
"song_roles": [{"index": i, "stems": STEM_NAMES, "gain_db": 0.0} for i in valid_indices],
}]
return plan
def _time_stretch_to_bpm(audio: np.ndarray, sr: int, current_bpm: float, target_bpm: float) -> np.ndarray:
# ---------------------------------------------------------------------------
# Audio helpers: stretching, tiling, sidechain, style presets
# ---------------------------------------------------------------------------
def _time_stretch_to_bpm(audio: np.ndarray, 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])
return librosa.effects.time_stretch(np.ascontiguousarray(audio), rate=rate)
def _load_mono(path: str, sr: int) -> np.ndarray:
y, _ = librosa.load(path, sr=sr, mono=True)
return y
def _pitch_shift(audio: np.ndarray, sr: int, semitones: int) -> np.ndarray:
if not semitones:
return audio
board = Pedalboard([PitchShift(semitones=semitones)])
out = board(audio.astype(np.float32), sr)
return out[0] if out.ndim > 1 else out
def render_remix_sync(job_id: int, input_paths: list, prompt: str, filenames: list):
"""The full synchronous remix pipeline: identify -> 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.
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
def _tile_to_length(audio: np.ndarray, target_len: int) -> np.ndarray:
if len(audio) == 0:
return np.zeros(target_len, dtype=np.float32)
if len(audio) >= target_len:
return audio[:target_len]
reps = int(np.ceil(target_len / len(audio)))
return np.tile(audio, reps)[:target_len]
def _sidechain_gain_envelope(source_audio: np.ndarray, sr: int, amount: float) -> np.ndarray:
"""Derives a gain-reduction curve from a source signal's energy (typically a drum/kick
stem) that, multiplied onto other stems, produces the classic sidechain 'pump'. A
vectorized lowpass-filtered envelope follower rather than a per-sample Python loop -
this needs to run on a CPU with no SIMD acceleration, so a compiled scipy filter instead
of a manual attack/release loop is the difference between milliseconds and minutes."""
rectified = np.abs(source_audio)
peak = np.max(rectified)
if peak > 0:
rectified = rectified / peak
b, a = butter(2, 8.0 / (sr / 2), btype="low")
envelope = filtfilt(b, a, rectified)
envelope = np.clip(envelope, 0.0, 1.0)
gain = 1.0 - amount * envelope
return np.clip(gain, 1.0 - amount, 1.0).astype(np.float32)
def _apply_style_preset(audio: np.ndarray, sr: int, style: str) -> np.ndarray:
stages = []
if style == "lofi":
stages = [LowpassFilter(cutoff_frequency_hz=4500), Distortion(drive_db=8)]
elif style == "trap":
stages = [LowShelfFilter(cutoff_frequency_hz=100, gain_db=6), Compressor(threshold_db=-18, ratio=4)]
elif style == "house":
stages = [HighpassFilter(cutoff_frequency_hz=30), Compressor(threshold_db=-16, ratio=3)]
if not stages:
return audio
board = Pedalboard(stages)
return board(audio.astype(np.float32), sr)
identify_audio (Shazam/AcoustID) runs here, not in the API handler - each call can take
~30s to time out on a miss, which would otherwise block the initial HTTP response for
minutes with multiple songs. The API handler only saves files and returns immediately."""
# ---------------------------------------------------------------------------
# Main pipeline
# ---------------------------------------------------------------------------
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
(Claude) -> separate (Demucs) -> stretch/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
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."""
db = SessionLocal()
def set_status(status: str, detail: str = None):
......@@ -208,31 +373,33 @@ def render_remix_sync(job_id: int, input_paths: list, prompt: str, filenames: li
db.commit()
try:
set_status("planning", "Identifying songs and detecting tempo")
target_sr = 44100
set_status("planning", "Identifying songs, detecting tempo and key")
songs_info = []
for i, path in enumerate(input_paths):
bpm = detect_bpm(path)
key = detect_key(path)
fallback_title = os.path.splitext(filenames[i])[0] if i < len(filenames) else f"Track {i + 1}"
title, artist, genre = fallback_title, "Unknown Artist", "Unknown"
title, artist = fallback_title, "Unknown Artist"
try:
candidates = asyncio.run(identify_audio(path))
if candidates:
title = candidates[0].get("title", title)
artist = candidates[0].get("artist", artist)
genre = candidates[0].get("genre", genre)
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,
"title": title,
"artist": artist,
"genre": genre,
"index": i, "path": path, "bpm": bpm,
"key_tonic": key["tonic"], "key_name": key["name"],
"title": title, "artist": artist,
})
set_status("planning", "Asking Gemini for a remix plan")
set_status("planning", "Listening to each song (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))
job = db.query(RemixJob).filter(RemixJob.id == job_id).first()
......@@ -241,51 +408,86 @@ def render_remix_sync(job_id: int, input_paths: list, prompt: str, filenames: li
db.commit()
target_bpm = float(plan.get("target_bpm") or songs_info[0]["bpm"])
target_key_tonic = int(plan.get("target_key_tonic", songs_info[0]["key_tonic"]))
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"]
# Every stem of every song used anywhere in the plan gets stretched/pitch-matched
# ONCE and cached in memory; sections then just slice/sum from this shared pool
# instead of reprocessing per section.
used_song_indices = {
role["index"]
for section in plan["sections"]
for role in section["song_roles"]
}
prepared_stems = {} # song_index -> stem_name -> np.ndarray
for idx in used_song_indices:
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)
semitone_shift = _semitone_shift_to_key(info["key_tonic"], target_key_tonic)
prepared_stems[idx] = {}
for stem_name, stem_path in stem_paths.items():
y, _ = librosa.load(stem_path, sr=TARGET_SR, mono=True)
y = _time_stretch_to_bpm(y, info["bpm"], target_bpm)
y = _pitch_shift(y, TARGET_SR, semitone_shift)
prepared_stems[idx][stem_name] = y.astype(np.float32)
set_status("mixing", "Rendering the arrangement section by section")
total_len = max(len(y) for stems in prepared_stems.values() for y in stems.values())
rest_buffer = np.zeros(total_len, dtype=np.float32)
source_drums_buffer = np.zeros(total_len, dtype=np.float32)
sidechain = plan.get("sidechain") or {}
sidechain_source_idx = sidechain.get("source_index") if sidechain.get("enabled") else None
crossfade_len = min(int(TARGET_SR * 0.3), total_len // 20 if total_len else 0)
for section in plan["sections"]:
start = int(section["start_fraction"] * total_len)
end = int(section["end_fraction"] * total_len)
end = max(end, start + 1)
section_len = end - start
fade = np.ones(section_len, dtype=np.float32)
if crossfade_len > 0:
ramp = np.linspace(0.0, 1.0, crossfade_len, dtype=np.float32)
if start > 0:
fade[:crossfade_len] = ramp
if end < total_len:
fade[-crossfade_len:] = np.minimum(fade[-crossfade_len:], ramp[::-1])
for role in section["song_roles"]:
idx = role["index"]
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)
for stem_name in stems_wanted:
full = prepared_stems[idx].get(stem_name)
if full is None:
continue
segment = _tile_to_length(full[start:end] if start < len(full) else np.zeros(section_len, dtype=np.float32), section_len)
segment = segment * gain * fade
is_source_drums = (idx == sidechain_source_idx and stem_name == "drums")
target_buffer = source_drums_buffer if is_source_drums else rest_buffer
target_buffer[start:end] = _pad_add(target_buffer[start:end], segment)
if sidechain_source_idx is not None:
set_status("mixing", "Applying sidechain")
envelope = _sidechain_gain_envelope(source_drums_buffer, TARGET_SR, float(sidechain.get("amount", 0.6)))
mix = source_drums_buffer + rest_buffer * envelope
else:
mix = source_drums_buffer + rest_buffer
peak = np.max(np.abs(mix)) or 1.0
if peak > 0.98:
mix = mix / peak * 0.98
style = plan.get("style", "none")
if style and style != "none":
set_status("mastering", f"Applying '{style}' style preset")
mix = _apply_style_preset(mix, TARGET_SR, style)
set_status("mastering", "Applying master effects chain")
effects = plan.get("master_effects", {})
board = Pedalboard([
......@@ -295,11 +497,15 @@ def render_remix_sync(job_id: int, input_paths: list, prompt: str, filenames: li
),
Reverb(room_size=effects.get("reverb_room_size", 0.15)),
])
mastered = board(mix, target_sr)
mastered = board(mix, TARGET_SR)
peak = np.max(np.abs(mastered)) or 1.0
if peak > 0.98:
mastered = mastered / peak * 0.98
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)
sf.write(wav_path, mastered, TARGET_SR)
title_bits = " x ".join(s["title"] for s in songs_info)
candidate = {
......@@ -331,11 +537,3 @@ def render_remix_sync(job_id: int, input_paths: list, prompt: str, filenames: li
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
import os
import numpy as np
from src.services.remix_engine import (
_pad_add,
_semitone_shift_to_key,
_sidechain_gain_envelope,
_tile_to_length,
detect_key,
)
def test_semitone_shift_same_key_is_zero():
assert _semitone_shift_to_key(3, 3) == 0
def test_semitone_shift_picks_smallest_magnitude_direction():
# C (0) -> F# (6): exactly 6 either way, must be within [-6, 6]
shift = _semitone_shift_to_key(0, 6)
assert shift in (-6, 6)
# C (0) -> C# (1): +1 is closer than -11
assert _semitone_shift_to_key(0, 1) == 1
# C (0) -> B (11): -1 is closer than +11
assert _semitone_shift_to_key(0, 11) == -1
def test_semitone_shift_always_in_range():
for a in range(12):
for b in range(12):
shift = _semitone_shift_to_key(a, b)
assert -6 <= shift <= 6
assert (a + shift) % 12 == b
FIXTURES_DIR = os.path.join(os.path.dirname(__file__), "fixtures")
def test_detect_key_returns_valid_structure():
key = detect_key(os.path.join(FIXTURES_DIR, "tone.wav"))
assert 0 <= key["tonic"] <= 11
assert key["mode"] in ("major", "minor")
assert key["name"] == f"{['C','C#','D','D#','E','F','F#','G','G#','A','A#','B'][key['tonic']]} {key['mode']}"
def test_sidechain_envelope_ducks_loud_regions_more():
sr = 8000
silence = np.zeros(sr, dtype=np.float32)
loud = np.ones(sr, dtype=np.float32)
source = np.concatenate([silence, loud])
envelope = _sidechain_gain_envelope(source, sr, amount=0.8)
assert envelope.shape == source.shape
assert envelope.min() >= 0.2 - 1e-6 # amount=0.8 -> floor of 1-0.8=0.2
assert envelope.max() <= 1.0
# the loud region should be ducked more (lower gain) than the silent region
assert envelope[:sr].mean() > envelope[sr:].mean()
def test_pad_add_matches_longer_length():
a = np.array([1.0, 2.0, 3.0], dtype=np.float32)
b = np.array([10.0, 20.0], dtype=np.float32)
result = _pad_add(a, b)
assert len(result) == 3
assert np.allclose(result, [11.0, 22.0, 3.0])
def test_tile_to_length_extends_short_audio():
audio = np.array([1.0, 2.0], dtype=np.float32)
result = _tile_to_length(audio, 5)
assert len(result) == 5
assert np.allclose(result, [1.0, 2.0, 1.0, 2.0, 1.0])
def test_tile_to_length_truncates_long_audio():
audio = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32)
result = _tile_to_length(audio, 2)
assert np.allclose(result, [1.0, 2.0])
def test_tile_to_length_handles_empty_audio():
result = _tile_to_length(np.array([], dtype=np.float32), 4)
assert len(result) == 4
assert np.allclose(result, 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