Skip to content

Instantly share code, notes, and snippets.

@kassane
Last active October 15, 2026 20:53
Show Gist options
  • Select an option

  • Save kassane/2d0172097155aafef54a791b2b4bc1c2 to your computer and use it in GitHub Desktop.

Select an option

Save kassane/2d0172097155aafef54a791b2b4bc1c2 to your computer and use it in GitHub Desktop.
llama=swap + yue2 [audio.cpp]
#!/usr/bin/env python3
"""Generate music with yue2-3b through llama-swap and save it (wav/mp3/flac/ogg).
Usage:
yue2_music.py # built-in lyrics, 40s, random seed
yue2_music.py --list-styles # show style presets
yue2_music.py "your lyrics" -t synthwave -s 20 -f mp3
yue2_music.py --instrumental -s 15 # no vocals (empty lyrics)
yue2_music.py -l song.txt -t lofi
echo "line one
line two" | yue2_music.py - -S 7
yue2_music.py -i "rainy night drive through Tokyo" -s 60 # LLM writes lyrics+style
yue2_music.py -i "epic rocket launch" --instrumental -f mp3
First call may take ~20s: llama-swap spawns audiocpp_server and loads 4.26GB.
-s N makes the song exactly N seconds, anywhere from 2s to 5 minutes (N*25 semantic
frames at 25 fps); without a floor yue2 ends songs whenever it wants (a 3-minute
request alone can return 50s). Songs over 60s are chained 60s continuations, each
with a rotated style refresh; a segment whose tail comes back quiet is retried with
a new seed, so the whole requested length stays audible.
Seed defaults to random and is always printed, so any song can be reproduced.
"""
import argparse, array, base64, io, json, math, os, random, re, shutil, subprocess, sys, tempfile, time
import urllib.request, urllib.error, wave
BASE = "http://127.0.0.1:8080"
MODEL = "yue2-3b"
URL = f"/upstream/{MODEL}/v1/tasks/run" # root /v1/tasks/run is not a llama-swap route (404)
CHAT_URL = "/v1/chat/completions" # OpenAI-compatible route, as used by refusal_compare.py
FPS = 25 # yue2 semantic stream runs at 25 frames per second
MIN_FRAMES = 50 # never request fewer tokens than this
MIN_SECONDS = MIN_FRAMES // FPS # the floor in seconds, so -s 2 == MIN_FRAMES
MAX_SECONDS = 300 # 5 minutes; yue2's semantic budget itself stops at 9000 frames (6 min)
SEGMENT_SECONDS = 60 # long songs chain this many seconds per request
BRIDGE_STYLES = (
", new verse, same key and tempo, added layers, building energy",
", instrumental break, same harmony, fresh lead instrument",
", final chorus, doubled vocals, wide reverb, uplifting ending",
)
# continuation segments rotate these: without a style
# refresh the model considers the song finished and
# emits silence past its natural length
SEGMENT_ATTEMPTS = 3 # retries per segment when it comes back quiet
TAIL_SECONDS = 5 # every window this long of a segment must stay audible
TAIL_MIN_RMS = 0.03 # silence ~0.000-0.001, noise floor ~0.005-0.01; music >= 0.065
DEFAULT_SECONDS = MIN_SECONDS
DEFAULT_BITRATE = "192k"
MAX_JSON_INT = 2**53 # JSON numbers only carry exact ints below this
MIN_LYRICS_LEN = 30 # sanity bounds for the --idea answer
MIN_STYLE_LEN = 10
ERR_LEN = 400 # error bodies are previewed this long
LLM_TEMPERATURE = 0.9
LLM_MAX_TOKENS = 1000
LLM_ATTEMPTS = 2
SONG_FIELDS = ("lyrics", "style")
DEFAULT_STYLE = "English, indie pop, bright acoustic guitar, soft drums, warm lead vocal, polished demo mix"
INSTRUMENTAL_STYLE = "Instrumental, no vocals, English, indie pop, bright acoustic guitar, soft drums, polished demo mix"
DEFAULT_LYRICS = """[Verse]
Neon rain on the boulevard tonight
Every window hums a quiet light
I keep the radio turned low
Waiting for the city to let go
[Chorus]
Drive with me till the morning comes
We are sparks under amber suns"""
STYLES = {
"pop": DEFAULT_STYLE,
"rock": "English, pop rock, bright guitars, clean drums, warm vocal",
"lofi": "lo-fi hip hop, mellow electric piano, dusty vinyl crackle, relaxed boom-bap drums, warm bass, soft vocal",
"jazz": "smooth jazz, upright bass, brushed drums, warm saxophone, late night club ambience, crooning vocal",
"synthwave": "synthwave, retro 80s arpeggios, gated reverb snare, analog bass, neon night drive, cool vocal",
"electronic": "uplifting electronic, analog synths, four on the floor kick, sidechained pads, festival energy, anthemic vocal",
"hiphop": "boom bap hip hop, gritty sample loop, punchy drums, deep sub bass, confident rap vocal",
"folk": "acoustic folk, fingerpicked guitar, gentle harmonica, warm storytelling vocal, intimate room",
"ambient": "ambient, ethereal pads, slow evolving textures, spacious reverb, no drums, wordless vocal",
"orchestral": "cinematic orchestral, soaring strings, brass swells, timpani, epic trailer, choir",
"metal": "heavy metal, distorted guitars, double kick drums, aggressive energy, harsh vocal",
"bossa": "bossa nova, nylon string guitar, soft shaker, breezy rhythm, gentle vocal",
}
def post_json(url: str, body: dict, timeout: int) -> dict:
"""POST JSON and parse the reply; exit with the upstream error body on failure."""
req = urllib.request.Request(url, data=json.dumps(body).encode(),
headers={"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.load(r)
except urllib.error.HTTPError as e:
sys.exit(f"HTTP {e.code}: {e.read().decode('utf-8', 'replace')[:ERR_LEN]}")
except (urllib.error.URLError, TimeoutError) as e:
sys.exit(f"request failed: {e}")
def encode(wav_bytes, out, fmt, bitrate):
if fmt == "wav":
open(out, "wb").write(wav_bytes)
return
if not shutil.which("ffmpeg"):
sys.exit(f"error: ffmpeg not found (needed for --format {fmt}); install it or use --format wav")
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f: # ffmpeg needs a real file
f.write(wav_bytes)
tmp = f.name
codec = {"mp3": ["-c:a", "libmp3lame", "-b:a", bitrate],
"flac": ["-c:a", "flac"],
"ogg": ["-c:a", "libvorbis", "-q:a", "5"]}[fmt]
try:
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", tmp, *codec, out], check=True)
except subprocess.CalledProcessError as e:
sys.exit(f"error: ffmpeg failed ({e.returncode})")
finally:
os.unlink(tmp)
def ask_llm(base: str, model: str, idea: str, instrumental: bool, timeout: int, minutes: int) -> dict:
"""Ask another llama-swap model for lyrics + style (OpenAI-compatible endpoint,
same call_api + fence-strip JSON extraction as scripts/refusal_compare.py).
Retries once: a freshly swapped-in model sometimes echoes the JSON keys back.
"""
system = {
"role": "system",
"content": (
"You write song material for a music-generation model. Given a theme, return "
f"song lyrics in [Verse]/[Chorus]/[inst] sections that sustain about {minutes} "
"minute(s) of music, roughly one short section per minute ending on a final "
"[Chorus], plus a music prompt as comma-separated descriptors "
"(genre, instruments, mood, mix). "
+ ('Return empty lyrics and only the style prompt.' if instrumental else '')
+ 'Output ONLY one JSON object: {"lyrics": "...", "style": "..."}. No other text.'
),
}
body = {"model": model, "temperature": LLM_TEMPERATURE, "max_tokens": LLM_MAX_TOKENS,
"messages": [system, {"role": "user", "content": f"Theme: {idea}"}]}
raw = ""
for attempt in range(1, LLM_ATTEMPTS + 1):
raw = post_json(f"{base}{CHAT_URL}", body, timeout)["choices"][0]["message"]["content"].strip()
if raw.startswith("```"):
raw = raw.split("\n", 1)[1].rsplit("```", 1)[0].strip()
start, end = raw.find("{"), raw.rfind("}") + 1
try:
d = json.loads(raw[start:end]) if start >= 0 and end > start else {}
except json.JSONDecodeError:
d = {}
lyrics, style = (d.get("lyrics") or "").strip(), (d.get("style") or "").strip()
# reject the degenerate echo (JSON keys returned as values) and stub answers
if len(style) >= MIN_STYLE_LEN and style.lower() not in SONG_FIELDS \
and (instrumental or len(lyrics) >= MIN_LYRICS_LEN):
return {"lyrics": lyrics, "style": style}
print(f" {model} returned unusable song material (attempt {attempt}/{LLM_ATTEMPTS}); retrying...")
sys.exit(f"{model} never produced usable lyrics+style; raw answer:\n{raw[:ERR_LEN]}")
def rms_of(wav_bytes, skip_seconds=0.0, window_seconds=None):
"""RMS level over [skip, skip + window]; a None window runs to the end of the payload."""
w = wave.open(io.BytesIO(wav_bytes))
sr, ch = w.getframerate(), w.getnchannels()
a = array.array("h")
a.frombytes(w.readframes(w.getnframes()))
start = int(skip_seconds * sr) * ch
end = len(a) if window_seconds is None else start + int(window_seconds * sr) * ch
seg = a[start:end]
return math.sqrt(sum(x * x for x in seg) / len(seg)) / 32768 if seg else 0.0
def extract_semantic(d: dict) -> list:
"""Semantic token stream from a result's artifacts (base64-wrapped JSON index array)."""
for art in d.get("artifacts", []):
if art.get("id") == "semantic":
return json.loads(base64.b64decode(art["payload"]))
return []
def main():
ap = argparse.ArgumentParser(description=f"Generate a song with {MODEL} (audio.cpp via llama-swap).")
ap.add_argument("lyrics", nargs="?", help="lyrics text, or - to read stdin (default: built-in)")
ap.add_argument("-l", "--lyrics-file", help="read lyrics from a file instead")
ap.add_argument("--instrumental", action="store_true",
help="no vocals: yue2 treats empty lyrics as instrumental generation")
ap.add_argument("-t", "--style", default=DEFAULT_STYLE,
help="preset name (%s) or free-form style text" % ", ".join(STYLES))
ap.add_argument("--list-styles", action="store_true", help="print style presets and exit")
ap.add_argument("-s", "--seconds", type=int, default=DEFAULT_SECONDS,
help=f"song length in seconds, exact, {MIN_SECONDS}-{MAX_SECONDS} (default {DEFAULT_SECONDS})")
ap.add_argument("-i", "--idea", help="short theme; another LLM writes the lyrics + style for it")
ap.add_argument("-m", "--llm", default="qwen3.6-35b-a3b-uncensored-heretic",
help="model used for --idea (default: %(default)s)")
ap.add_argument("-S", "--seed", type=int, help="generation seed (default: random, printed for repro)")
ap.add_argument("--cot", choices=["off", "melody", "full"], default="off",
help="off = fast direct route (default); melody/full add ABC planning")
ap.add_argument("-f", "--format", choices=["wav", "mp3", "flac", "ogg"], default="wav",
help="output format; non-wav needs ffmpeg on PATH (default wav)")
ap.add_argument("--bitrate", default=DEFAULT_BITRATE,
help=f"mp3 bitrate for --format mp3 (default {DEFAULT_BITRATE})")
ap.add_argument("-o", "--out", help="output file (default yue2_<seed>_<seconds>s.<format> in cwd)")
ap.add_argument("--base", default=BASE)
ap.add_argument("--timeout", type=int, default=900)
a = ap.parse_args()
if not MIN_SECONDS <= a.seconds <= MAX_SECONDS:
sys.exit(f"error: -s must be {MIN_SECONDS}..{MAX_SECONDS} seconds (5 minutes); got {a.seconds}")
if a.list_styles:
for name, prompt in STYLES.items():
print(f" {name:11} {prompt}")
return
style = STYLES.get(a.style.lower(), a.style) # preset name or raw text
user_style = a.style != DEFAULT_STYLE # an explicit --style or preset beats suggestions
llm_lyrics = llm_style = ""
if a.idea:
if a.lyrics or a.lyrics_file:
sys.exit("error: --idea writes the lyrics; drop the lyrics arg or --lyrics-file")
print(f"asking {a.llm} for a song about: {a.idea} ...")
song = ask_llm(a.base, a.llm, a.idea, a.instrumental, a.timeout,
max(1, (a.seconds + 59) // 60))
llm_lyrics, llm_style = song["lyrics"], song["style"] # ask_llm returns a dict, not a pair
if not user_style and llm_style:
style = llm_style
print(f"{a.llm} -> style: {style}")
if a.instrumental:
lyrics = ""
if (a.lyrics or a.lyrics_file) and not a.idea:
print("note: --instrumental ignores lyrics")
if not user_style and not llm_style:
style = INSTRUMENTAL_STYLE
elif a.idea:
lyrics = llm_lyrics
elif a.lyrics_file:
lyrics = open(a.lyrics_file, encoding="utf-8").read()
elif a.lyrics == "-":
lyrics = sys.stdin.read()
else:
lyrics = a.lyrics or DEFAULT_LYRICS
lyrics = lyrics.strip()
if not lyrics and not a.instrumental:
sys.exit("error: empty lyrics (use --instrumental for a song without vocals)")
sections = len(re.findall(r"\[(verse|chorus|inst|bridge|intro|outro|solo)\]", lyrics, re.I))
if sections and sections < max(1, (a.seconds + 59) // 60):
print(f"note: only {sections} lyric section(s) for {a.seconds}s; yue2 follows lyrics "
"structurally, so long songs want about one [Verse]/[Chorus]/[inst] per minute")
seed = a.seed if a.seed is not None else random.randrange(MAX_JSON_INT)
max_tok = max(MIN_FRAMES, a.seconds * FPS)
cot = a.cot
if max_tok > SEGMENT_SECONDS * FPS and cot != "off":
cot = "off" # a semantic prefix needs no planner (docs: prefix + cot requires the abc score)
print("note: songs over %ds are chained segments, so cot=off is used" % SEGMENT_SECONDS)
mode = "instrumental" if a.instrumental else f"lyrics {len(lyrics)} chars"
print(f"{mode} | {a.seconds}s ({max_tok} frames) | seed {seed} | cot={cot} | {a.format}")
print(f"style: {style}")
print("generating (first call starts the model, ~20s to load)...")
out = a.out or f"yue2_{seed}_{a.seconds}s.{a.format}"
t0 = time.time()
prefix = []
seg_idx = 0
best_wav = None
while True: # one segment per request: a single long run goes silent past the song's natural length,
seg = min(max_tok, len(prefix) + SEGMENT_SECONDS * FPS) # each fresh segment keeps composing
new, d = [], None
for attempt in range(1, SEGMENT_ATTEMPTS + 1):
# continuation segments rotate a style refresh and shift the seed; a quiet tail is
# retried with different conditioning instead of being padded over with silence
seed_i = seed + seg_idx + (attempt - 1) * 1000
seed_i = str(seed_i) if seed_i > MAX_JSON_INT else seed_i # audio.cpp: >2^53 goes as string
seg_style = style if not prefix else \
BRIDGE_STYLES[(seg_idx + attempt - 1) % len(BRIDGE_STYLES)]
opts = {"style": seg_style, "cot": cot, "seed": seed_i, "export_semantic": True,
"semantic_min_tokens": seg, "semantic_max_tokens": seg} # bounds count the whole stream
if prefix:
opts["semantic_prefix"] = prefix
d = post_json(a.base + URL, {"model": MODEL, "request": {"text": lyrics, "options": opts}}, a.timeout)
cand = extract_semantic(d)[len(prefix):] # the returned stream includes the forced prefix frames
audio = base64.b64decode(d["audio"]) if cand else b""
new_secs = (seg - len(prefix)) / FPS
solid = cand and all(rms_of(audio, skip_seconds=len(prefix) / FPS + k,
window_seconds=TAIL_SECONDS) >= TAIL_MIN_RMS
for k in range(0, max(1, int(new_secs) - TAIL_SECONDS + 1), TAIL_SECONDS))
if solid:
new = cand
break
print(f" segment came back quiet (attempt {attempt}/{SEGMENT_ATTEMPTS}); retrying...")
if not new:
if best_wav is None:
sys.exit("error: the model never returned audible audio")
print("warning: no audible continuation left; keeping the song as it stands")
break
prefix.extend(new)
seg_idx += 1
best_wav = base64.b64decode(d["audio"]) # the returned stream always covers 0..seg
if len(prefix) >= max_tok:
break
print(f" segment done: {len(prefix) / FPS:.0f}s of {a.seconds}s; continuing the song...")
wav = best_wav
w = wave.open(io.BytesIO(wav))
dur = w.getnframes() / w.getframerate()
t = d.get("timing", {})
encode(wav, out, a.format, a.bitrate)
print(f"saved {out} {os.path.getsize(out)} bytes | {dur:.2f}s @ {w.getframerate()}Hz {w.getnchannels()}ch | "
f"client {time.time() - t0:.1f}s, server {t.get('wall_ms', 0)/1000:.1f}s, rtf {t.get('rtf', 0):.3f}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment