Datasets:
File size: 12,737 Bytes
4ed7d22 0dd0f72 4ed7d22 0dd0f72 4ed7d22 0dd0f72 4ed7d22 0dd0f72 4ed7d22 0dd0f72 4ed7d22 0dd0f72 4ed7d22 0dd0f72 4ed7d22 0dd0f72 4ed7d22 fb9026f 4ed7d22 fb9026f 4ed7d22 0dd0f72 4ed7d22 0dd0f72 4ed7d22 0dd0f72 4ed7d22 | 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 | """Build the end-of-turn (EoT) dataset from Seamless Interaction (naturalistic conversations).
Every VAD speech_stop of either participant becomes one example: that person's audio from the start of their
current turn up to the moment the stop fires, labelled complete (the other person takes the floor next) or
incomplete (they go on themselves). Labels come from both participants' word timestamps.
python -m scripts.seamless.download --split validation # audio + transcripts -> tmp/seamless/raw/
python -m scripts.seamless.build --split validation --vad-sr 16000 --out <root> [--limit N] [--workers K]
Per conversation (files in <root>/_parts_{source}_{split}/, deleted after the merge) -> output under <root>:
data/{split}-XXXXX.parquet same schema as every source (scripts/utils.py FEATURES)
dropped/{split}.parquet dropped points with the reason (no audio)
stats/{split}_conversations.parquet, _meta.json per-conversation info, settings used
"""
import argparse
import json
import re
import shutil
import zlib
from dataclasses import dataclass
from multiprocessing import Pool
from pathlib import Path
import numpy as np
import pandas as pd
import soundfile as sf
import torch
from tqdm import tqdm
from scripts.utils import SR, bounds, dataset_row, merge_parts, turn_start, write_rows
from scripts.vad import Segment, VadConfig, detect
@dataclass(frozen=True)
class Config:
raw_dir: str = "tmp/seamless/raw" # filled by scripts.seamless.download (16 kHz FLAC + transcript json)
data_source: str = "seamless"
sr: int = SR # raw audio and clip rate (source is 48 kHz, downsampled to 16 kHz on download)
min_speech_share: float = 0.05 # participants who barely speak give no examples (still count as the other)
word_tol_s: float = 0.5 # a stop needs a word of the speaker ending this close to it (else VAD noise)
terminal_overlap_s: float = 0.5 # the other may start this long before S stops and it still counts as a reply
collision_s: float = 0.2 # both start within this of each other -> ambiguous
long_gap_s: float = 3.0 # nobody speaks for longer than this -> ambiguous
# A listener's reaction is not taking the floor: an utterance of <= 3 words that are all reaction words,
# or any utterance of <= 3 words after which S speaks again within 1 s (S never gave up the floor).
backchannel_words: tuple = ("mm", "mmm", "hmm", "mhm", "mm-hmm", "mmhmm", "uh", "huh", "uh-huh", "uhhuh", "yeah", "yea",
"yes", "right", "okay", "ok", "oh", "wow", "alright", "all", "sure", "really", "ha")
short_reply_words: int = 3
resume_after_reply_s: float = 1.0
real_seg_s: float = 1.0 # other-speaker VAD segments shorter than this don't break the clip's turn
preroll_s: float = 0.3 # audio kept before the turn start
max_clip_s: float = 30.0 # clips keep at most the last 30 s before fire_time
other_words_s: float = 3.0 # window for the other speaker's words in meta (review only)
listen_tail_s: float = 2.0 # audio after fire_time in listening exports (humans only, never training)
# Long monologues give many near-duplicate incomplete points; keep a random few per turn (complete ones all stay).
max_incomplete_per_turn: int = 2
rows_per_shard: int = 10000
seed: int = 0
CFG = Config()
# ======================================================================== transcripts
def words_and_utterances(transcript: list[dict], cfg: Config) -> tuple[list[tuple], list[tuple]]:
"""Timed words (start, end, word) and utterances (start, end, n_words, all_reaction_words) from one transcript.
Utterances are the transcript segments; words without timestamps (not aligned) are left out.
"""
words, utts = [], []
for seg in transcript:
ws = [(w["start"], w["end"], w["word"]) for w in seg["words"] if w.get("start") is not None]
if not ws:
continue
words += ws
tokens = [re.sub(r"[^\w'-]", "", w[2].lower()) for w in ws]
utts.append((ws[0][0], ws[-1][1], len(tokens), all(t in cfg.backchannel_words for t in tokens)))
return words, utts
# ======================================================================== labels
def floor_utterances(other_utts: list[tuple], own_words: list[tuple], cfg: Config) -> list[tuple]:
"""(start, end) of the other's utterances that take the floor: everything except short reactions (backchannels)."""
floor = []
for s, e, n, reaction in other_utts:
resume = next((ws for ws, _, _ in own_words if ws >= e), None)
backchannel = n <= cfg.short_reply_words and (reaction or (resume is not None and resume - e <= cfg.resume_after_reply_s))
if not backchannel:
floor.append((s, e))
return floor
def label_stop(seg: Segment, own_words: list[tuple], floor: list[tuple], cfg: Config) -> dict:
"""Label one VAD stop of S from both participants' word timings.
- no word of S ends within word_tol_s of the stop -> dropped (no_word: VAD noise)
- the other is in the middle of a floor-taking utterance when S stops -> dropped (overlap)
- S's next word comes before the other takes the floor -> incomplete
- the other takes the floor first (backchannels don't count) -> complete
- nobody speaks within long_gap_s / both start together -> dropped (long_gap / collision)
"""
near = min((abs(e - seg.end) for _, e, _ in own_words), default=float("inf"))
own_next = next((s for s, _, _ in own_words if s >= seg.end), None)
other_next = next((s for s, _ in floor if s >= seg.end - cfg.terminal_overlap_s), None)
gap_same = None if own_next is None else own_next - seg.end
gap_other = None if other_next is None else other_next - seg.end
gaps = [g for g in (gap_same, gap_other) if g is not None]
if near > cfg.word_tol_s:
label, reason = None, "no_word"
elif any(s < seg.end - cfg.terminal_overlap_s and seg.end < e for s, e in floor):
label, reason = None, "overlap"
elif not gaps or min(gaps) > cfg.long_gap_s:
label, reason = None, "long_gap"
elif len(gaps) == 2 and abs(gap_same - gap_other) <= cfg.collision_s:
label, reason = None, "collision"
else:
label, reason = ("incomplete", None) if gap_same is not None and (gap_other is None or gap_same < gap_other) else ("complete", None)
return {"label": label, "drop_reason": reason, "gap_to_next_same_s": gap_same, "gap_to_next_other_s": gap_other,
"word_end_offset_s": near}
def cap_incomplete(labels: list[dict], turn_starts: list[float], cap: int, rng: np.random.Generator) -> set[int]:
"""Indices of incomplete points to drop so each turn (same turn start) keeps at most `cap`, chosen at random."""
by_turn = {}
for j, (b, start) in enumerate(zip(labels, turn_starts)):
if b["label"] == "incomplete":
by_turn.setdefault(start, []).append(j)
keep = {j for js in by_turn.values() for j in rng.permutation(js)[:cap]}
return {j for js in by_turn.values() for j in js} - keep
# ======================================================================== per conversation
def label_conversation(job) -> None:
conv, keys, raw, vad, parts = job # keys: the two participant files, sorted -> channel 0 / 1
audio = [sf.read(raw / f"{k}.flac", dtype="float32")[0] for k in keys]
transcripts = [json.loads((raw / f"{k}.json").read_text())["metadata:transcript"] for k in keys]
segments = [detect(a, CFG.sr, vad) for a in audio]
words, utts = zip(*(words_and_utterances(t, CFG) for t in transcripts))
duration = len(audio[0]) / CFG.sr
speech_share = [sum(s.dur for s in segs) / duration for segs in segments]
rows, dropped = [], []
for ch in (0, 1):
if speech_share[ch] < CFG.min_speech_share:
continue
own, other = segments[ch], segments[1 - ch]
floor = floor_utterances(utts[1 - ch], words[ch], CFG)
labels = [label_stop(seg, words[ch], floor, CFG) for seg in own]
complete = [b["label"] == "complete" for b in labels]
other_turn_starts = [s for s, _ in floor]
starts = [turn_start(own, j, other, other_turn_starts, complete, CFG.real_seg_s) for j in range(len(own))]
rng = np.random.default_rng([CFG.seed, zlib.crc32(f"{conv}_{ch}".encode())]) # same choice on every rebuild
for j in cap_incomplete(labels, [s for s, _ in starts], CFG.max_incomplete_per_turn, rng):
labels[j] = {**labels[j], "label": None, "drop_reason": "turn_cap"}
# One point per VAD stop of this participant; j counts all stops, so ids stay stable when rules change.
for j, (seg, b) in enumerate(zip(own, labels)):
start, run_break = starts[j]
s0, s1 = bounds(start, seg.fire, CFG.sr, CFG.preroll_s, CFG.max_clip_s)
meta = {
"participant": keys[ch].rsplit("_", 1)[1], **{k: v for k, v in b.items() if k not in ("label", "drop_reason")},
"turn_start": start, "run_break_reason": run_break, "speech_start": seg.start, "speech_end": seg.end,
"text": " ".join(w for s, _, w in words[ch] if s0 / CFG.sr <= s < seg.end), # words inside the clip
"other_words": " ".join(w for s, _, w in words[1 - ch] if seg.end <= s < seg.end + CFG.other_words_s),
"speech_share": speech_share[ch],
}
meta = {k: round(v, 3) if isinstance(v, float) else v for k, v in meta.items()} # times to ms
point = {"id": f"{CFG.data_source}_{conv}_{ch}_{j:03d}", "original_data_id": conv, "channel": ch,
"timestamp_start": round(s0 / CFG.sr, 3), "timestamp_end": round(s1 / CFG.sr, 3), "label": b["label"]}
if b["label"] is None:
dropped.append({**point, "drop_reason": b["drop_reason"], **meta})
else:
rows.append(dataset_row(point, audio[ch][s0:s1], CFG.data_source, meta))
pd.DataFrame(dropped).to_parquet(parts / f"{conv}.dropped.parquet")
write_rows(rows, parts / f"{conv}.parquet")
(parts / f"{conv}.json").write_text(json.dumps({"duration": duration, "speech_share": speech_share, "participants": keys}))
# ======================================================================== main
def main():
p = argparse.ArgumentParser()
p.add_argument("--split", required=True, choices=["train", "validation", "test"])
p.add_argument("--vad-sr", required=True, type=int, choices=[8000, 16000])
p.add_argument("--out", required=True, type=Path)
p.add_argument("--limit", type=int)
p.add_argument("--workers", type=int, default=8)
args = p.parse_args()
out, split, vad = args.out, args.split, VadConfig(sr=args.vad_sr)
parts, stats = out / f"_parts_{CFG.data_source}_{split}", out / "stats" / CFG.data_source
for d in (parts, out / "data", out / "dropped" / CFG.data_source, stats):
d.mkdir(parents=True, exist_ok=True)
# Conversations = V_S_I with both participants downloaded; participants sorted -> channel 0 / 1.
# A few source recordings are empty (no audio, empty transcript, e.g. test V03_S2028): their 0-byte FLACs are skipped.
raw = Path(CFG.raw_dir) / split
keys = sorted(f.stem for f in raw.glob("*.json") if f.with_suffix(".flac").stat().st_size > 0)
convs = {}
for k in keys:
convs.setdefault(k.rsplit("_", 1)[0], []).append(k)
ids = sorted(c for c, ks in convs.items() if len(ks) == 2)[: args.limit]
with Pool(args.workers, initializer=torch.set_num_threads, initargs=(1,)) as pool:
jobs = [(c, convs[c], raw, vad, parts) for c in ids]
for _ in tqdm(pool.imap_unordered(label_conversation, jobs), total=len(jobs), desc="label"):
pass
table, dropped = merge_parts(parts, ids, out, split, CFG.data_source, CFG.rows_per_shard)
conv_stats = [json.loads((parts / f"{c}.json").read_text()) for c in ids]
pd.DataFrame([{"conversation": c, "duration": s["duration"], "speech_share_0": s["speech_share"][0],
"speech_share_1": s["speech_share"][1], "participant_0": s["participants"][0], "participant_1": s["participants"][1]}
for c, s in zip(ids, conv_stats)]).to_parquet(stats / f"{split}_conversations.parquet")
meta = {"n_conversations": len(ids), "config": vars(CFG), "vad": vars(vad)}
(stats / f"{split}_meta.json").write_text(json.dumps(meta, indent=1))
shutil.rmtree(parts)
print(f"{split}: {len(table)} rows, {len(dropped)} dropped, {len(ids)} conversations")
if __name__ == "__main__":
main()
|