Commit 7c856954 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 ef508645
......@@ -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.
......
This diff is collapsed.
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