duplex-v0 / data /build_timeline.py
Jr23xd23's picture
RightNow Duplex v0
f730521 verified
Raw History Blame Contribute Delete
12.3 kB
"""Put both speakers of each dialogue on one shared timeline and label every 80 ms frame.
Channel 0 is the caller as the model hears them (room, line and noise effects, and
sometimes the model's own voice leaking back). Channel 1 is the model's own output
audio, clean, exactly what a server would have sent.
Labels are the action the model (the agent) should take in that frame:
START the caller's turn is over and the agent has not begun yet. The agent's
audio starts in the frame right after the last START frame, so the label
can never be read off the agent's own channel.
STOP the caller is truly interrupting; from one frame after the caller's onset
until the agent's audio is cut.
BACKCHANNEL the caller says "mm-hm" over the agent; the agent keeps talking.
WAIT everything else, including mid-sentence pauses of the caller.
All noise, room responses and line effects are generated here (no third-party audio),
so the licence of the dataset is the licence of this code and of the TTS output.
python -m data.build_timeline --dialogues data/out/dialogues.jsonl --tts data/out/tts \
--out data/out/dataset --workers 32
"""
import argparse
import json
import zlib
from collections import Counter
from multiprocessing import Pool
from pathlib import Path
import numpy as np
from duplex.spec import AGENT, BACKCHANNEL, CALLER, FRAME, LABELS, SR, START, STOP, read_jsonl, write_json, write_wav
def trim(x, rel=0.01, margin=160):
"""Cut leading and trailing silence, keeping 10 ms each side."""
x = x.astype(np.float32) / 32768.0
if not len(x):
return x
loud = np.nonzero(np.abs(x) > rel * max(float(np.abs(x).max()), 1e-6))[0]
return x[max(0, loud[0] - margin): loud[-1] + margin] if len(loud) else x[:0]
def lay_out(d, clips, bank, rng, barge_prob=0.0):
"""Returns (placements, events, end_sample) or None when a turn could not be voiced."""
turns = []
for ti, turn in enumerate(d["turns"]):
parts, si = [], 0
while f"t{ti}_s{si}" in clips:
part = trim(clips[f"t{ti}_s{si}"])
if len(part) < SR // 20:
return None
parts.append(part)
si += 1
if not parts:
return None
turns.append((turn["spk"], parts, turn.get("interrupts", False)))
cg, ag = 10 ** (rng.uniform(-6, 0) / 20), 10 ** (rng.uniform(-3, 0) / 20)
place, events = [], []
t = int(rng.uniform(0.3, 1.0) * SR)
for k, (spk, parts, _) in enumerate(turns):
nxt = turns[k + 1] if k + 1 < len(turns) else None
if spk == "caller":
start = t
for pi, part in enumerate(parts):
place.append((CALLER, t, part * cg))
t += len(part)
if pi < len(parts) - 1: # mid-sentence pause: stays WAIT
pause = int(rng.uniform(0.5, 2.0) * SR)
events.append({"type": "pause", "start": t, "end": t + pause, "f0": -(-t // FRAME), "f1": (t + pause) // FRAME})
t += pause
events.append({"type": "caller_turn", "start": start, "end": t})
if nxt: # the agent answers: START until its audio begins
f0 = -(-t // FRAME)
f1 = f0 + int(rng.integers(2, 13)) # 160 ms to 960 ms
events.append({"type": "start", "caller_end": t, "f0": f0, "f1": f1})
t = f1 * FRAME
else:
seg = np.concatenate(parts) * ag
start = t
# the caller cuts in: where the dialogue says so, and at random elsewhere (barge_prob), so that
# true interruptions are not vastly outnumbered by backchannels
if nxt and len(seg) > 2.5 * SR and (nxt[2] or rng.random() < barge_prob):
react = int(rng.integers(3, 8)) # the agent stops 240 ms to 560 ms after noticing
onset = start + int(rng.uniform(0.35, 0.8) * (len(seg) - (react + 2) * FRAME))
f_cut = onset // FRAME + 1 + react
seg = seg[: f_cut * FRAME - start].copy()
seg[-320:] *= np.linspace(1.0, 0.0, 320, dtype=np.float32)
place.append((AGENT, start, seg))
events.append({"type": "interrupt", "onset": onset, "f0": onset // FRAME + 1, "f1": f_cut})
t = onset # the caller's next turn starts here, over the agent
else:
place.append((AGENT, start, seg))
taken = []
if bank and len(seg) > 4 * SR and rng.random() < 0.5:
for _ in range(int(rng.integers(1, 3))):
bc = bank[int(rng.integers(len(bank)))] * cg * rng.uniform(0.5, 1.0)
pos = start + int(rng.uniform(1.0 * SR, len(seg) - 1.0 * SR - len(bc)))
if any(pos < e and s < pos + len(bc) + SR for s, e in taken):
continue
taken.append((pos, pos + len(bc)))
place.append((CALLER, pos, bc))
events.append({"type": "backchannel", "start": pos, "end": pos + len(bc),
"f0": pos // FRAME + 1, "f1": -(-(pos + len(bc)) // FRAME)})
t = start + len(seg) + int(rng.uniform(0.2, 1.2) * SR)
return place, events, t + int(0.5 * SR)
def fft_conv(x, h):
n = 1 << (len(x) + len(h) - 1).bit_length()
return np.fft.irfft(np.fft.rfft(x, n) * np.fft.rfft(h, n), n)[: len(x)].astype(np.float32)
def room(rng):
"""Synthetic room response: direct path plus exponentially decaying noise."""
rt60 = rng.uniform(0.15, 0.7)
n = int(rt60 * SR)
h = rng.standard_normal(n) * np.exp(-6.908 * np.arange(n) / SR / rt60)
h[: int(0.002 * SR)] = 0.0
h *= 10 ** (-rng.uniform(3, 15) / 20) / np.sqrt(np.sum(h ** 2) + 1e-9) # direct-to-reverberant ratio 3 to 15 dB
h[0] = 1.0
return h.astype(np.float32)
def colored_noise(rng, n):
"""Noise with a random spectral tilt between white and brown, unit RMS."""
spec = np.fft.rfft(rng.standard_normal(n))
f = np.fft.rfftfreq(n, 1.0 / SR)
f[0] = f[1]
x = np.fft.irfft(spec / f ** (rng.uniform(0.0, 2.0) / 2.0), n)
return (x / (np.sqrt(np.mean(x ** 2)) + 1e-9)).astype(np.float32)
def degrade_caller(caller, agent, rng):
"""What the model's microphone side would hear: room, echo of itself, line, noise."""
active = caller[np.abs(caller) > 1e-4]
speech_rms = float(np.sqrt(np.mean(active ** 2))) if len(active) else 0.05
n, fx = len(caller), []
if rng.random() < 0.6:
caller = fft_conv(caller, room(rng))
fx.append("room")
if rng.random() < 0.3: # the agent's voice leaking back, delayed and quiet
delay = int(rng.uniform(0.04, 0.2) * SR)
echo = fft_conv(np.concatenate([np.zeros(delay, np.float32), agent[: n - delay]]), room(rng))
caller = caller + echo * 10 ** (-rng.uniform(18, 35) / 20)
fx.append("echo")
if rng.random() < 0.3: # narrow telephone band
spec = np.fft.rfft(caller)
f = np.fft.rfftfreq(n, 1.0 / SR)
spec[(f < 300) | (f > 3400)] = 0
caller = np.fft.irfft(spec, n).astype(np.float32)
fx.append("phone_band")
if rng.random() < 0.85:
noise = colored_noise(rng, n)
if rng.random() < 0.2:
tt = np.arange(n) / SR
f0 = float(rng.choice([50.0, 60.0]))
noise = noise + 2.0 * sum(np.sin(2 * np.pi * f0 * h * tt + rng.uniform(0, 6.28)) / h for h in (1, 2, 3)).astype(np.float32)
noise /= np.sqrt(np.mean(noise ** 2)) + 1e-9
snr = rng.uniform(5, 35)
caller = caller + noise * speech_rms * 10 ** (-snr / 20)
fx.append(f"noise_snr{snr:.0f}")
if rng.random() < 0.3: # short bangs: not speech, must not trigger anything
for _ in range(int(rng.integers(1, 4))):
m = int(rng.uniform(0.1, 0.4) * SR)
pos = int(rng.integers(0, max(1, n - m)))
caller[pos: pos + m] += colored_noise(rng, m) * np.hanning(m).astype(np.float32) * speech_rms * rng.uniform(0.5, 1.5)
fx.append("bursts")
return caller, fx
def build(job):
d, tts_dir, out_dir, seed, barge_prob = job
try:
z = np.load(Path(tts_dir) / f"{d['id']}.npz")
clips = {k: z[k] for k in z.files}
except FileNotFoundError:
return None
bank_file = Path(tts_dir) / f"_bank_{d['caller_voice']}.npz"
bank = []
if bank_file.exists():
z = np.load(bank_file)
bank = [b for b in (trim(z[k]) for k in z.files) if len(b) > SR // 20]
rng = np.random.default_rng([seed, zlib.crc32(d["id"].encode())])
laid = lay_out(d, clips, bank, rng, barge_prob)
if laid is None:
return None
place, events, end = laid
n_frames = -(-end // FRAME)
audio = np.zeros((n_frames * FRAME, 2), dtype=np.float32)
for ch, start, x in place:
x = x[: len(audio) - start]
audio[start: start + len(x), ch] += x
audio[:, CALLER], fx = degrade_caller(audio[:, CALLER], audio[:, AGENT], rng)
peak = float(np.abs(audio).max())
if peak > 0.99:
audio *= 0.99 / peak
labels = np.zeros(n_frames, dtype=np.uint8)
for e in events:
code = {"start": START, "interrupt": STOP, "backchannel": BACKCHANNEL}.get(e["type"])
if code is not None:
labels[e["f0"]: e["f1"]] = code
out = Path(out_dir)
write_wav(out / "audio" / f"{d['id']}.wav", audio, SR)
np.save(out / "labels" / f"{d['id']}.npy", labels)
meta = {k: d[k] for k in ("id", "split", "domain", "task", "caller_voice", "agent_voice")}
meta.update(n_frames=int(n_frames), effects=fx, events=[{k: (int(v) if k != "type" else v) for k, v in e.items()} for e in events],
self_corrections=sum(t.get("self_correction", False) for t in d["turns"]))
write_json(out / "meta" / f"{d['id']}.json", meta)
return {"id": d["id"], "split": d["split"], "n_frames": int(n_frames), "labels": np.bincount(labels, minlength=len(LABELS)).tolist(),
"events": dict(Counter(e["type"] for e in events)), "self_corrections": meta["self_corrections"]}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--dialogues", required=True)
ap.add_argument("--tts", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--workers", type=int, default=16)
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--barge-prob", type=float, default=0.25, help="chance that a caller turn not marked as an interruption still starts over the agent")
args = ap.parse_args()
out = Path(args.out)
for sub in ("audio", "labels", "meta"):
(out / sub).mkdir(parents=True, exist_ok=True)
dialogues = read_jsonl(args.dialogues)
with Pool(args.workers) as pool:
rows = [r for r in pool.imap_unordered(build, [(d, args.tts, args.out, args.seed, args.barge_prob) for d in dialogues], chunksize=4) if r]
stats = {"dialogues_in": len(dialogues), "dialogues_built": len(rows), "frame_ms": 80, "labels": LABELS}
for split in ("train", "test"):
part = sorted((r for r in rows if r["split"] == split), key=lambda r: r["id"])
write_json(out / f"index_{split}.json", [{"id": r["id"], "n_frames": r["n_frames"]} for r in part])
counts = np.sum([r["labels"] for r in part], axis=0) if part else np.zeros(len(LABELS))
events = Counter()
for r in part:
events.update(r["events"])
stats[split] = {
"dialogues": len(part), "hours": round(sum(r["n_frames"] for r in part) * 0.08 / 3600, 3),
"label_frames": dict(zip(LABELS, (int(c) for c in counts))), "events": dict(events),
"self_corrections": sum(r["self_corrections"] for r in part),
}
write_json(out / "stats.json", stats)
print(json.dumps(stats, indent=2))
if __name__ == "__main__":
main()