File size: 12,314 Bytes
f730521
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
"""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()