Lumi robot software on the Jetson Thor

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 15:19:07 +09:00
co-authored by Claude Opus 5.5
commit 96b01fa12e
177 changed files with 39901 additions and 0 deletions
View File
+70
View File
@@ -0,0 +1,70 @@
"""Turn the singer's separated vocal into Lumi's voice (an "AI cover"): words, melody, timing and feeling stay the
singer's, the voice becomes Lumi's. Zero-shot singing voice conversion with Seed-VC (its 44.1 kHz pitch-conditioned
model) and a 25 s reference of Lumi's TTS voice. Offline tool: runs only in the render venv .venv-cover (torch
CUDA), with the Seed-VC code in models/seed-vc (local, GPL-3.0, not part of the robot's software).
.venv-cover/bin/python audio/cover.py MEOMUREU_DREAMED_ADULT
Reads data/songs/mine/<NAME>/vocals.wav (audio/separate.py), writes data/songs/mine/<NAME>/vocal_lumi.wav.
Then audio/sing_mine.py mixes it with the instrumental and picks the part to sing.
"""
import argparse
import os
import pathlib
import sys
import time
ROOT = pathlib.Path(__file__).resolve().parents[1]
SEED_VC = ROOT / "models" / "seed-vc"
MINE = ROOT / "data" / "songs" / "mine"
REFERENCE = MINE / "lumi_voice" / "ref25.wav" # 25 s of Lumi's TTS voice (F1), Korean and English
STEPS = 40 # diffusion steps (Seed-VC suggests 30-50 for singing)
CFG_RATE = 0.7 # how strongly the result follows the reference voice
SEMITONES = 0 # the singer's pitch is kept exactly
FP16 = True # half precision on the GPU
# Seed-VC fine-tuned on Lumi's voice (audio/lumi_voice_set.py, 300 clips / 24 min; train.py, 1000 steps from the
# 44.1 kHz pitch model). Tried on 꿈꾸던 어른이 되었나요: no closer to Lumi than the base model with REFERENCE alone
# (speaker similarity 0.81 against 0.83), so it is used only when asked (--fine-tuned)
FINE_TUNED = SEED_VC / "runs" / "run_dit_mel_seed_uvit_whisper_base_f0_44k" / "lumi_f0_44k"
def convert(name, steps=STEPS, cfg=CFG_RATE, semitones=SEMITONES, reference=REFERENCE, source=None, result=None,
fine_tuned=False):
"""source / result: another vocal file and output (tries on a part); default the whole vocal."""
import soundfile as sf
import torchaudio
folder = MINE / name
source = pathlib.Path(source).resolve() if source else folder / "vocals.wav" # before the chdir below
result = pathlib.Path(result).resolve() if result else folder / "vocal_lumi.wav"
out = folder / "seedvc"
out.mkdir(exist_ok=True)
# this torchaudio saves only through torchcodec; Seed-VC's one save goes through soundfile instead
torchaudio.save = lambda path, wav, sr: sf.write(path, wav.numpy().T, sr)
sys.path.insert(0, str(SEED_VC))
os.chdir(SEED_VC)
import inference
ft = fine_tuned and (FINE_TUNED / "ft_model.pth").exists()
args = argparse.Namespace(source=str(source), target=str(reference), output=str(out),
diffusion_steps=steps, length_adjust=1.0, inference_cfg_rate=cfg, f0_condition=True,
auto_f0_adjust=False, semi_tone_shift=semitones, fp16=FP16,
checkpoint=str(FINE_TUNED / "ft_model.pth") if ft else None,
config=str(next(FINE_TUNED.glob("*.yml"))) if ft else None)
t = time.time()
inference.main(args)
made = max(out.glob("vc_*.wav"), key=os.path.getmtime)
made.rename(result)
print(f"{result} ({time.time() - t:.0f} s)")
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("name")
ap.add_argument("--steps", type=int, default=STEPS)
ap.add_argument("--cfg", type=float, default=CFG_RATE)
ap.add_argument("--semitones", type=int, default=SEMITONES)
ap.add_argument("--reference", default=str(REFERENCE))
ap.add_argument("--source")
ap.add_argument("--result")
ap.add_argument("--fine-tuned", action="store_true", help="the model fine-tuned on Lumi's voice")
a = ap.parse_args()
convert(a.name, a.steps, a.cfg, a.semitones, pathlib.Path(a.reference), a.source, a.result, a.fine_tuned)
+115
View File
@@ -0,0 +1,115 @@
"""Judge a converted vocal (Lumi's voice cover) against the singer's original, without listening. Offline tool for
the render venv (.venv-cover: resemblyzer); prints numbers only, never lyrics.
.venv-cover/bin/python audio/cover_check.py data/songs/mine/<NAME>/vocals.wav <converted.wav> [start end]
(a) words: whisper (the running server) on both, cut the same way at the singer's phrases, the similarity of the
two transcripts, and how many characters
each gave; (b) voice: speaker-embedding similarity of the converted vocal to Lumi (data/songs/mine/lumi_voice)
and to the original singer; (c) melody: correlation and median difference of the two pitch contours;
(d) clipping and silent gaps where the singer sings.
"""
import difflib
import json
import pathlib
import re
import subprocess
import sys
import tempfile
import numpy as np
import soundfile as sf
from audio import sing_mine as M
ROOT = pathlib.Path(__file__).resolve().parents[1]
LUMI = ROOT / "data" / "songs" / "mine" / "lumi_voice"
STT_URL = "http://127.0.0.1:8096/inference"
PIECE_S = 25 # s per whisper request
GAP_S = 0.3 # s; a silent stretch this long where the singer sings is a gap
SINGING = 0.5 # the singer sings where the vocal is above this part of its loud level (lower is
# mostly the reverb tail of a phrase, which the converted vocal rightly leaves out)
def load(path, sr=44100):
x, r = sf.read(path, dtype="float32", always_2d=True)
x = x.mean(1)
if r != sr:
x = np.interp(np.arange(int(len(x) * sr / r)) * r / sr, np.arange(len(x)), x).astype(np.float32)
return x
def pieces(x, sr=44100):
"""[(start, end) samples]: the singer's phrases joined into pieces up to PIECE_S, so whisper hears whole lines
(fixed 25 s cuts split words, and whisper drops parts of a long song)."""
out = []
for a, b in M.phrases(x):
if out and b - out[-1][0] / sr <= PIECE_S:
out[-1] = (out[-1][0], int(b * sr))
else:
out.append((int(max(0.0, a - 0.2) * sr), int(b * sr)))
return out
def transcript(x, cuts, sr=44100):
out = []
with tempfile.TemporaryDirectory() as d:
for a, b in cuts:
p = pathlib.Path(d) / "p.wav"
sf.write(p, x[a:b + int(0.3 * sr)], sr)
subprocess.run(["sox", str(p), "-r", "16000", "-c", "1", "-b", "16", str(p.with_name("p16.wav"))],
check=True, stderr=subprocess.DEVNULL)
r = subprocess.run(["curl", "-s", "-F", f"file=@{p.with_name('p16.wav')}", "-F", "response_format=json",
"-F", "language=ko", STT_URL], capture_output=True, text=True).stdout
out.append(json.loads(r).get("text", ""))
return re.sub(r"\W", "", " ".join(out)).lower()
def embed(enc, x, sr=44100):
from resemblyzer import preprocess_wav
return enc.embed_utterance(preprocess_wav(x, source_sr=sr))
def check(orig_path, conv_path, start=None, end=None):
from resemblyzer import VoiceEncoder
sr = 44100
o, c = load(orig_path), load(conv_path)
n = min(len(o), len(c))
o, c = o[:n], c[:n]
if start is not None:
o, c = o[int(start * sr):int(end * sr)], c[int(start * sr):int(end * sr)]
cuts = pieces(o) # the same cuts for both
to, tc = transcript(o, cuts), transcript(c, cuts)
words = difflib.SequenceMatcher(None, to, tc).ratio()
enc = VoiceEncoder("cpu")
lumi = np.mean([embed(enc, load(p)) for p in sorted(LUMI.glob("line_*.wav"))], 0)
e_c, e_o = embed(enc, c), embed(enc, o)
cos = lambda a, b: float(np.dot(a, b) / np.linalg.norm(a) / np.linalg.norm(b))
f_o, f_c = M.pitch_contour(o), M.pitch_contour(c)
m = min(len(f_o), len(f_c))
both = (f_o[:m] > 0) & (f_c[:m] > 0)
so, sc = 12 * np.log2(f_o[:m][both] / 440), 12 * np.log2(f_c[:m][both] / 440)
diff = sc - so
octave = round(float(np.median(diff)) / 12) * 12 # a whole-octave shift is allowed
e_orig = M.rms(o) > SINGING * np.percentile(M.rms(o), 95)
e_conv = M.rms(c) > 0.02 * np.percentile(M.rms(o), 95)
gap, longest = 0, 0
for so_on, sc_on in zip(e_orig, e_conv):
gap = gap + 1 if so_on and not sc_on else 0
longest = max(longest, gap)
res = {"words_similarity": round(words, 2), "chars_original": len(to), "chars_converted": len(tc),
"voice_sim_to_lumi": round(cos(e_c, lumi), 3), "voice_sim_to_singer": round(cos(e_c, e_o), 3),
"singer_sim_to_lumi": round(cos(e_o, lumi), 3),
"pitch_corr": round(float(np.corrcoef(so, sc)[0, 1]), 3), "pitch_octave_shift": octave,
"pitch_median_err_cents": round(float(np.median(np.abs(diff - octave))) * 100),
"pitch_within_50_cents": round(float((np.abs(diff - octave) < 0.5).mean()), 2),
"pitch_frames_both_voiced": round(float(both.mean()), 2),
"clipped_samples": int((np.abs(c) >= 0.999).sum()), "longest_gap_s": round(longest * 0.01, 2),
"gaps_over_limit": longest * 0.01 >= GAP_S}
print(json.dumps(res, indent=1))
return res
if __name__ == "__main__":
a = sys.argv[1:]
check(a[0], a[1], *(float(x) for x in a[2:4])) if len(a) >= 4 else check(a[0], a[1])
+183
View File
@@ -0,0 +1,183 @@
"""Sound direction (direction of arrival) from the six mics of the head array, SRP-PHAT.
For each candidate direction the expected time differences between the mics of a ring are compared with the
measured cross-spectra (PHAT-weighted); the direction with the most energy wins.
Geometry (to calibrate, kept in doa_calib.json): six mics on a ring of `radius`; mic k sits at
offset + sign * k * 60 deg. Angles are in the head frame: 0 = where the head looks, + = to the robot's left
(same sign as head yaw). Robot (waist) angle = head yaw + this angle.
Calibration needs people at known angles. lumi.py collects them on its own: while it talks with a person
the head camera sees, each utterance of that person is a sample (camera angle = truth). After MIN_SAMPLES
samples spread over at least SPREAD_DEG it fits sign / offset / radius and writes doa_calib.json.
Or by hand:
python audio/doa.py --calibrate # stand in front of the head camera, talk, move left / right, Ctrl+C to fit
"""
import json
import math
import pathlib
import sys
import time
import numpy as np
ROOT = pathlib.Path(__file__).resolve().parents[1] # the project folder
CALIB = ROOT / "data" / "doa_calib.json"
SAMPLES = ROOT / "data" / "doa_samples.npz"
RATE = 16000
SOUND = 343.0 # m/s
NFFT, HOP = 512, 256
BAND = (300.0, 3500.0) # Hz used
GRID = np.arange(-180, 180, 2.0) # deg
MIN_SAMPLES, SPREAD_DEG = 6, 30.0
PAIRS = [(i, j) for i in range(6) for j in range(i + 1, 6)]
_freqs = np.fft.rfftfreq(NFFT, 1 / RATE)
_band = (_freqs >= BAND[0]) & (_freqs <= BAND[1])
_f = _freqs[_band]
def load_calib():
try:
c = json.loads(CALIB.read_text())
return {"radius": float(c["radius"]), "offset": float(c["offset"]), "sign": int(c["sign"]), "fitted": True}
except (FileNotFoundError, ValueError, KeyError):
return {"radius": 0.04, "offset": 0.0, "sign": 1, "fitted": False}
def cross_spectra(mics):
"""Average PHAT-normalised cross-spectra of all mic pairs: (15, n_band) complex, or None if too short."""
x = mics.astype(np.float32)
if len(x) < NFFT:
return None
win = np.hanning(NFFT).astype(np.float32)
frames = np.stack([x[i:i + NFFT] * win[:, None] for i in range(0, len(x) - NFFT, HOP)]) # (t, NFFT, 6)
spec = np.fft.rfft(frames, axis=1)[:, _band, :] # (t, F, 6)
energy = (np.abs(spec) ** 2).sum((1, 2))
keep = energy >= np.percentile(energy, 50) # the louder half of the frames: the voice, not pauses
spec = spec[keep]
g = np.stack([(spec[:, :, i] * np.conj(spec[:, :, j])) for i, j in PAIRS]) # (15, t, F)
g = g / (np.abs(g) + 1e-9)
return g.mean(1) # (15, F)
def _steering(radius, offset, sign):
"""(n_grid, 15, F) expected phase for each candidate direction."""
th = np.radians(GRID)[:, None]
phi = np.radians(offset + sign * 60.0 * np.arange(6))[None, :]
tau = -radius * np.cos(th - phi) / SOUND # (n_grid, 6): arrival time of each mic
d = np.stack([tau[:, i] - tau[:, j] for i, j in PAIRS], 1) # (n_grid, 15)
return np.exp(2j * np.pi * _f[None, None, :] * d[:, :, None])
_cache = {}
def _power(g, calib):
key = (calib["radius"], calib["offset"], calib["sign"])
if key not in _cache:
_cache.clear()
_cache[key] = _steering(*key)
return np.real((_cache[key] * g[None]).sum((1, 2))) # (n_grid,)
def estimate(mics, calib=None):
"""(angle deg in the head frame, confidence 0..1, raw angle with the default geometry)."""
calib = calib or load_calib()
g = cross_spectra(mics)
if g is None:
return 0.0, 0.0, 0.0
p = _power(g, calib)
best = int(np.argmax(p))
conf = float((p[best] - np.median(p)) / (np.abs(p).max() + 1e-9))
raw = float(GRID[int(np.argmax(_power(g, {"radius": 0.04, "offset": 0.0, "sign": 1})))])
return float(GRID[best]), max(0.0, min(1.0, conf)), raw
# ---------- calibration ----------
def add_sample(mics, true_deg):
"""Store one utterance with its true head-frame angle; refit when there are enough. Returns the new calib or None."""
g = cross_spectra(mics)
if g is None:
return None
try:
d = np.load(SAMPLES)
gs, ts = list(d["g"]), list(d["t"])
except (FileNotFoundError, KeyError, ValueError):
gs, ts = [], []
gs.append(g)
ts.append(float(true_deg))
gs, ts = gs[-60:], ts[-60:]
np.savez(SAMPLES, g=np.array(gs), t=np.array(ts))
if len(ts) >= MIN_SAMPLES and max(ts) - min(ts) >= SPREAD_DEG:
return fit(np.array(gs), np.array(ts))
return None
def fit(gs, ts):
"""Grid search sign / offset / radius that best explains the samples; saves doa_calib.json."""
best = None
for sign in (1, -1):
for radius in (0.03, 0.035, 0.04, 0.045, 0.05):
for offset in np.arange(0, 360, 5.0):
c = {"radius": radius, "offset": float(offset), "sign": sign}
err = []
for g, t in zip(gs, ts):
a = GRID[int(np.argmax(_power(g, c)))]
err.append(abs((a - t + 180) % 360 - 180))
score = float(np.median(err))
if best is None or score < best[0]:
best = (score, c)
score, c = best
c["median_error_deg"] = round(score, 1)
c["samples"] = len(ts)
c["time"] = time.strftime("%Y-%m-%d %H:%M")
CALIB.write_text(json.dumps(c, indent=1))
_cache.clear()
return c
def calibrate_by_hand():
"""Talk in front of the head camera from several places; the camera gives the true angle."""
from audio import mic
import threading
from vision.camview import RemoteDetector
det = RemoteDetector("head")
seen = {"angle": None, "time": 0.0}
def watch():
while True:
_, people = det.read()
near = [p for p in people if p["distance_m"] and p["distance_m"] < 3.0]
if len(near) == 1: # exactly one person: no doubt who talks
seen.update(angle=near[0]["angle_deg"] - det.head_yaw * det.head_sign, time=time.time())
threading.Thread(target=watch, daemon=True).start()
m = mic.get()
print("Stand 1-2 m in front of the robot, alone in the head camera's view, and talk for a few seconds.\n"
"Then move ~1 m to the left, talk; to the right, talk. Ctrl+C when done.")
n = 0
try:
while True:
u = m.next(1.0)
if u is None or u.seconds < 0.8:
continue
if time.time() - seen["time"] > 1.0:
print(" (heard speech but no single person in view - skipped)")
continue
n += 1
c = add_sample(u.mics, seen["angle"])
print(f" sample {n}: person at {seen['angle']:+.0f} deg, raw estimate {estimate(u.mics)[2]:+.0f} deg"
+ (f" -> calibrated: {c}" if c else ""))
except KeyboardInterrupt:
d = np.load(SAMPLES)
if len(d["t"]) >= 3:
print("fit:", fit(d["g"], d["t"]))
if __name__ == "__main__":
if "--calibrate" in sys.argv:
calibrate_by_hand()
else:
print(load_calib())
+185
View File
@@ -0,0 +1,185 @@
"""Listening: one utterance from the head microphone array (via mic.py) turned into text.
python audio/ears.py # listen once, print what was said (English or Korean)
Recording, speech detection and "do not listen while Lumi talks" are in mic.py (one always-on recording that
lumi.py also uses for the wake word). Speech-to-text: whisper.cpp (GPU) server with large-v3-turbo on
127.0.0.1:8096, started when needed.
"""
import io
import json
import re
import pathlib
import subprocess
import time
import urllib.request
import uuid
import wave
from audio import mic
ROOT = pathlib.Path(__file__).resolve().parents[1] # the project folder
RATE = mic.RATE
STT_URL = "http://127.0.0.1:8096"
WHISPER_SERVER = ROOT / "whisper.cpp/build/bin/whisper-server"
WHISPER_MODEL = ROOT / "models/ggml-large-v3-turbo-q5_0.bin"
PROMPT = "Hi Lumi. Hey Lumi. 루미야." # helps whisper spell the robot's name
last = {} # levels of the last listen() call, for the log: noise, threshold, peak
def ensure_stt_server():
try:
urllib.request.urlopen(f"{STT_URL}/", timeout=1)
return
except OSError:
pass
log = open(ROOT / "logs" / "whisper_server.log", "a")
subprocess.Popen([str(WHISPER_SERVER), "-m", str(WHISPER_MODEL), "--host", "127.0.0.1", "--port", "8096",
"-l", "auto", "-nt"], stdout=log, stderr=log, start_new_session=True)
for _ in range(120):
time.sleep(0.5)
try:
urllib.request.urlopen(f"{STT_URL}/", timeout=1)
return
except OSError:
pass
raise RuntimeError("whisper-server did not start, see whisper_server.log")
def record(wait_s=8.0, on_start=None, abort=None):
"""Wait up to wait_s for speech to start, then until it ends. Returns a mic.Utterance or None.
abort: optional function checked every 30 ms; when it returns True, stop and return None."""
m = mic.get()
m.clear() # only speech that starts from now on
t0, started = time.time(), False
try:
while True:
if abort and abort():
return None
u = m.next(0.03)
if u is not None and u.t_end > t0:
return u
if m.in_speech and not started:
started = True
if on_start:
on_start()
if not m.in_speech and not started and time.time() - t0 > wait_s:
return None
finally:
last.update(noise=round(m.noise), threshold=round(m.threshold))
def louder(audio, target=0.7):
"""Quiet speech from far away: raise the peak to `target` of full scale (at most 12x) for speech-to-text."""
import numpy as np
peak = float(np.abs(audio).max()) if len(audio) else 0.0
if peak < 1:
return audio
gain = min(12.0, target * 32767 / peak)
return np.clip(audio.astype(np.float32) * gain, -32767, 32767).astype(np.int16) if gain > 1.05 else audio
LANGS = {"english": "en", "korean": "ko"}
MIN_LOGPROB = -1.0 # below this average token log-probability whisper was guessing
last_stt = {} # language / confidence of the last transcription (see understood())
HEARD_DIR = ROOT / "logs" / "heard" # the last HEARD_KEEP utterances as wav, to check what Lumi really heard
HEARD_KEEP = 50
def _infer(wav, prompt, language=None):
"""One whisper-server call: (text, language, language probability, average token log-probability)."""
boundary = uuid.uuid4().hex
fields = {"response_format": "verbose_json", "prompt": prompt, **({"language": language} if language else {})}
body = "".join(f"--{boundary}\r\nContent-Disposition: form-data; name=\"{k}\"\r\n\r\n{v}\r\n"
for k, v in fields.items()).encode()
body += (f"--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"a.wav\"\r\n"
f"Content-Type: audio/wav\r\n\r\n").encode() + wav + f"\r\n--{boundary}--\r\n".encode()
req = urllib.request.Request(f"{STT_URL}/inference", body,
{"Content-Type": f"multipart/form-data; boundary={boundary}"})
with urllib.request.urlopen(req, timeout=30) as r:
out = json.loads(r.read())
segs = out.get("segments") or []
logprob = sum(s.get("avg_logprob", 0.0) for s in segs) / len(segs) if segs else 0.0
lang = out.get("language") or out.get("detected_language")
return out.get("text", "").strip(), lang, out.get("detected_language_probability"), logprob
def transcribe(audio, prompt=PROMPT):
"""int16 mono 16 kHz -> text (empty string if nothing understood). Also fills last_stt.
Whisper sometimes names another language (Japanese) for Korean said from afar and writes only the prompt's
"Lumi." (2026-10-20: "컵 좀 주세요" came back as "Lumi." [japanese] four times): then it is asked again with
Korean and with English fixed, and the surer of the two is kept."""
ensure_stt_server()
audio = louder(audio)
buf = io.BytesIO()
with wave.open(buf, "wb") as w:
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(RATE)
w.writeframes(audio.tobytes())
wav = buf.getvalue()
try:
HEARD_DIR.mkdir(parents=True, exist_ok=True)
(HEARD_DIR / time.strftime("%H%M%S.wav")).write_bytes(wav)
for old in sorted(HEARD_DIR.glob("*.wav"), key=lambda p: p.stat().st_mtime)[:-HEARD_KEEP]: # by time: names wrap at midnight
old.unlink()
except OSError:
pass
text, lang, prob, logprob = _infer(wav, prompt)
only_name = re.fullmatch(r"\W*(lumi|루미야?)\W*", text, re.I) and len(audio) > 1.5 * RATE
if lang not in LANGS or only_name:
tries = [(text, lang, prob, logprob)] if lang in LANGS and not only_name else []
for code, name in (("ko", "korean"), ("en", "english")):
t2, _, _, lp2 = _infer(wav, prompt, code)
tries.append((t2, name, None, lp2))
text, lang, prob, logprob = max(tries, key=lambda r: r[3])
last_stt.clear()
last_stt.update(text=text, language=lang, lang_prob=prob, logprob=round(logprob, 2))
# whisper writes things like "[BLANK_AUDIO]" or "(music)" for non-speech
return "" if text.startswith(("[", "(", "*")) else text
def understood(min_logprob=MIN_LOGPROB):
"""Was the last transcription clear English or Korean? (else Lumi asks the visitor to say it again)
The text must also be written in that language: Whisper turns noise or Lumi's own Korean voice into
English sentences tagged 'korean' ("I'll see you next time.", 2026-10-13)."""
lang, text = last_stt.get("language"), last_stt.get("text", "")
if lang not in LANGS or last_stt.get("logprob", 0.0) < min_logprob:
return False
return bool(re.search(r"[가-힣]", text)) == (lang == "korean")
def heard_clearly(min_logprob=MIN_LOGPROB):
"""English or Korean said clearly, whatever script whisper wrote it in ("Can you sing song?" came tagged
'korean', 2026-10-21): lumi.py takes it only for its own fixed commands."""
return last_stt.get("language") in LANGS and last_stt.get("logprob", 0.0) >= min_logprob
def heard_lang(default="en"):
"""'en' or 'ko': the language of the last transcription."""
return LANGS.get(last_stt.get("language"), default)
def listen(wait_s=8.0, on_start=None, abort=None, full=False):
"""Record one utterance and transcribe it. Returns text or None (nobody spoke, or aborted).
full=True: returns (text, mic.Utterance) instead, for the sound direction."""
u = record(wait_s, on_start, abort)
if u is not None:
last["peak"] = round(u.peak)
if u is None or u.seconds < 0.4:
return (None, u) if full else None
text = transcribe(u.mono) or None
return (text, u) if full else text
if __name__ == "__main__":
ensure_stt_server()
print("Say something (English or Korean)...")
u = record(10, on_start=lambda: print(" (hearing you)"))
if u is None:
print("nothing heard")
else:
t = time.time()
print(f"you said: {transcribe(u.mono)!r} ({u.seconds:.1f} s audio, STT {time.time() - t:.2f} s)")
+39
View File
@@ -0,0 +1,39 @@
"""Make a training set of Lumi's voice (Supertonic-3, the voice audio/mouth.py speaks with) for the voice-conversion
model of audio/cover.py: Lumi's own example answers (assistant/talk_examples.py), Korean and English, at varied
speeds. Local only (data/songs/mine/lumi_voice/train/).
.venv/bin/python audio/lumi_voice_set.py [count]
"""
import pathlib
import random
import sys
import numpy as np
import soundfile as sf
from assistant import talk_examples
from audio import mouth
OUT = pathlib.Path(__file__).resolve().parents[1] / "data" / "songs" / "mine" / "lumi_voice" / "train"
COUNT = 300 # clips, about 15 minutes
SPEEDS = (0.8, 1.05) # TTS speed range: slower clips give long vowels
def make(count=COUNT):
OUT.mkdir(parents=True, exist_ok=True)
tts = mouth._load()
rng = random.Random(7)
replies = sorted({r for _, _, _, r in talk_examples.EXAMPLES if 10 <= len(r) <= 160})
rng.shuffle(replies)
total = 0.0
for i, text in enumerate(replies[:count]):
wav, _ = tts.synthesize(text, voice_style=mouth._style, lang=mouth.lang_of(text), total_steps=8,
speed=rng.uniform(*SPEEDS))
wav = np.asarray(wav, np.float32).reshape(-1)
sf.write(OUT / f"{i:04d}.wav", wav, tts.sample_rate)
total += len(wav) / tts.sample_rate
print(f"{OUT}: {min(count, len(replies))} clips, {total / 60:.1f} min")
if __name__ == "__main__":
make(int(sys.argv[1]) if len(sys.argv) > 1 else COUNT)
+298
View File
@@ -0,0 +1,298 @@
"""Always-on microphone: the head mic array (and a wireless clip mic if one is plugged in), cut into utterances.
Head array (AIUI-USB-MC): 8 channels at 16 kHz; channels 0-5 are the six mics of the ring, 6-7 are silent.
It is far from a speaker's mouth, so speech-to-text works better with a wireless clip mic (DJI Mic Mini):
when its receiver shows up as a sound card (EXTERNAL_NAMES), utterances are cut from the clip mic and their
text comes from it, while the head array keeps recording in parallel for the sound direction (doa.py): the
six-mic audio of the same time span is taken from a ring buffer. Choose with mic_source.txt: auto | head | clip.
An ALSA device can be opened only once, so everything that listens goes through here. An energy detector
cuts utterances: speech starts when the level stays above START_FACTOR x the background noise for
START_FRAMES frames and ends after END_SILENCE of quiet.
While Lumi itself speaks (mouth.py calls speaking()), the head array records nothing (the speaker is ~25x
louder than a voice there). The clip mic keeps listening (BARGE_IN): its utterances are marked during_speech, so
lumi.py can stop talking when the visitor says "stop" / "thanks" or asks something new.
python audio/mic.py # print every utterance: source, length, level and the direction
"""
import collections
import queue
import re
import subprocess
import threading
import time
from pathlib import Path
import numpy as np
ROOT = Path(__file__).resolve().parents[1] # the project folder
SOURCE_FILE = ROOT / "data" / "mic_source.txt"
DEVICE = "hw:CARD=AIUIUSBMC"
EXTERNAL_NAMES = r"DJI|Wireless|Mic Mini|MIC MINI|RX" # sound card names of a clip-mic receiver
RATE, CHANNELS, MICS = 16000, 8, slice(0, 6)
FRAME = 480 # 30 ms
START_FACTOR = 1.8 # speech = louder than START_FACTOR x background noise (2.5 missed
# people 4-5 m away: only 1 of 4 phrases was heard, 2026-10-12)
MIN_LEVEL = 250 # ... and at least this RMS (head array; room noise is ~180)
MIN_LEVEL_CLIP = 300 # ... (clip mic: close to the mouth, quiet room noise)
START_FRAMES = 4 # 120 ms of speech to start
END_LEVEL = 1.0 # quiet = below this x the start threshold (0.7 kept room noise ~180-250 "speech")
END_SILENCE = 0.6 # s of quiet that ends an utterance
MAX_UTTERANCE = 8.0 # s (12 s: in a room with music an utterance never got quiet enough
# to end, every one ran the full 12 s, 2026-10-21)
PRE_ROLL = 10 # frames kept before the start (300 ms)
AFTER_SPEAKING = 0.4 # s still ignored after Lumi stopped talking (room echo)
BARGE_IN = True # clip mic: keep listening while Lumi talks (interruptions)
RING_S = 20.0 # s of head-array audio kept for the sound direction of clip-mic utterances
class Utterance:
def __init__(self, mics, mono, t_start, t_end, peak, source, during_speech=False):
self.mics = mics # int16 (n, 6) head array (for doa), may be empty
self.mono = mono # int16 mono (for speech-to-text)
self.t_start, self.t_end, self.peak, self.source = t_start, t_end, peak, source
self.during_speech = during_speech # recorded while Lumi was talking (clip mic only)
@property
def seconds(self):
return len(self.mono) / RATE
class Segmenter:
"""Energy speech detector over 30 ms frames."""
def __init__(self, min_level):
self.min_level = min_level
self.levels = collections.deque(maxlen=300) # last 9 s of frame levels, for the noise floor
self.before = collections.deque(maxlen=PRE_ROLL)
self.frames, self.voiced, self.silent, self.peak = [], 0, 0, 0.0
self.in_speech, self.started = False, 0.0
self.noise = self.threshold = 0.0
def reset(self):
self.before.clear()
self.frames, self.voiced, self.in_speech = [], 0, False
def feed(self, frame, level, now):
"""Returns (frames, t_start, t_end, peak) when an utterance ended, else None."""
if not self.in_speech:
self.levels.append(level)
self.noise = float(np.percentile(self.levels, 30))
self.threshold = max(self.min_level, START_FACTOR * self.noise)
self.before.append(frame)
self.voiced = self.voiced + 1 if level > self.threshold else 0
if self.voiced >= START_FRAMES:
self.in_speech, self.started = True, now - (len(self.before) * FRAME / RATE)
self.frames, self.silent, self.peak = list(self.before), 0, level
return None
self.frames.append(frame)
self.peak = max(self.peak, level)
self.silent = self.silent + 1 if level < self.threshold * END_LEVEL else 0
if self.silent * FRAME / RATE >= END_SILENCE or now - self.started > MAX_UTTERANCE:
out = (self.frames, self.started, now, self.peak)
self.frames, self.voiced, self.in_speech = [], 0, False
self.before.clear()
return out
return None
def find_external():
"""ALSA name of a clip-mic receiver (e.g. DJI Mic Mini RX), or None."""
choice = SOURCE_FILE.read_text().strip().lower() if SOURCE_FILE.exists() else "auto"
if choice == "head":
return None
out = subprocess.run(["arecord", "-l"], capture_output=True, text=True).stdout
for m in re.finditer(r"card (\d+): (\S+) \[([^\]]*)\]", out):
num, short, long_ = m.groups()
if "AIUI" in short or "AIUI" in long_:
continue
if re.search(EXTERNAL_NAMES, short + " " + long_):
return f"plughw:CARD={short},DEV=0"
return None
class Mic(threading.Thread):
def __init__(self):
super().__init__(daemon=True)
self.utterances = queue.Queue(maxsize=20)
self.ring = collections.deque(maxlen=int(RING_S * RATE / FRAME)) # (time, (480, 6) int16)
self.ring_lock = threading.Lock()
self.head_seg, self.clip_seg = Segmenter(MIN_LEVEL), Segmenter(MIN_LEVEL_CLIP)
self.external = None # ALSA device of the clip mic, when found
self.muted_until = 0.0
self.speaking_now = False
self.error = None
# the active detector's state (ears.py reads these)
@property
def seg(self):
return self.clip_seg if self.external else self.head_seg
@property
def in_speech(self):
return self.seg.in_speech
@property
def noise(self):
return self.seg.noise
@property
def threshold(self):
return self.seg.threshold
# ---------- used by mouth.py ----------
def speaking(self, on):
self.speaking_now = on
if not on:
self.muted_until = time.time() + AFTER_SPEAKING
def muted(self):
return self.speaking_now or time.time() < self.muted_until
# ---------- used by listeners ----------
def clear(self):
while not self.utterances.empty():
try:
self.utterances.get_nowait()
except queue.Empty:
break
def next(self, timeout):
try:
return self.utterances.get(timeout=timeout)
except queue.Empty:
return None
def _put(self, u):
try:
self.utterances.put_nowait(u)
except queue.Full: # nobody is reading: keep the newest
try:
self.utterances.get_nowait()
except queue.Empty:
pass
self.utterances.put_nowait(u)
def head_audio(self, t_start, t_end):
"""Six-mic audio recorded between two times (from the ring buffer)."""
with self.ring_lock:
frames = [x for t, x in self.ring if t_start <= t <= t_end + 0.05]
return np.concatenate(frames) if frames else np.zeros((0, 6), np.int16)
# ---------- recording threads ----------
def run(self):
threading.Thread(target=self._clip_loop, daemon=True).start()
while True:
try:
self._record_head()
except Exception as e:
self.error = repr(e)
time.sleep(1.0) # arecord ended (device gone?): start again
def _record_head(self):
proc = subprocess.Popen(["arecord", "-q", "-D", DEVICE, "-f", "S16_LE", "-r", str(RATE), "-c", str(CHANNELS),
"-t", "raw"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
nbytes = FRAME * CHANNELS * 2
try:
while True:
raw = proc.stdout.read(nbytes)
if len(raw) < nbytes:
return
x = np.frombuffer(raw, np.int16).reshape(-1, CHANNELS)[:, MICS]
now = time.time()
with self.ring_lock:
self.ring.append((now, x))
if self.external: # the clip mic cuts the utterances
continue
if self.muted(): # Lumi is talking: drop everything
self.head_seg.reset()
continue
level = float(np.sqrt(np.mean(x.astype(np.float32).mean(1) ** 2)))
done = self.head_seg.feed(x, level, now)
if done:
frames, t0, t1, peak = done
mics = np.concatenate(frames)
self._put(Utterance(mics, mics.astype(np.float32).mean(1).astype(np.int16), t0, t1, peak, "head"))
finally:
proc.kill()
def _clip_loop(self):
"""Look for a clip-mic receiver every few seconds; record from it while it is there."""
while True:
dev = find_external()
if not dev:
self.external = None
time.sleep(5.0)
continue
self.external = dev
try:
self._record_clip(dev)
except Exception as e:
self.error = repr(e)
self.external = None
time.sleep(2.0)
def _record_clip(self, dev):
proc = subprocess.Popen(["arecord", "-q", "-D", dev, "-f", "S16_LE", "-r", str(RATE), "-c", "1", "-t", "raw"],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
nbytes = FRAME * 2
talking_since = None # Lumi started talking at (for during_speech)
try:
while True:
raw = proc.stdout.read(nbytes)
if len(raw) < nbytes:
return
x = np.frombuffer(raw, np.int16)
now = time.time()
if self.muted():
if not BARGE_IN:
self.clip_seg.reset()
continue
talking_since = talking_since or now
elif talking_since and not self.clip_seg.in_speech:
talking_since = None
level = float(np.sqrt(np.mean(x.astype(np.float32) ** 2)))
done = self.clip_seg.feed(x, level, now)
if done:
frames, t0, t1, peak = done
during = talking_since is not None and t1 >= talking_since
self._put(Utterance(self.head_audio(t0, t1), np.concatenate(frames), t0, t1, peak, "clip", during))
finally:
proc.kill()
_mic = None
_lock = threading.Lock()
def get():
"""The shared, running microphone."""
global _mic
with _lock:
if _mic is None:
_mic = Mic()
_mic.start()
return _mic
def speaking(on):
"""mouth.py: Lumi starts / stops talking (no-op if nothing listens in this program)."""
if _mic is not None:
_mic.speaking(on)
if __name__ == "__main__":
from audio import doa
m = get()
time.sleep(1.0)
print(f"listening on {'clip mic ' + m.external if m.external else 'the head array'} ... (Ctrl+C to stop)")
try:
while True:
u = m.next(1.0)
if u is None:
continue
ang = doa.estimate(u.mics) if len(u.mics) else (0.0, 0.0, 0.0)
print(f"[{u.source}] {u.seconds:4.1f} s peak {u.peak:5.0f} noise {m.noise:4.0f} "
f"direction {ang[0]:+5.0f} deg (confidence {ang[1]:.2f})")
except KeyboardInterrupt:
pass
+210
View File
@@ -0,0 +1,210 @@
"""Speaking: text -> speech (Supertonic-3, English and Korean, on the robot) -> USB speaker.
python audio/mouth.py "Hello, I am Lumi."
python audio/mouth.py "안녕하세요, 저는 루미예요."
Long answers are split into sentences: the next sentence is synthesised while the current one plays,
so Lumi starts talking after the first sentence is ready (about 1 s). say_stream() takes sentences while
they are still being written by the LLM, so speech starts before the whole answer exists.
Fixed phrases (greetings) are synthesised once and kept (CACHED), so they play at once.
While Lumi talks the microphone is muted (mic.speaking), so it never hears itself.
"""
import pathlib
import queue
import re
import subprocess
import sys
import threading
import time
import numpy as np
from audio import mic
ROOT = pathlib.Path(__file__).resolve().parents[1] # the project folder
DEVICE = "plughw:CARD=Device,DEV=0" # "USB Audio Device"
VOICE = "F1" # F1-F5 female, M1-M5 male
STEPS = 4 # quality/speed: 4 fast ... 8 best
SPEED = 0.92 # < 1 = slower; 1.05 sounded rushed
SPEED_MIN, SPEED_MAX = 0.72, 1.2 # what "speak slower / faster" may set (Supertonic takes 0.7 to 2.0)
SPLIT_WORDS = 8 # a first sentence this long is said in two parts, cut after its first
# comma: the first part is synthesised in ~0.7 s instead of ~1.8 s
VOLUME = 55 # % of the USB speaker mixer (100 % disturbed people in the office)
CACHED = ["Hi, I'm Lumi, the assistant robot. How can I help you?", "안녕하세요, 저는 루미예요. 무엇을 도와드릴까요?",
"Yes?", "네?", "Okay, I'm coming.", "네, 갈게요.", "I'm right here.",
"Sorry, I can't get closer from here.", "How can I help you?", "무엇을 도와드릴까요?",
"Let me check.", "확인해 볼게요.", "Okay, I'll be quiet.", "네, 조용히 할게요.",
"Sorry, I'm not connected to the internet right now, so I can't look that up.",
"Yes? How can I help?", "네? 무엇을 도와드릴까요?",
"Welcome back! How can I help you?", "다시 오셨네요, 무엇을 도와드릴까요?", "Okay, I'm going to my charging dock.", "네, 충전소로 갈게요.",
"Sorry, driving is switched off."] + [f"Okay, I'm going to p{i}." for i in range(1, 11)]
_tts = None
_style = None
_cache = {}
_volume_set = False
_recent = [] # (time, sentence) Lumi said lately: to tell its own echo from a visitor
last_voice = 0.0 # time.time() when the last say_stream() began to play (lumi.py logs it)
def recent_speech(seconds=30.0):
"""What Lumi said in the last seconds (lumi.py ignores its own voice picked up by the clip mic).
Long sentences take 15 s and more to say, so the window is long."""
now = time.time()
return " ".join(t for when, t in _recent if now - when < seconds)
VOLUME_FILE = ROOT / "data" / "volume.txt" # set from the dashboard (api/server.py /volume); overrides VOLUME
def volume():
try:
return max(0, min(100, int(VOLUME_FILE.read_text().strip())))
except (FileNotFoundError, ValueError):
return VOLUME
def set_volume(percent=None):
"""Apply (and with percent: store) the speaker volume."""
if percent is not None:
VOLUME_FILE.write_text(str(int(max(0, min(100, percent)))))
subprocess.run(["amixer", "-q", "-c", "Device", "sset", "Speaker", f"{volume()}%"], check=False)
SPEED_FILE = ROOT / "data" / "speech_speed.txt" # set by voice ("speak slower", assistant/voice_words.py)
def speed():
try:
return max(SPEED_MIN, min(SPEED_MAX, float(SPEED_FILE.read_text().strip())))
except (FileNotFoundError, ValueError):
return SPEED
def set_speed(value):
"""Store the speaking speed; the cached fixed phrases were made at the old one, so they are made when said."""
SPEED_FILE.write_text(f"{max(SPEED_MIN, min(SPEED_MAX, value)):.2f}")
_cache.clear()
def _set_volume():
global _volume_set
if not _volume_set:
set_volume()
_volume_set = True
def _load():
global _tts, _style
_set_volume()
if _tts is None:
from supertonic import TTS
_tts = TTS(model="supertonic-3", model_dir=ROOT / "models/supertonic3", auto_download=False,
intra_op_num_threads=8)
_style = _tts.get_voice_style(VOICE)
return _tts
def lang_of(text):
return "ko" if re.search(r"[가-힣]", text) else "en"
def sentences(text):
parts = re.split(r"(?<=[.!?。!?])\s+", text.strip())
return [p for p in parts if p]
def first_parts(sentence):
"""A long first sentence cut after its first comma (3 words in or later), so the voice starts sooner."""
m = re.search(r"[,;]\s", sentence)
if len(sentence.split()) < SPLIT_WORDS or not m or len(sentence[:m.start()].split()) < 3:
return [sentence]
return [sentence[:m.start() + 1], sentence[m.end():]]
_play_lock = threading.Lock() # one sentence at a time (a skill's result is spoken from another thread)
def _play(wav, rate, abort=None):
"""Play; returns False if aborted."""
pcm = (np.clip(wav, -1, 1) * 32767).astype(np.int16).tobytes()
with _play_lock:
mic.speaking(True)
try:
return _play_pcm(pcm, rate, abort)
finally:
mic.speaking(False)
def _play_pcm(pcm, rate, abort):
p = subprocess.Popen(["aplay", "-q", "-D", DEVICE, "-f", "S16_LE", "-r", str(rate), "-c", "1", "-t", "raw"],
stdin=subprocess.PIPE)
def feed():
try:
p.stdin.write(pcm)
p.stdin.close()
except (BrokenPipeError, ValueError): # aplay was killed (abort)
pass
threading.Thread(target=feed, daemon=True).start()
while p.poll() is None:
if abort and abort():
p.kill()
return False
time.sleep(0.05)
return True
def _synth(text, lang):
if text in _cache:
return _cache[text]
wav, _ = _tts.synthesize(text, voice_style=_style, lang=lang, total_steps=STEPS, speed=speed())
return np.asarray(wav).reshape(-1)
def say_stream(pieces, lang=None, abort=None):
"""Speak text that arrives in pieces (e.g. sentences from a streaming LLM); returns the full text.
Synthesis of the next sentence runs while the current one plays."""
tts = _load()
rate = tts.sample_rate
q = queue.Queue() # unbounded: the synth thread always finishes
spoken = []
def synth():
try:
for piece in pieces:
for s in sentences(piece):
for part in [s] if spoken else first_parts(s):
spoken.append(part)
q.put((part, _synth(part, lang or lang_of(part))))
finally:
q.put(None)
global last_voice
threading.Thread(target=synth, daemon=True).start()
first = True
while (item := q.get()) is not None:
text, wav = item
if first:
last_voice, first = time.time(), False
_recent.append((time.time(), text))
del _recent[:-12]
if not _play(wav, rate, abort):
break
return " ".join(spoken)
def say(text, lang=None, abort=None):
"""Speak text and return when finished (or when abort() becomes True)."""
say_stream([text], lang, abort)
def warm_up():
"""Load the model, run it once so the first real sentence is fast, and prepare the fixed phrases."""
tts = _load()
tts.synthesize("Hi.", voice_style=_style, lang="en", total_steps=2)
for text in CACHED:
_cache[text] = _synth(text, lang_of(text))
if __name__ == "__main__":
say(" ".join(sys.argv[1:]) or "Hello, I am Lumi Robot Assistant. How can I help you?")
+48
View File
@@ -0,0 +1,48 @@
"""Split a song into vocals and accompaniment (Demucs htdemucs) for audio/sing_mine.py. Offline tool: runs only in
the separate render venv (.venv-songs, torch CPU + demucs), never in the robot's .venv.
.venv-songs/bin/python audio/separate.py data/songs/mine/BIGBANG_FANTASTIC_BABY.mp3
Writes <folder>/<name>/vocals.wav and <folder>/<name>/mr.wav (44.1 kHz stereo) next to the song.
"""
import pathlib
import sys
import numpy as np
import soundfile as sf
import torch
from demucs.apply import apply_model
from demucs.pretrained import get_model
MODEL = "htdemucs" # 4 stems: drums, bass, other, vocals
THREADS = 12 # CPU threads (the Thor has 14 cores; leave some for the robot's services)
def separate(path):
path = pathlib.Path(path)
out = path.with_suffix("")
out.mkdir(exist_ok=True)
torch.set_num_threads(THREADS)
model = get_model(MODEL)
model.eval()
wav, sr = sf.read(path, dtype="float32", always_2d=True)
assert sr == model.samplerate, (sr, model.samplerate)
x = torch.from_numpy(wav.T.copy())
if x.shape[0] == 1:
x = x.repeat(2, 1)
ref = x.mean(0)
mean, std = ref.mean(), ref.std()
with torch.no_grad():
stems = apply_model(model, ((x - mean) / std)[None], shifts=1, split=True, overlap=0.25, progress=True)[0]
stems = stems * std + mean
names = model.sources
vocals = stems[names.index("vocals")].numpy().T
mr = sum(stems[i] for i, n in enumerate(names) if n != "vocals").numpy().T
sf.write(out / "vocals.wav", np.clip(vocals, -1, 1), sr)
sf.write(out / "mr.wav", np.clip(mr, -1, 1), sr)
print(f"{out}/vocals.wav, mr.wav")
if __name__ == "__main__":
for p in sys.argv[1:]:
separate(p)
+378
View File
@@ -0,0 +1,378 @@
"""Singing: play a pre-rendered song (data/songs/<id>.wav, made by audio/sing_render.py, or data/songs/mine/<id>.wav,
made by audio/sing_mine.py from the owner's own files) and move the head with it.
python audio/sing.py # list the songs
python audio/sing.py twinkle # sing one (plays on the speaker and moves the head)
Each <id>.json holds the title, the names it is asked by and the lyrics; the public domain songs also the melody
and chords, the owner's songs (local only, never copied off the robot) their head moves timed to the beat. The song is played through mouth._play (the microphone is muted the same way as for speech,
and abort() stops it within 50 ms). The head turns to yaw 0 / pitch 0 and dances around it in a thread, following the
music: small diagonal bobs landing on the beats in energetic parts, a quick sweep with a dip on a bar's accent or a
phrase start, slower sways in calm parts, each move called early enough (the owner's measured head timing) to land
on its beat, one call at a time; it goes back to yaw 0 / pitch 0 when the song ends or is stopped. Never the lift, the waist or the arm.
"""
import json
import pathlib
import random
import re
import sys
import threading
import time
import numpy as np
ROOT = pathlib.Path(__file__).resolve().parents[1]
SONGS = ROOT / "data" / "songs"
MINE = SONGS / "mine" # the owner's songs: local only
YAW_SWAY = 40.0 # deg; head yaw stays within +- this while singing (owner: wider, 2026-10-21)
PITCH_RANGE = (0.0, 28.0) # deg, absolute head pitch while singing (0 = level, + = up; owner: higher)
# head timing measured by the owner (2026-10-20, body API, vel = acc = 100, head.status polled every 20 ms): the head
# starts 0.2 s after the call and turns ~40 deg/s after that (15 / 6 deg diagonal reached at 0.87 s, 25 / 10 deg at
# 1.12 s); the call returns ~0.1 s after it arrives. Speed is no higher above vel 50. Overlapping moveto calls hang
# the body API: a move is sent only after the last one returned.
REACH_S = 0.5 # s from the call until a small move arrives (start delay + speeding up)
RETURN_S = 0.6 # s from the call until it returns, for a small move
HEAD_DEG_S = 40.0 # deg/s of the larger axis at vel >= VEL_FULL
VEL_FULL = 50 # speed ratio % from which the head is at its full speed
VEL_LIVELY, VEL_CALM, VEL_CALMEST = 100, 100, 80 # speed ratio %: energetic / calm / the calmest parts
ENERGETIC = 0.4 # music energy (0..1) from which the head bobs on the beat
CALMEST = 0.15 # below this energy the head sways slowly
BOB_DEG = (7.0, 12.0) # deg, a beat's bob (diagonal nod / tilt), alternating sides
ACCENT_DEG = (25.0, 38.0) # deg, a bar's or phrase's accent: a quick sweep with a dip
SWAY_DEG = (12.0, 20.0) # deg, a calm sway
ACCENT_EVERY_S = 1.2 # s, at least this between two accents
CENTRE_PITCH = 12.0 # deg; the dance moves around yaw 0, this pitch
GAP_S = 0.02 # s between a call returning and the next one
MIN_CHANGE = (1.5, 0.8) # deg; every move changes yaw and pitch at least this much
MIN_TURN_DEG = 20.0 # two moves in a row differ in direction by at least this (never one line)
HEAD_VEL = 70 # speed ratio % for turning to yaw 0 / pitch 0 before and after the song
LATE_S = 0.4 # s; a move this late is skipped (the previous one took longer)
RETURN_WAIT_S = 3.0 # s a new song waits for the head to get back from the last one
SING = re.compile(r"\bsing\b|\bsay (?:a |some )?songs?\b|" # whisper writes "let's say song"
r"\b(?:play|put on|turn on|start)(?: me| us)? (?:a |some |any |another |the |your )?(?:songs?|music|tunes?)\b|"
r"\b(?:another|different|next|new|other) (?:song|tune)\b|\b(?:want|like|love) to hear (?:a |some )?(?:song|music)\b|"
r"^\W*(?:lumi\W*)?(?:a |some )?(?:song|music)(?:\W+(?:please|lumi))*\W*$|"
r"(?:노래|음악|(?<![가-힣])곡)\s*(?:를|을|좀|하나|한\s*곡|한\s*번|한번|도|이나|나|이든|든|라도|\s)*"
r"(?:불러|부르|들려|해|틀어|틀|뽑아|부탁|재생|플레이|(?:할|부를)\s*(?:수|줄)\s*(?:있|알))|"
r"노래\s*(?:좀|하나)?\s*(?:듣고\s*싶|들을래|듣자)|(?:다른|딴|다음)\s*(?:노래|곡)|(?:다른|딴)\s*(?:거|걸|걸로)\s*(?:불러|들려|틀어)|^\W*(?:노래|음악)\s*(?:좀|하나)?\W*$", re.I)
SING_TITLE = re.compile(r"(불러|들려|틀어) ?(줘|주세요|줄래|봐|볼래)|\b(?:sing|play)\b") # "아리랑 불러 줘": a title said with it
SONG_LIST = re.compile(r"\b(?:what|which) (?:kinds? of |sort of |other )?(?:songs?|music|tunes)\b|\bwhat can you sing\b|"
r"\bsongs? (?:do |can |could )?you (?:know|sing|have)\b|\b(?:know|have) any (?:other )?songs\b|"
r"\b(?:list|names?) of (?:your |the )?songs\b|"
r"(?:무슨|어떤|뭔|어느)\s*(?:노래|곡)(?!\s*(?:이든|든|이나|나|라도))|노래\s*(?:는|를|은)?\s*(?:뭐|뭘|몇)|"
r"아는\s*노래|부를\s*(?:수\s*있는|줄\s*아는)\s*노래|노래\s*목록", re.I)
NOT_REQUEST = re.compile(r"\b(?:do|did) you (?:really )?(?:like|love|enjoy)\b|"
r"\bwho sings?\b|\bfavou?rite\b|좋아하는|좋아해|잘\s*(?:해|하|불러)", re.I)
# right after a song (or the list of songs): a short word switches or repeats it
AFTER_SONG = re.compile(r"^\W*(?:(?:lumi|ok|okay|no|nah|um|please|then|now|and)\W+)*(?:sing |play )?"
r"(?:another(?: one)?|(?:the )?next(?: one)?|a different one|something (?:else|different)|"
r"not (?:this|that)(?: one)?|(?:it |that )?again|one more(?: time)?|once more|more)"
r"(?:\W+(?:please|lumi))*\W*$|"
r"^\W*(?:루미야?\W*)?(?:아니\W*)?(?:(?:그거|그\s*노래|이거|이\s*노래)\s*말고(?:\s*(?:다른|딴)\s*(?:거|걸로|노래))?|"
r"(?:다른|딴)\s*(?:거|걸|걸로|것)|다음\s*(?:거|곡|노래)?|한\s*번\s*더|하나\s*더|다시|또)"
r"\s*(?:요|줘|해\s*줘|불러\s*줘|들려\s*줘|부탁해요?|해요|주세요)?\W*$", re.I)
AGAIN = re.compile(r"\bagain\b|\bone more time\b|\bonce more\b|한 ?번 ?더|다시", re.I)
ANOTHER = re.compile(r"\b(another|different|next|other)\b|\bsomething else\b|\bnot (this|that)\b|다른|딴|다음|말고", re.I)
STOP = re.compile(r"\b(stop|enough|halt|quiet|shh+)\b|멈춰|그만|스톱|정지|조용", re.I)
KOREAN = re.compile(r"\bkorean\b|한국", re.I)
ENGLISH = re.compile(r"\benglish\b|영어", re.I)
FILLER = {"sing", "a", "an", "the", "song", "songs", "me", "us", "for", "please", "lumi", "some", "something", "now", "again",
"one", "another", "different", "other", "next", "little", "short", "can", "you", "could", "would", "will", "to",
"it", "that", "this", "together", "with", "and", "your", "nice", "hey", "hi", "ok", "okay", "play", "music",
"in", "korean", "english", "else", "let's", "lets", "let", "go", "now", "pretty", "beautiful", "my", "kids",
"children", "children's", "cute", "fun", "favorite", "favourite", "of", "yours", "so", "just", "maybe", "then"}
UNKNOWN = {"en": "Sorry, I don't know that song yet. I can sing {}.", "ko": "그 노래는 아직 몰라요. {} 부를 수 있어요."}
LIST = {"en": "I can sing {}. Which one would you like?", "ko": "{} 부를 수 있어요. 어떤 노래 불러 드릴까요?"}
_head_thread = None
def songs():
"""{id: song} for every song with a rendered file; song["wav"] is its path."""
out = {}
for p in sorted(SONGS.glob("*.json")) + sorted(MINE.glob("*.json")):
if p.with_suffix(".wav").exists():
out[p.stem] = {**json.loads(p.read_text()), "wav": p.with_suffix(".wav")}
return out
def asked(text, last=""):
"""Do these words ask Lumi to sing ("sing a song", "노래 불러 줘", "sing Arirang", "다른 노래", "can you sing?")?
`last` is the assistant's answer just before (brain history): right after a song a short "another one" /
"again" / "그거 말고" is a song too, right after the list of songs also a title alone ("Arirang")."""
t = text or ""
if NOT_REQUEST.search(t) or SONG_LIST.search(t):
return False
if re.match(r"ACTION: (?:sing|none songs)\b", last or "") and AFTER_SONG.search(t):
return True
if (last or "").startswith("ACTION: none songs") and _title(t, songs()):
return True
return bool(SING.search(t)) or bool(SING_TITLE.search(t) and _title(t, songs()))
def list_asked(text):
""""What songs can you sing?", "무슨 노래 알아?": the titles are said."""
return bool(SONG_LIST.search(text or "")) and not NOT_REQUEST.search(text or "")
def stop_words(text):
return bool(STOP.search(text or ""))
def _title(text, all_songs):
low = (text or "").lower() # Latin names are whole words ("bad" is not in "badminton")
return next((sid for sid, s in all_songs.items()
if any(re.search(rf"(?<![a-z]){re.escape(n)}(?![a-z])", low) for n in s["names"])), None)
def _unknown_title(text):
"""A title was named that is not one of ours: 'sing Yesterday', '애국가 불러 줘'."""
words = re.findall(r"[a-z']+", (text or "").lower())
if "sing" in words:
after = [w for w in words[words.index("sing") + 1:] if w not in ("me", "us", "please", "lumi")]
if after and after[0] not in FILLER: # "sing yesterday"; "sing for everyone" is no title
return True
m = re.search(r"(\S+?)\s*(?:을|를)?\s*(?:좀\s*)?(?:불러|들려)", text or "")
return bool(m) and not re.search(r"노래|좀|곡|하나|루미|아무|뭐|뭔가|^(한|또|더|다시|거|걸|것)$", m.group(1))
def choose(text, lang="en", last=None):
"""The song to sing for these words, or None when they name a song we don't have. A named song first; the
last one again when asked; else any song (one in the language asked for: "a Korean song"), not the last."""
all_songs = songs()
named = _title(text, all_songs)
if named and not ANOTHER.search(text or ""):
return named
if not named and _unknown_title(text):
return None
if last in all_songs and AGAIN.search(text or "") and not ANOTHER.search(text or ""):
return last # "sing it again", "한 번 더"
want = "ko" if KOREAN.search(text or "") else "en" if ENGLISH.search(text or "") else None
pool = [sid for sid, s in all_songs.items() if want in (None, s["lang"]) and sid != last] or \
[sid for sid in all_songs if sid != last] or list(all_songs)
return random.choice(pool) if pool else None
def unknown_reply(lang, lines=UNKNOWN):
names = [s["title_ko" if lang == "ko" else "title"] for s in songs().values()]
joined = ", ".join(names[:-1]) + (" and " if lang == "en" else ", ") + names[-1] if len(names) > 1 else "".join(names)
return lines[lang].format(joined + ("" if lang == "en" else "를" if _no_final(names[-1]) else "을"))
def list_reply(lang):
"""Every title: "I can sing Arirang, ... and Love Attack. Which one would you like?"."""
return unknown_reply(lang, LIST)
def _no_final(word):
"""Korean: the last syllable has no final consonant (를 rather than 을)."""
c = ord(word[-1]) - 0xAC00
return not (0 <= c < 11172) or c % 28 == 0
def song_beats(song):
"""[(seconds, energy 0..1, accent 0..1, a sung phrase starts)] per beat. The owner's songs carry them from the
instrumental (loudness, onsets) and the vocal (phrases); for the others they come from the tempo and the melody:
the bar's first beat is the accent, a phrase starts after a rest or a long note, the intro is calm."""
if "beats" in song:
return [tuple(b) if len(b) == 4 else (b[0], b[1], 0.5, False) for b in song["beats"]]
spb = 60.0 / song["bpm"]
meter = song["meter"]
intro = song.get("intro_bars", 1) * meter
tokens = [t.split(":") for t in song["melody"].split() if t != "|"] * song.get("repeat", 1)
starts, beat, after_break = set(), 0.0, True
for syl, note, b in tokens:
if note != "r" and syl != "~" and after_break:
starts.add(int(round(intro + beat)))
after_break = note == "r" or float(b) >= 2
beat += float(b)
total = intro + int(beat)
return [(i * spb, 0.3 if i < intro else 0.65, 1.0 if i % meter == 0 else 0.3, i in starts) for i in range(total)]
def _speed(vel):
return HEAD_DEG_S * min(1.0, vel / VEL_FULL)
def reach_time(dy, dp, vel):
"""s from the call until the head arrives (the owner's measurements)."""
return REACH_S + max(abs(dy), abs(dp)) / _speed(vel)
def move_time(dy, dp, vel):
"""s from the call until moveto returns."""
return RETURN_S + max(abs(dy), abs(dp)) / _speed(vel)
def _turn(a, b):
"""deg between two move directions (0 = same line forward, 180 = straight back)."""
na, nb = np.hypot(*a), np.hypot(*b)
return float(np.degrees(np.arccos(np.clip(np.dot(a, b) / (na * nb + 1e-9), -1, 1))))
def _fit(v, d, lo, hi, least):
"""A step d from v of at least `least`, ending inside lo..hi (turned toward the middle when it would not)."""
d = d if abs(d) >= least else least * (1 if d >= 0 else -1)
if lo <= v + d <= hi:
return d
if lo <= v - d <= hi:
return -d
toward = 1 if v < (lo + hi) / 2 else -1
return toward * max(least, min(abs(d), hi - v if toward > 0 else v - lo))
def p_room(pp):
"""+1 when the pitch has more room upward, -1 when downward."""
lo, hi = PITCH_RANGE
return 1 if hi - pp >= pp - lo else -1
def _bend(py, pp, dy, dp, last):
"""The move (dy, dp) from (py, pp) made to change both axes (MIN_CHANGE), to turn away from the last move's
line (MIN_TURN_DEG) and to end inside the limits: as planned, with the pitch the other way, else bent to either
side."""
lo, hi = PITCH_RANGE
for side in (0, "flip", 1, -1, 2, -2):
if side == "flip": # a sweep back: rise where the last one fell, and the other way
dy2, dp2 = dy, -dp if abs(dp) >= 2 else (2.5 if p_room(pp) > 0 else -2.5)
elif side and last is not None: # add a part across the last move's direction
n = np.hypot(*last) + 1e-9
size = max(np.hypot(dy, dp), 3.0) * 0.6 * abs(side)
dy2, dp2 = dy - last[1] / n * size * np.sign(side), dp + last[0] / n * size * np.sign(side)
else:
dy2, dp2 = dy, dp
dy2, dp2 = _fit(py, dy2, -YAW_SWAY, YAW_SWAY, MIN_CHANGE[0]), _fit(pp, dp2, lo, hi, MIN_CHANGE[1])
if last is None or MIN_TURN_DEG <= _turn(last, (dy2, dp2)) <= 180 - MIN_TURN_DEG:
break
return dy2, dp2
def head_targets(song, seed=0):
"""[(call s, yaw deg, pitch deg, speed %)] around yaw 0 / pitch CENTRE_PITCH, each move timed to land ON a beat
(called reach_time before it) and never before the last call returned. Energetic parts: a small diagonal bob on
every beat that leaves time (alternating sides, vel 100), and on a bar's accent or a phrase start a quick 15-25
deg sweep with a dip. Calm parts: slower sways. Every move changes both axes and turns away from the last move's
line (_bend)."""
rng = random.Random(seed)
beats = song_beats(song)
lo, hi = PITCH_RANGE
y, p, free = 0.0, 0.0, 0.0 # the pose and when the last call returns (starts at 0 / 0)
side, last, last_accent, out, pending = rng.choice((-1, 1)), None, -9.0, [], False
for k, (t, e, accent, phrase) in enumerate(beats):
if t < 0.8: # the head is still turning to 0 / 0
continue
pending = pending or ((accent >= 0.7 or phrase) and t - last_accent >= ACCENT_EVERY_S and e >= 0.3)
if pending: # an accent waits for the first beat it fits on
kind, vel = "accent", VEL_LIVELY
elif e >= ENERGETIC:
kind, vel = "bob", VEL_LIVELY
else:
kind, vel = "sway", VEL_CALM if e >= CALMEST else VEL_CALMEST
if kind != "bob" or rng.random() < 0.85:
side = -side
if kind == "accent": # a sweep across to the other side, dipping
side = -1 if y > 0 else 1
ty = side * rng.uniform(*ACCENT_DEG) * 0.7 + 0.3 * y
tp = rng.choice((max(lo, min(p, CENTRE_PITCH + 2) - rng.uniform(6, 10)), min(hi, CENTRE_PITCH + rng.uniform(8, 14)))) # dip or lift
elif kind == "bob":
size = rng.uniform(*BOB_DEG)
ty = y + side * size * rng.uniform(0.7, 1.0)
tp = (p - size * 0.8 if p > CENTRE_PITCH else p + size * 0.8) + rng.uniform(-1, 1) # diagonal
else:
ty = side * rng.uniform(*SWAY_DEG)
tp = CENTRE_PITCH + rng.uniform(-8, 8)
ty -= 0.15 * y if kind == "bob" else 0.0 # bobs drift back toward the middle
dy, dp = _bend(y, p, ty - y, tp - p, last)
call = t - reach_time(dy, dp, vel) # lands on the beat
for _ in range(8): # too little time: a smaller move (an accent stays big)
if call >= free + GAP_S or max(abs(dy), abs(dp)) <= (ACCENT_DEG[0] if kind == "accent" else 3.0):
break
dy, dp = _bend(y, p, dy * 0.8, dp * 0.8, last)
call = t - reach_time(dy, dp, vel)
if last is not None and not MIN_TURN_DEG <= _turn(last, (dy, dp)) <= 180 - MIN_TURN_DEG:
n = np.hypot(*last) + 1e-9 # still on the last line: a small step across it instead
for size in (4.0, -4.0, 6.0, -6.0, 2.5, -2.5):
dy = _fit(y, -last[1] / n * size, -YAW_SWAY, YAW_SWAY, MIN_CHANGE[0] + 0.2)
dp = _fit(p, last[0] / n * size, lo, hi, MIN_CHANGE[1] + 0.2)
if MIN_TURN_DEG <= _turn(last, (dy, dp)) <= 180 - MIN_TURN_DEG:
break
call = t - reach_time(dy, dp, vel)
if call < free + GAP_S or last is not None and not MIN_TURN_DEG <= _turn(last, (dy, dp)) <= 180 - MIN_TURN_DEG:
continue # no time or no fitting move for this beat: a later one
out.append((round(float(call), 3), round(float(y + dy), 2), round(float(p + dp), 2), int(vel)))
free = call + move_time(dy, dp, vel)
last, y, p = (dy, dp), y + dy, p + dp
if kind == "accent":
last_accent, pending = t, False
return out
def _move_head(song, seed, stop, head_api):
"""Turn the head to yaw 0 / pitch 0, follow the head targets until the song ends or stop is set, then go back
to yaw 0 / pitch 0. One call at a time (each blocks until the head arrives)."""
try:
lift, waist, _, _ = head_api.status()
except Exception as e:
print(f"sing: head status failed: {e}")
return
t0 = time.time()
try:
head_api.moveto([lift, waist, 0.0, 0.0], VEL_LIVELY, VEL_LIVELY)
for t, yaw, pitch, vel in head_targets(song, seed):
while not stop.is_set() and time.time() - t0 < t:
stop.wait(0.02)
if stop.is_set():
break
if time.time() - t0 - t > LATE_S:
continue
head_api.moveto([lift, waist, yaw, pitch], vel, vel)
except Exception as e:
print(f"sing: head move failed: {e}")
finally:
try:
head_api.moveto([lift, waist, 0.0, 0.0], HEAD_VEL, HEAD_VEL)
except Exception as e:
print(f"sing: head return failed: {e}")
def sing(song_id, abort=None, play=None, head_api=None, load=None):
"""Sing one song; blocks until it ends (True) or abort() becomes True (False). The head returns in its own
thread, so a stop is at once. play / head_api / load are for tests (default: the speaker and the real head)."""
global _head_thread
from audio import mouth
if play is None:
mouth._set_volume()
play = mouth._play
if head_api is None:
from robot import head as head_api
if load is None:
import soundfile as sf
def load(path):
return sf.read(path, dtype="float32")
song = songs()[song_id]
wav, rate = load(song["wav"])
wav = np.asarray(wav)
if wav.ndim == 2: # the owner's songs are stereo; the speaker is one channel
wav = wav.mean(1)
if _head_thread is not None:
_head_thread.join(RETURN_WAIT_S) # the head is still going back from the last song
# the clip mic hears the song: its words are Lumi's own voice until 30 s after its end (mouth.recent_speech)
mouth._recent.append((time.time() + len(wav) / rate, song["lyrics"]))
stop = threading.Event()
_head_thread = threading.Thread(target=_move_head, args=(song, time.time(), stop, head_api), daemon=True)
_head_thread.start()
try:
return bool(play(wav, rate, abort))
finally:
stop.set()
if __name__ == "__main__":
if len(sys.argv) < 2:
for sid, s in songs().items():
print(f"{sid:24} {s['lang']} {s['title']}")
else:
print("finished" if sing(sys.argv[1]) else "stopped")
if _head_thread:
_head_thread.join()
+316
View File
@@ -0,0 +1,316 @@
"""Make Lumi sing the best part of a song the owner provided (data/songs/mine/, local only, never copied to the Mac):
the singer's own vocal turned into Lumi's voice (audio/cover.py), over the song's instrumental.
.venv-songs/bin/python audio/separate.py data/songs/mine/<NAME>.mp3 # 1. vocals / instrumental (Demucs)
.venv-cover/bin/python audio/cover.py <NAME> # 2. the vocal in Lumi's voice
.venv/bin/python audio/sing_mine.py <NAME> --title "..." --title-ko "..." --names "a,b" # 3. this
3 does: words and their times from the separated vocal (whisper.cpp), the part to sing (~40-60 s where the
most-repeated lines, the singing and the loudness are; or --start/--end seconds), the beats of the instrumental for
the head moves, and the mix: Lumi's vocal at the singer's level with a little room reverb over the instrumental.
Writes data/songs/mine/<NAME>.wav (the part) + .json (audio/sing.py plays them) and <NAME>/full_lumi.wav (the
whole song, to check). Lyrics only ever go into data/songs/mine/.
"""
import argparse
import difflib
import json
import pathlib
import re
import subprocess
import numpy as np
import soundfile as sf
from audio import sing_render as R
ROOT = pathlib.Path(__file__).resolve().parents[1]
MINE = ROOT / "data" / "songs" / "mine"
WHISPER_CLI = ROOT / "whisper.cpp/build/bin/whisper-cli"
WHISPER_MODEL = ROOT / "models/ggml-large-v3-turbo-q5_0.bin"
SR = R.SR
PART_S = (40.0, 60.0) # s, length of the part sung
PART_BEST_S = 50.0 # s, preferred length
PAUSE_S = 0.2 # s of a quiet vocal between two sung phrases
PHRASE_LEVEL = 0.3 # vocal RMS below this part of its loud level counts as quiet (separated vocals
# keep some reverb and bleed, so not much lower)
MAX_PHRASE_S = 12.0 # s; a longer phrase is split at its quietest moment
CHUNK_S = 28.0 # s, longest piece of vocal given to whisper at once
SAME_LINE = 0.7 # difflib ratio: two lines are the same line (a repeat)
HOP = 441 # samples (10 ms) for pitch and energy frames
FRAME = 2048 # samples, pitch window
VOCAL_F0 = (70.0, 1000.0) # Hz, singer pitch range searched
VOICED_R = 0.6 # normalised autocorrelation above this = a sung (voiced) frame
VOICE_GAIN = 1.0 # Lumi's vocal level relative to the singer's in the record (1 = the same balance)
FADE_IN_S, FADE_OUT_S = 0.3, 2.5
BPM_RANGE = (70.0, 180.0)
BEAT_TIGHTNESS = 100.0 # DP beat tracker: how strongly beats keep the tempo
ENERGY_RANGE = (0.3, 0.8) # instrumental loudness (part of the song's loud level) mapped to energy 0 .. 1
BEAT_MIN = 0.6 # a beat closer than this part of the usual beat to the last one is a tracking hiccup
# ---------- analysis ----------
def mono(x):
return x.mean(1) if x.ndim == 2 else x
def frames(x, size, hop):
n = 1 + max(0, (len(x) - size) // hop)
idx = np.arange(size)[None, :] + hop * np.arange(n)[:, None]
return x[idx]
def rms(x, hop=HOP):
return np.sqrt((frames(x, hop * 2, hop) ** 2).mean(1) + 1e-12)
def pitch_contour(v):
"""Per 10 ms: f0 in Hz (0 = unvoiced) of a separated vocal; octave jumps of single frames removed."""
lo, hi = int(SR / VOCAL_F0[1]), int(SR / VOCAL_F0[0])
f = frames(np.pad(v, (FRAME // 2, FRAME)), FRAME, HOP)
e = np.sqrt((f ** 2).mean(1))
spec = np.fft.rfft(f * np.hanning(FRAME), 2 * FRAME)
ac = np.fft.irfft(np.abs(spec) ** 2)[:, :hi + 1]
ac /= ac[:, :1] + 1e-12
lag = lo + np.argmax(ac[:, lo:hi], 1)
best = ac[np.arange(len(ac)), lag]
# prefer the shortest lag that is nearly as good (the true period, not a multiple)
for div in (3, 2):
sub = np.round(lag / div).astype(int)
ok = (sub >= lo) & (ac[np.arange(len(ac)), np.clip(sub, 0, hi)] > 0.9 * best)
lag = np.where(ok, sub, lag)
f0 = np.where((best > VOICED_R) & (e > 0.1 * np.percentile(e, 95)), SR / lag, 0.0)
st = np.where(f0 > 0, 12 * np.log2(np.maximum(f0, 1) / 440), np.nan)
med = st.copy()
for i in range(2, len(st) - 2): # median of 5 frames
w = st[i - 2:i + 3]
w = w[~np.isnan(w)]
med[i] = np.median(w) if len(w) >= 3 and not np.isnan(st[i]) else np.nan
return np.where(np.isnan(med), 0.0, 440 * 2 ** (med / 12))
def onset_envelope(x):
"""Spectral flux per 10 ms frame (log magnitude, positive changes)."""
f = frames(x, 2048, HOP)
mag = np.log1p(100 * np.abs(np.fft.rfft(f * np.hanning(2048), axis=1)))
flux = np.maximum(0, np.diff(mag, axis=0)).sum(1)
flux = np.concatenate([[0], flux])
flux -= np.convolve(flux, np.ones(50) / 50, "same") # local mean removed
return np.maximum(flux, 0)
def beats(x):
"""(bpm, beat times s) of the instrumental: tempo from the onset autocorrelation, beats by dynamic
programming (Ellis 2007)."""
env = onset_envelope(x)
fps = SR / HOP
lags = np.arange(int(fps * 60 / BPM_RANGE[1]), int(fps * 60 / BPM_RANGE[0]) + 1)
ac = np.array([np.dot(env[:-l], env[l:]) for l in lags])
prior = np.exp(-0.5 * (np.log2(60 * fps / lags / 120.0) / 0.9) ** 2) # a mild preference for ~120 bpm
period = lags[np.argmax(ac * prior)]
score = env.copy()
back = np.full(len(env), -1)
span = np.arange(-2 * period, -period // 2)
cost = -BEAT_TIGHTNESS * np.log(-span / period) ** 2
for i in range(2 * period, len(env)):
c = score[i + span] + cost
k = np.argmax(c)
score[i] += c[k]
back[i] = i + span[k]
i = len(env) - period + np.argmax(score[-period:])
out = []
while i >= 0:
out.append(i)
i = back[i]
return 60 * fps / period, np.array(out[::-1]) / fps
def phrases(v):
"""[(t0, t1)] sung phrases of the separated vocal: parts between pauses of PAUSE_S."""
e = rms(v)
on = e > PHRASE_LEVEL * np.percentile(e, 95)
out, start, quiet = [], None, 0
for i, o in enumerate(on):
if o:
if start is None:
start = i
quiet = 0
elif start is not None:
quiet += 1
if quiet * 0.01 >= PAUSE_S:
out.append((start / 100, (i - quiet + 1) / 100))
start, quiet = None, 0
if start is not None:
out.append((start / 100, len(on) / 100))
out = [(a, b) for a, b in out if b - a >= 0.3]
done = []
while out:
a, b = out.pop(0)
if b - a <= MAX_PHRASE_S:
done.append((a, b))
continue
lo, hi = int((a + (b - a) / 4) * 100), int((b - (b - a) / 4) * 100)
cut = (lo + int(np.argmin(np.convolve(e[lo:hi], np.ones(15) / 15, "same")))) / 100
out[:0] = [(a, cut), (cut, b)]
return done
def whisper_words(v, folder, lang):
"""[(t0, t1, word)] of the separated vocal. whisper.cpp (one word per segment, DTW timestamps) on chunks of
whole phrases up to CHUNK_S: on a whole song at once it skips parts and drifts."""
chunks, cur = [], None
for a, b in phrases(v):
if cur and b - cur[0] <= CHUNK_S:
cur = (cur[0], b)
else:
if cur:
chunks.append(cur)
cur = (a, b)
chunks += [cur] if cur else []
words = []
tmp = folder / "chunk.wav"
for a, b in chunks:
a0 = max(0.0, a - 0.3)
sf.write(tmp, v[int(a0 * SR):int((b + 0.3) * SR)], SR)
subprocess.run(["sox", str(tmp), "-r", "16000", "-c", "1", "-b", "16", str(tmp.with_name("chunk16.wav"))],
check=True)
subprocess.run([str(WHISPER_CLI), "-m", str(WHISPER_MODEL), "-f", str(tmp.with_name("chunk16.wav")), "-l", lang,
"-ml", "1", "-sow", "-mc", "0", "-dtw", "large.v3.turbo", "-oj", "-of", str(folder / "chunk"),
"-np"], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
words += [(t0 + a0, t1 + a0, w) for t0, t1, w in read_words(folder / "chunk.json") if t0 + a0 < b + 0.2]
(folder / "words.json").write_text(json.dumps(words, ensure_ascii=False))
for f in ("chunk.wav", "chunk16.wav", "chunk.json"):
(folder / f).unlink(missing_ok=True)
return words
def read_words(path):
"""whisper.cpp's JSON with one word per segment. A Korean character can be split over two segments (its UTF-8
bytes): such segments are joined."""
segs = json.loads(path.read_bytes().decode("utf-8", "surrogateescape"))["transcription"]
words, buf, t0 = [], b"", None
for s in segs:
if not buf:
t0 = s["offsets"]["from"] / 1000
buf += s["text"].encode("utf-8", "surrogateescape")
try:
w = buf.decode("utf-8").strip()
except UnicodeDecodeError:
continue
buf = b""
if w and not re.fullmatch(r"[\W_]*|\[.*\]|\(.*\)", w):
words.append((t0, s["offsets"]["to"] / 1000, w))
return words
def pick_part(words, phr, mr, vocal_f0):
"""(start s, end s): a part PART_S long, starting and ending with a sung phrase, where repeated lines (the
chorus), singing and a loud instrumental are."""
texts = [re.sub(r"\W", "", "".join(w for t, _, w in words if a - 0.2 <= t < b)).lower() for a, b in phr]
rep = np.array([sum(len(a) > 3 and difflib.SequenceMatcher(None, a, b).ratio() > SAME_LINE
for j, b in enumerate(texts) if j != i) for i, a in enumerate(texts)], float)
loud = rms(mr)
loud /= np.percentile(loud, 95)
voiced = vocal_f0 > 0
best, part = -1.0, (phr[0][0], phr[0][0] + PART_BEST_S)
for i in range(len(phr)):
for j in range(i, len(phr)):
t0, t1 = phr[i][0], phr[j][1]
if t1 - t0 > PART_S[1]:
break
if t1 - t0 < PART_S[0]:
continue
f0, f1 = int(t0 * 100), int(t1 * 100)
score = (1 + rep[i:j + 1].mean()) * (0.5 + voiced[f0:f1].mean()) * (0.5 + loud[f0:f1].mean()) \
* (1 + 0.3 * min(rep[i], 2)) * np.exp(-abs(t1 - t0 - PART_BEST_S) / 30) # begins with a repeated line
if score > best:
best, part = score, (t0, t1)
return part
# ---------- mix ----------
def beat_info(beat_times, mr, v, t_start, t_end):
"""[[s from the part's start, energy 0..1, accent 0..1, a sung phrase starts]] per beat of the part, for the
head moves of audio/sing.py: energy = the instrumental's loudness over half a second against the whole
song's (ENERGY_RANGE), accent = its strongest
onset within 60 ms of the beat, phrase = a vocal phrase begins before the next beat."""
loud = rms(mono(mr))
onset = onset_envelope(mono(mr))
bt = beat_times[(beat_times >= t_start) & (beat_times < t_end - 0.5)]
if not len(bt):
return []
period = np.median(np.diff(bt)) if len(bt) > 1 else 0.5
keep = [bt[0]]
for t in bt[1:]:
if t - keep[-1] > BEAT_MIN * period:
keep.append(t)
bt = np.array(keep)
energy = np.array([loud[int(t * 100):int(t * 100) + 50].mean() for t in bt]) / np.percentile(loud, 95)
energy = np.clip((energy - ENERGY_RANGE[0]) / (ENERGY_RANGE[1] - ENERGY_RANGE[0]), 0, 1)
accent = np.array([onset[max(0, int(t * 100) - 6):int(t * 100) + 7].max() for t in bt])
accent = np.clip(accent / (np.percentile(accent, 90) + 1e-9), 0, 1)
starts = np.array([a for a, _ in phrases(v)])
phrase = [bool(((starts >= t - 0.1) & (starts < t + period - 0.1)).any()) for t in bt]
return [[round(float(t - t_start), 3), round(float(e), 2), round(float(a), 2), ph]
for t, e, a, ph in zip(bt, energy, accent, phrase)]
def active_rms(x, ref):
"""RMS of x over the frames where it sounds (above 10 % of ref's loud level)."""
e = rms(x)
on = e > 0.1 * np.percentile(rms(ref), 95)
return float(np.sqrt((e[on] ** 2).mean())) if on.any() else 1e-9
def make(name, title, title_ko, names, lang, start=None, end=None):
folder = MINE / name
vocals, sr = sf.read(folder / "vocals.wav", dtype="float32", always_2d=True)
mr, _ = sf.read(folder / "mr.wav", dtype="float32", always_2d=True)
lumi, sr_l = sf.read(folder / "vocal_lumi.wav", dtype="float32", always_2d=True)
assert sr == SR and sr_l == SR, (sr, sr_l)
v, lumi = mono(vocals), mono(lumi)
f0 = pitch_contour(v)
words_file = folder / "words.json"
words = [tuple(w) for w in json.loads(words_file.read_text())] if words_file.exists() else \
whisper_words(v, folder, lang)
phr = phrases(v)
bpm, bt = beats(mono(mr))
if start is None:
start, end = pick_part(words, phr, mono(mr), f0)
bar = 4 * 60 / bpm
before = bt[bt <= start - 0.2]
t_start = float(before[-1] if len(before) and start - before[-1] < bar + 0.3 else max(0.0, start - 0.5))
if start - t_start < bar * 0.75 and len(before) > 4: # a bar of music before Lumi starts
t_start = float(bt[max(0, len(before) - 5)])
t_end = min(len(mr) / SR, end + 1.5)
n = min(len(lumi), len(mr))
voice = np.zeros(len(mr), np.float32)
voice[:n] = lumi[:n] * VOICE_GAIN * active_rms(v, v) / active_rms(lumi, v)
full = R.reverb(voice)[:, None] + mr
full *= 0.9 / np.abs(full).max()
sf.write(folder / "full_lumi.wav", full.astype(np.float32), SR, subtype="PCM_16")
part = full[int(t_start * SR):int(t_end * SR)].copy()
fi, fo = int(FADE_IN_S * SR), int(FADE_OUT_S * SR)
part[:fi] *= np.linspace(0, 1, fi)[:, None]
part[-fo:] *= np.linspace(1, 0, fo)[:, None]
sf.write(MINE / f"{name}.wav", part.astype(np.float32), SR, subtype="PCM_16")
lyrics = " ".join(w for a, _, w in words if start - 0.05 <= a < end)
song = {"title": title, "title_ko": title_ko, "lang": lang, "names": names,
"source": "owner's file; company holds the performance licence; local only",
"part_s": [round(t_start, 2), round(t_end, 2)], "bpm": round(bpm, 1),
"lyrics": lyrics, "beats": beat_info(bt, mr, v, t_start, t_end)}
(MINE / f"{name}.json").write_text(json.dumps(song, ensure_ascii=False, indent=1))
print(f"{MINE / name}.wav part {t_start:.1f}-{t_end:.1f} s ({t_end - t_start:.0f} s), {bpm:.0f} bpm; "
f"{folder / 'full_lumi.wav'}")
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("name")
ap.add_argument("--title", required=True)
ap.add_argument("--title-ko", required=True)
ap.add_argument("--names", required=True, help="comma-separated words it is asked by")
ap.add_argument("--lang", default="ko")
ap.add_argument("--start", type=float)
ap.add_argument("--end", type=float)
a = ap.parse_args()
make(a.name, a.title, a.title_ko, [n.strip().lower() for n in a.names.split(",")], a.lang, a.start, a.end)
+321
View File
@@ -0,0 +1,321 @@
"""Render the songs in data/songs/ once: Lumi's TTS voice sung to the melody over a backing track made here.
python audio/sing_render.py # every song
python audio/sing_render.py arirang # one song
Each syllable is spoken by the TTS (Supertonic-3, the same voice as every answer), its pitch is set to the note
and its vowel stretched to the note's length with a pitch-synchronous overlap-add (TD-PSOLA, written below: no
pyworld / librosa on this Thor). The backing (bass + chords, a soft piano-like tone) is synthesised from the
song's chord list. Voice and backing are mixed into data/songs/<id>.wav, which audio/sing.py plays.
Nothing here is downloaded: the melodies and chords are written in the song files (public domain songs).
"""
import json
import pathlib
import sys
import numpy as np
import soundfile as sf
ROOT = pathlib.Path(__file__).resolve().parents[1]
SONGS = ROOT / "data" / "songs"
SR = 44100 # Hz, the TTS sample rate
TARGET_MEAN_HZ = 240.0 # songs are transposed so their average note is near this (voice F1 speaks at ~175 Hz)
F0_RANGE = (110.0, 400.0) # Hz, pitch search range for the speaking voice
HOP = 220 # samples (5 ms) between pitch frames
WIN = 1323 # samples (30 ms) pitch analysis window
VOICED_R = 0.5 # normalised autocorrelation above this = voiced frame
UNVOICED_P = SR // 200 # samples; grain spacing in unvoiced parts
ONSET_MAX_S = 0.12 # s; a syllable's leading consonant is sung before the beat by up to this
GLIDE_S = 0.03 # s; pitch moves between notes with this time constant
VIBRATO = (5.5, 0.25, 0.3) # Hz, semitones depth, s from a note's start before the vibrato grows
NOTE_FILL = 0.92 # part of a note's length the syllable lasts (a short breath between notes)
VOICE_GAIN, BACKING_GAIN = 0.8, 0.22
REVERB_S, REVERB_MIX = 0.9, 0.12
NOTE_NAMES = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11}
CHORDS = {"": (0, 4, 7), "m": (0, 3, 7), "7": (0, 4, 7, 10), "m7": (0, 3, 7, 10)}
# ---------- song file ----------
def midi(name):
"""'F#4' -> 66"""
n = NOTE_NAMES[name[0]] + name[1:-1].count("#") - name[1:-1].count("b")
return 12 * (int(name[-1]) + 1) + n
def hz(m):
return 440.0 * 2 ** ((m - 69) / 12)
def notes(song):
"""[(start beat, beats, midi or None, syllable)] from 'syl:NOTE:beats' tokens ('-:r:1' rest, '~' slur);
the melody is played song['repeat'] times."""
out, beat = [], 0.0
tokens = [t for t in song["melody"].split() if t != "|"]
for _ in range(song.get("repeat", 1)):
for tok in tokens:
syl, note, beats = tok.split(":")
beats = float(beats)
out.append((beat, beats, None if note == "r" else midi(note), syl))
beat += beats
return out
def transpose(song):
"""Semitones that bring the song's average note to TARGET_MEAN_HZ (or the file's own 'transpose')."""
if "transpose" in song:
return song["transpose"]
ms = [m for _, _, m, _ in notes(song) if m is not None]
return round(12 * np.log2(TARGET_MEAN_HZ / hz(np.mean(ms))))
def chord_notes(name):
"""'F#m7' -> (root pitch class, intervals)"""
root = NOTE_NAMES[name[0]]
rest = name[1:]
if rest[:1] in ("#", "b"):
root += 1 if rest[0] == "#" else -1
rest = rest[1:]
return root % 12, CHORDS[rest]
# ---------- voice: pitch analysis and PSOLA ----------
def trim(x, level=0.02):
e = np.sqrt(np.convolve(x ** 2, np.ones(441) / 441, "same"))
on = np.nonzero(e > level * max(e.max(), 1e-9) / 0.3)[0]
return x[max(0, on[0] - 220):on[-1] + 220] if len(on) else x
def f0_track(x):
"""Per HOP frame: period in samples (0 = unvoiced)."""
lo, hi = int(SR / F0_RANGE[1]), int(SR / F0_RANGE[0])
rms_all = np.sqrt((x ** 2).mean())
periods = []
for i in range(0, max(1, len(x) - WIN), HOP):
f = x[i:i + WIN]
if len(f) < WIN or np.sqrt((f ** 2).mean()) < 0.3 * rms_all:
periods.append(0)
continue
spec = np.fft.rfft(f * np.hanning(WIN), 4096)
ac = np.fft.irfft(np.abs(spec) ** 2)[:hi + 1]
ac /= ac[0] + 1e-12
best = lo + np.argmax(ac[lo:hi])
periods.append(best if ac[best] > VOICED_R else 0)
p = np.array(periods, float)
sm = p.copy() # median of 5 frames removes single octave jumps
for i in range(2, len(p) - 2):
win = p[i - 2:i + 3]
sm[i] = np.median(win) if np.count_nonzero(win) >= 3 else 0
return sm
def pitch_marks(x, per):
"""Analysis marks [(sample, period)]: one per pitch period on voiced parts, every UNVOICED_P elsewhere."""
marks, t = [], 0
sign = 1 if x.max() >= -x.min() else -1
while t < len(x):
p = per[min(len(per) - 1, t // HOP)]
if p:
p = int(p)
a, b = max(0, t - p // 3), min(len(x), t + p // 3 + 1)
t = a + int(np.argmax(sign * x[a:b])) if b > a else t
marks.append((t, p))
t += p
else:
marks.append((t, UNVOICED_P))
t += UNVOICED_P
return marks
def voiced_span(per):
v = np.nonzero(per)[0]
return (v[0] * HOP, v[-1] * HOP + WIN) if len(v) else (0, 0)
def sing_syllable(x, pitches, dur):
"""x (a spoken syllable) sung for dur seconds on pitches [(seconds, Hz)] (one note, or a slur over several).
Returns (audio, onset seconds: the consonant before the vowel, to be placed before the beat)."""
per = f0_track(x)
va, vb = voiced_span(per)
if vb <= va: # nothing voiced (a whispered syllable): just fit the length
va, vb = 0, len(x)
va, vb = min(va, len(x)), min(vb, len(x))
n_out = int(dur * SR)
onset = min(va, int(ONSET_MAX_S * SR))
head, tail = va, len(x) - vb # consonants before / after the vowel keep their speed
body_out = n_out + onset - head - tail
if body_out < 0.3 * (vb - va): # too short a note: squeeze everything evenly
scale = (n_out + onset) / len(x)
def src(t):
return t / scale
else:
def src(t):
if t < head:
return t
if t < head + body_out:
return va + (t - head) * (vb - va) / body_out
return vb + (t - head - body_out)
total = n_out + onset
# target pitch along the output: notes in order, smoothed (glide) with a vibrato that grows into long notes
f0 = np.zeros(total)
ends = head + (np.cumsum([sec for sec, _ in pitches]) * SR).astype(int)
starts = [head] + list(ends[:-1])
for i in range(len(pitches)):
f0[0 if i == 0 else starts[i]:total if i == len(pitches) - 1 else ends[i]] = pitches[i][1]
alpha = 1 - np.exp(-1 / (GLIDE_S * SR))
log_f = np.log(f0)
sm = np.empty_like(log_f)
acc = log_f[0]
for i in range(0, total, 64): # smoothing in blocks of 64 samples is plenty
acc += (log_f[i] - acc) * (1 - (1 - alpha) ** 64)
sm[i:i + 64] = acc
t = np.arange(total) / SR
note_start = np.zeros(total)
for a in starts:
note_start[a:] = a / SR
since = np.clip(t - note_start - VIBRATO[2], 0, None)
vib = VIBRATO[1] * np.minimum(1, since / 0.3) * np.sin(2 * np.pi * VIBRATO[0] * t)
target = np.exp(sm) * 2 ** (vib / 12)
# TD-PSOLA: grains two input periods long, placed at the target period
marks = pitch_marks(x, per)
pos = np.array([m for m, _ in marks])
y, w = np.zeros(total + 2 * SR // 50), np.zeros(total + 2 * SR // 50)
out = 0
while out < total:
s = src(out)
k = int(np.argmin(np.abs(pos - s)))
m, p = marks[k]
voiced = va <= s < vb and p != UNVOICED_P
win = np.hanning(2 * p + 1)
a, b = m - p, m + p + 1
grain = np.zeros(2 * p + 1)
ga, gb = max(0, a), min(len(x), b)
grain[ga - a:gb - a] = x[ga:gb]
oa = out - p
lo = max(0, oa)
hi = min(len(y), oa + 2 * p + 1)
if hi > lo:
y[lo:hi] += (grain * win)[lo - oa:hi - oa]
w[lo:hi] += win[lo - oa:hi - oa]
out += max(20, int(SR / target[min(out, total - 1)])) if voiced else p
y = y[:total] / np.maximum(w[:total], 0.5)
fade = int(0.01 * SR)
fade = min(fade, len(y) // 4) # a very short syllable (fast rap) gets shorter fades
y[:fade] *= np.linspace(0, 1, fade)
y[len(y) - fade * 3:] *= np.linspace(1, 0, fade * 3)
return y, onset / SR
def segments(song, shift):
"""Sung syllables [(start s, seconds, syllable, [(seconds, Hz)])]: a syllable and the slurs ('~') after it."""
spb = 60.0 / song["bpm"]
intro = song.get("intro_bars", 1) * song["meter"] * spb
out = []
for beat, beats, m, syl in notes(song):
sec = beats * spb
if m is None:
continue
if syl == "~" and out:
out[-1][1] += sec
out[-1][3].append((sec, hz(m + shift)))
else:
out.append([intro + beat * spb, sec, syl, [(sec, hz(m + shift))]])
return out
def render_voice(song, shift, n):
from audio import mouth
tts = mouth._load()
assert tts.sample_rate == SR, tts.sample_rate
lang = song["lang"]
spoken = {}
y = np.zeros(n)
for start, sec, syl, pitches in segments(song, shift):
if syl not in spoken:
spoken[syl] = trim(np.asarray(mouth._synth(syl, lang), float))
dur = sec * NOTE_FILL if sec > 0.3 else sec * 0.97
v, onset = sing_syllable(spoken[syl], pitches, dur)
a = max(0, int((start - onset) * SR))
b = min(n, a + len(v))
y[a:b] += v[:b - a]
return y
# ---------- backing ----------
def tone(f, sec, bright=1.0, decay=2.5):
"""A soft plucked / piano-like note."""
t = np.arange(int(sec * SR)) / SR
y = sum(np.sin(2 * np.pi * f * k * t) * bright ** (k - 1) / k ** 1.6 * np.exp(-t * decay * (1 + 0.5 * k))
for k in range(1, 7))
y *= np.minimum(1, t / 0.006)
return y
def render_backing(song, shift, n):
"""Bass on the bar's first beat (and the middle in 4/4 and 6/8), the chord on the other beats; one chord per
bar, or 'C,G' for two."""
spb = 60.0 / song["bpm"]
meter = song["meter"]
bars = song["chords"].split() * song.get("repeat", 1)
bars = [bars[0]] * song.get("intro_bars", 1) + bars + [bars[-1]] # count-in bar and a last ringing bar
strong = {3: (0,), 4: (0, 2), 6: (0, 3)}[meter]
y = np.zeros(n)
for i, bar in enumerate(bars):
parts = bar.split(",")
for beat in range(meter):
name = parts[min(len(parts) - 1, beat * len(parts) // meter)]
root, iv = chord_notes(name)
t = (i * meter + beat) * spb
a = int(t * SR)
last = i == len(bars) - 1
if last and beat:
break
ring = meter * spb if last else spb * 1.2
f = hz(36 + (root + shift) % 12) # bass, C2..B2
bass = 0.9 * tone(f, ring * 1.5, 0.4, 1.5) + 0.3 * tone(f * 2, ring * 1.5, 0.3, 2.0)
chord = sum(tone(hz(55 + (root + shift + k - 7) % 12), ring, 0.6, 3.0) for k in iv) * 0.45 # G3..F#4
if last:
v = bass[:len(chord)] + chord
else:
v = bass if beat in strong else chord
b = min(n, a + len(v))
y[a:b] += v[:b - a]
return y
def reverb(x):
"""Convolution with a short decaying noise tail (a small room)."""
rng = np.random.default_rng(1)
t = np.arange(int(REVERB_S * SR)) / SR
ir = rng.standard_normal(len(t)) * np.exp(-t * 6.9 / REVERB_S)
ir[:int(0.02 * SR)] = 0
ir /= np.sqrt((ir ** 2).sum())
size = 1 << int(np.ceil(np.log2(len(x) + len(ir))))
wet = np.fft.irfft(np.fft.rfft(x, size) * np.fft.rfft(ir, size), size)[:len(x)]
return x + REVERB_MIX * wet
def length_s(song):
beats = sum(b for _, b, _, _ in notes(song))
return (song.get("intro_bars", 1) * song["meter"] + beats + song["meter"]) * 60.0 / song["bpm"] + 1.0
def render(song_id):
song = json.loads((SONGS / f"{song_id}.json").read_text())
shift = transpose(song)
n = int(length_s(song) * SR)
voice = render_voice(song, shift, n)
backing = render_backing(song, shift, n)
voice *= VOICE_GAIN / max(np.abs(voice).max(), 1e-9)
backing *= BACKING_GAIN / max(np.abs(backing).max(), 1e-9)
mix = reverb(voice + backing)
mix *= 0.9 / np.abs(mix).max()
path = SONGS / f"{song_id}.wav"
sf.write(path, mix.astype(np.float32), SR, subtype="PCM_16")
print(f"{path} {len(mix) / SR:.1f} s, transposed {shift:+d}")
return path
if __name__ == "__main__":
ids = sys.argv[1:] or sorted(p.stem for p in SONGS.glob("*.json"))
for i in ids:
render(i)