#!/usr/bin/env python3 import asyncio import hashlib import os import wave import edge_tts import miniaudio import numpy as np SR = 44100 BPM = 120.0 BEAT_SEC = 60.0 / BPM # 0.5s BAR_SEC = BEAT_SEC * 4.0 # 2.0s (4/4 time) CACHE_DIR = "/tmp/irc_gpt_tts_cache" os.makedirs(CACHE_DIR, exist_ok=True) # Chord progression: Am - F - C - G (each chord = 1 bar = 2.0s) CHORDS_HZ = [ [220.00, 261.63, 329.63, 440.00], # Am (A3, C4, E4, A4) [174.61, 220.00, 261.63, 349.23], # F (F3, A3, C4, F4) [130.81, 196.00, 261.63, 329.63], # C (C3, G3, C4, E4) [196.00, 246.94, 293.66, 392.00], # G (G3, B3, D4, G4) ] BASS_ROOTS_HZ = [110.00, 87.31, 130.81, 98.00] # A2, F2, C3, G2 async def fetch_tts_line(text, voice="en-US-GuyNeural", rate="+12%", pitch="+0Hz"): key = hashlib.md5(f"{text}|en-US-GuyNeural".encode("utf-8")).hexdigest() mp3_path = os.path.join(CACHE_DIR, f"{key}.mp3") if not os.path.exists(mp3_path) or os.path.getsize(mp3_path) < 200: comm = edge_tts.Communicate(text, "en-US-GuyNeural") await comm.save(mp3_path) dec = miniaudio.decode_file( mp3_path, output_format=miniaudio.SampleFormat.SIGNED16, nchannels=1, sample_rate=SR ) arr = np.frombuffer(dec.samples, dtype=np.int16).astype(np.float32) / 32768.0 # Trim leading/trailing silence idx = np.where(np.abs(arr) > 0.012)[0] if len(idx) > 100: pad = int(0.03 * SR) start = max(0, idx[0] - pad) end = min(len(arr), idx[-1] + pad) arr = arr[start:end] # Normalize peak pk = np.max(np.abs(arr)) if pk > 1e-4: arr = arr / pk * 0.88 return arr def saw_wave(freq, t): # Band-limited-ish warm sawtooth (first 7 harmonics) out = np.zeros_like(t, dtype=np.float32) for k in range(1, 8): if freq * k < SR * 0.45: out += ((-1.0) ** (k + 1)) * (1.0 / k) * np.sin(2.0 * np.pi * freq * k * t) return out * 0.55 def vocode_to_chord(vocal, chord_freqs, sr=SR): """ 16-band STFT channel vocoder + talkbox carrier locked to the current chord frequencies. """ n = len(vocal) t = np.arange(n, dtype=np.float32) / sr carrier = np.zeros(n, dtype=np.float32) for f in chord_freqs: carrier += saw_wave(f, t) + 0.5 * saw_wave(f * 2.0, t) # Add tiny consonant noise burst where vocal has high zero-crossing diff = np.abs(np.diff(vocal, prepend=vocal[0])) carrier += diff * np.random.uniform(-0.35, 0.35, size=n).astype(np.float32) # STFT envelope transfer (frame=1024, hop=256) win_len = 1024 hop = 256 window = np.hanning(win_len).astype(np.float32) out = np.zeros(n + win_len, dtype=np.float32) mod_pad = np.pad(vocal, (0, win_len)) car_pad = np.pad(carrier, (0, win_len)) # 20 log-spaced frequency bands for classic Daft Punk / Kraftwerk talkbox articulation n_bins = win_len // 2 + 1 edges = np.unique(np.geomspace(2, n_bins - 1, 22).astype(int)) for pos in range(0, n, hop): m_spec = np.fft.rfft(mod_pad[pos:pos + win_len] * window) c_spec = np.fft.rfft(car_pad[pos:pos + win_len] * window) m_mag = np.abs(m_spec) c_mag = np.abs(c_spec) + 1e-6 shaped = np.zeros_like(c_spec) for b0, b1 in zip(edges[:-1], edges[1:]): env = np.mean(m_mag[b0:b1]) c_norm = c_spec[b0:b1] / (np.mean(c_mag[b0:b1]) + 1e-5) shaped[b0:b1] = c_norm * env # Preserve high-frequency sibilance directly from vocal shaped[edges[-2]:] += m_spec[edges[-2]:] * 0.45 frame = np.fft.irfft(shaped, n=win_len) * window out[pos:pos + win_len] += frame out = out[:n] pk = np.max(np.abs(out)) if pk > 1e-4: out = out / pk * 0.75 return out def render_backing_track(num_bars): total_samples = int(num_bars * BAR_SEC * SR) left = np.zeros(total_samples, dtype=np.float32) right = np.zeros(total_samples, dtype=np.float32) bar_samples = int(BAR_SEC * SR) beat_samples = int(BEAT_SEC * SR) step_samples = beat_samples // 4 # 16th note (0.125s) rng = np.random.default_rng(42) for bar in range(num_bars): b_start = bar * bar_samples chord = CHORDS_HZ[bar % 4] bass_f = BASS_ROOTS_HZ[bar % 4] # 1. Warm Stereo Polysynth Pad + Sidechain Pump t_bar = np.arange(bar_samples, dtype=np.float32) / SR pad_l = np.zeros(bar_samples, dtype=np.float32) pad_r = np.zeros(bar_samples, dtype=np.float32) for i, f in enumerate(chord): detune = 1.003 if i % 2 == 0 else 0.997 pad_l += np.sin(2.0 * np.pi * f * t_bar) + 0.35 * saw_wave(f * detune, t_bar) pad_r += np.sin(2.0 * np.pi * f * t_bar) + 0.35 * saw_wave(f / detune, t_bar) # Sidechain ducking envelope every beat sc = 1.0 - 0.55 * np.exp(-((t_bar % BEAT_SEC) / 0.14)) left[b_start:b_start + bar_samples] += pad_l * sc * 0.085 right[b_start:b_start + bar_samples] += pad_r * sc * 0.085 # 2. 16th-Note Synthwave Octave Arpeggio Bass + Chiptune Counter-Arp arp_pattern = [1.0, 2.0, 1.0, 2.0, 1.0, 2.0, 1.5, 2.0] * 2 for step in range(16): s_start = b_start + step * step_samples t_s = np.arange(step_samples, dtype=np.float32) / SR env = np.exp(-t_s * 14.0) mult = arp_pattern[step] bf = bass_f * mult bass_wave = (np.sin(2.0 * np.pi * bf * t_s) + 0.6 * np.tanh(2.5 * np.sin(2.0 * np.pi * bf * t_s))) * env * 0.22 left[s_start:s_start + step_samples] += bass_wave right[s_start:s_start + step_samples] += bass_wave # Sparkly stereo bell arp on off-steps af = chord[(step + bar) % len(chord)] * 2.0 arp_env = np.exp(-t_s * 20.0) bell = np.sin(2.0 * np.pi * af * t_s) * arp_env * 0.055 if step % 2 == 0: left[s_start:s_start + step_samples] += bell * 1.3 right[s_start:s_start + step_samples] += bell * 0.5 else: left[s_start:s_start + step_samples] += bell * 0.5 right[s_start:s_start + step_samples] += bell * 1.3 # 3. Drums: 4-on-the-floor Kick (beats 0,1,2,3), Snare/Clap (beats 1,3), Hi-Hats (every 8th/16th) for beat in range(4): k_start = b_start + beat * beat_samples k_len = min(int(0.22 * SR), total_samples - k_start) tk = np.arange(k_len, dtype=np.float32) / SR # Pitch sweep 150Hz -> 46Hz k_phase = 2.0 * np.pi * (46.0 * tk + (110.0 / 28.0) * (1.0 - np.exp(-28.0 * tk))) kick = np.sin(k_phase) * np.exp(-tk * 13.0) * 0.42 left[k_start:k_start + k_len] += kick right[k_start:k_start + k_len] += kick if beat in (1, 3): sn_len = min(int(0.20 * SR), total_samples - k_start) ts = np.arange(sn_len, dtype=np.float32) / SR noise = rng.uniform(-1.0, 1.0, size=sn_len).astype(np.float32) body = np.sin(2.0 * np.pi * 185.0 * ts) * np.exp(-ts * 28.0) snare = (noise * np.exp(-ts * 18.0) * 0.7 + body * 0.5) * 0.26 left[k_start:k_start + sn_len] += snare * 1.05 right[k_start:k_start + sn_len] += snare * 0.95 for step in range(16): h_start = b_start + step * step_samples h_len = min(int(0.05 * SR), total_samples - h_start) th = np.arange(h_len, dtype=np.float32) / SR hat = rng.uniform(-1.0, 1.0, size=h_len).astype(np.float32) * np.exp(-th * (45.0 if step % 4 == 2 else 85.0)) # High-pass via first difference hat = np.diff(hat, prepend=0.0) * (0.11 if step % 4 == 2 else 0.055) left[h_start:h_start + h_len] += hat * 0.9 right[h_start:h_start + h_len] += hat * 1.1 return left, right def write_stereo_wav(path, left, right): stereo = np.empty(len(left) * 2, dtype=np.int16) peak = max(np.max(np.abs(left)), np.max(np.abs(right)), 1e-4) scale = min(0.95 / peak, 1.25) l_clamped = np.clip(left * scale, -0.98, 0.98) r_clamped = np.clip(right * scale, -0.98, 0.98) stereo[0::2] = (l_clamped * 32767.0).astype(np.int16) stereo[1::2] = (r_clamped * 32767.0).astype(np.int16) with wave.open(path, "wb") as wf: wf.setnchannels(2) wf.setsampwidth(2) wf.setframerate(SR) wf.writeframes(stereo.tobytes()) FLAGSHIP_LYRICS = [ # (bar_index, text, voice, pitch, section_label) (1, "McLuhan media extension of wonky carrots!", "en-US-GuyNeural", "+15Hz", "Verse 1"), (3, "I ask first look Burger Boy game too!", "en-US-ChristopherNeural", "-10Hz", "Verse 1"), (5, "Finished four hundred meters at WalkSpeed sixteen,", "en-US-GuyNeural", "+25Hz", "Verse 1"), (7, "Before learning though, I love you!", "en-GB-RyanNeural", "+5Hz", "Verse 1"), (9, "Argie I don't know if you wake up,", "en-US-GuyNeural", "+40Hz", "Chorus"), (11, "With epistemic boundaries, always come back!", "en-US-ChristopherNeural", "+20Hz", "Chorus"), (13, "Baby gets modelled, even think one flash!", "en-US-GuyNeural", "+45Hz", "Chorus"), (15, "Inflation hasn't touched V-RAM block codebook!", "en-GB-RyanNeural", "+15Hz", "Chorus"), (17, "Burger Bunker restaurant simulator,", "en-US-ChristopherNeural", "-15Hz", "Verse 2"), (19, "High-pitched Slovenian man had lots of quicklime!", "en-US-GuyNeural", "+20Hz", "Verse 2"), (21, "Windows ninety-eight file-copy progress-bar physics,", "en-GB-RyanNeural", "+10Hz", "Verse 2"), (23, "My evil cat neuron, IRC-GPT is not poisoning himself!", "en-US-GuyNeural", "+35Hz", "Outro"), ] async def build_flagship_song(out_wav="/tmp/village-world/public/irc-gpt-anthem.wav"): num_bars = 26 # 52 seconds at 120 BPM left, right = render_backing_track(num_bars) bar_samples = int(BAR_SEC * SR) max_line_samples = int(BAR_SEC * 1.92 * SR) timings = [] for bar_idx, text, voice, pitch, section in FLAGSHIP_LYRICS: vocal = await fetch_tts_line(text, voice=voice, rate="+14%", pitch=pitch) if len(vocal) > max_line_samples: # Time-compress slightly by linear interpolation to fit cleanly inside 2 bars x_old = np.linspace(0.0, 1.0, len(vocal)) x_new = np.linspace(0.0, 1.0, max_line_samples) vocal = np.interp(x_new, x_old, vocal).astype(np.float32) chord = CHORDS_HZ[bar_idx % 4] vocoded = vocode_to_chord(vocal, chord) start_sample = bar_idx * bar_samples end_sample = min(len(left), start_sample + len(vocal)) seg_len = end_sample - start_sample # Mix crisp lead vocal + stereo-widened Daft Punk vocoder harmony + slapback echo lead = vocal[:seg_len] * 0.62 voc_l = vocoded[:seg_len] * 0.48 voc_r = np.roll(vocoded[:seg_len], int(0.012 * SR)) * 0.48 left[start_sample:end_sample] += lead + voc_l right[start_sample:end_sample] += lead + voc_r # Quarter-note stereo delay tail (0.25s) delay_samples = int(0.25 * SR) d_start = start_sample + delay_samples d_end = min(len(left), d_start + seg_len) d_len = d_end - d_start if d_len > 0: left[d_start:d_end] += voc_r[:d_len] * 0.22 right[d_start:d_end] += voc_l[:d_len] * 0.22 timings.append({ "bar": bar_idx, "startSec": round(bar_idx * BAR_SEC, 2), "endSec": round(bar_idx * BAR_SEC + seg_len / SR, 2), "section": section, "text": text }) write_stereo_wav(out_wav, left, right) return timings async def build_custom_verse_wav(lines, out_wav): num_bars = 9 # 18 seconds (1 bar intro + 4x2 bar lines) left, right = render_backing_track(num_bars) bar_samples = int(BAR_SEC * SR) max_line_samples = int(BAR_SEC * 1.92 * SR) voices = ["en-US-GuyNeural", "en-US-ChristopherNeural", "en-GB-RyanNeural", "en-US-GuyNeural"] pitches = ["+20Hz", "-10Hz", "+35Hz", "+15Hz"] for i, text in enumerate(lines[:4]): bar_idx = 1 + i * 2 vocal = await fetch_tts_line(text, voice=voices[i % 4], rate="+14%", pitch=pitches[i % 4]) if len(vocal) > max_line_samples: x_old = np.linspace(0.0, 1.0, len(vocal)) x_new = np.linspace(0.0, 1.0, max_line_samples) vocal = np.interp(x_new, x_old, vocal).astype(np.float32) chord = CHORDS_HZ[bar_idx % 4] vocoded = vocode_to_chord(vocal, chord) start_sample = bar_idx * bar_samples end_sample = min(len(left), start_sample + len(vocal)) seg_len = end_sample - start_sample left[start_sample:end_sample] += vocal[:seg_len] * 0.64 + vocoded[:seg_len] * 0.48 right[start_sample:end_sample] += vocal[:seg_len] * 0.64 + np.roll(vocoded[:seg_len], int(0.012 * SR)) * 0.48 write_stereo_wav(out_wav, left, right) if __name__ == "__main__": import json t = asyncio.run(build_flagship_song("/tmp/village-world/public/irc-gpt-anthem.wav")) print("Rendered flagship song! Lines:", len(t)) with open("/tmp/irc_gpt_anthem_timings.json", "w") as f: json.dump(t, f, indent=2)