"""Shared by every data source: dataset schema, clip boundaries, turn start, writing and merging parts.""" import io import json from pathlib import Path import numpy as np import pandas as pd import pyarrow as pa import pyarrow.parquet as pq import soundfile as sf from datasets import Audio, ClassLabel, Dataset, Features, Value from sklearn.linear_model import LogisticRegression from scripts.vad import Segment SR = 16000 # every source's clips are stored at 16 kHz # One schema for all sources. FEATURES = Features({ "id": Value("string"), "audio": Audio(sampling_rate=SR), "data_source": Value("string"), "original_data_id": Value("string"), "channel": Value("int8"), "timestamp_start": Value("float64"), "timestamp_end": Value("float64"), "label": ClassLabel(names=["incomplete", "complete"]), "meta": Value("string"), }) def turn_start(own: list[Segment], j: int, other: list[Segment], other_turn_starts: list[float], complete: list[bool], real_seg_s: float) -> tuple[float, str]: """Where S's current turn starts, as production could know it at own[j].fire, and why. Walk back over S's segments; the run breaks between own[k-1] and own[k] when - the other speaker had a real segment in the gap (judged only with audio up to fire): other_real_segment - an annotated turn of the other speaker started after own[k-1] started: other_annotated_turn - point k-1 was a complete turn end: prev_complete """ fire = own[j].fire for k in range(j, 0, -1): if any(own[k - 1].end <= o.start < own[k].start and min(o.end, fire) - o.start >= real_seg_s for o in other): return own[k].start, "other_real_segment" if any(own[k - 1].start < s <= own[k].start for s in other_turn_starts): return own[k].start, "other_annotated_turn" if complete[k - 1]: return own[k].start, "prev_complete" return own[0].start, "dialogue_start" def bounds(start: float, fire: float, sr: int, preroll_s: float, max_clip_s: float) -> tuple[int, int]: """Clip sample range [a, b): pre-roll before the turn start, ends exactly at fire_time, at most max_clip_s long. Nothing after fire_time: that audio would tell the model whether the speaker went on (label leak). Long monologues keep only their last max_clip_s (the model crops to a few seconds anyway). """ return round(max(start - preroll_s, fire - max_clip_s, 0.0) * sr), round(fire * sr) def dataset_row(point: dict, wav, data_source: str, meta: dict) -> dict: """One dataset row: the clip (16 kHz) as FLAC bytes + the shared columns, in FEATURES order.""" buf = io.BytesIO() sf.write(buf, wav, SR, format="FLAC", subtype="PCM_16") row = {**point, "audio": {"bytes": buf.getvalue(), "path": f"{point['id']}.flac"}, "data_source": data_source, "meta": json.dumps(meta)} return {k: row[k] for k in FEATURES} def write_rows(rows: list[dict], path: Path) -> None: # Dataset.from_list([]) can't build an empty table, so an empty part is written straight from the schema. table = Dataset.from_list(rows, features=FEATURES).data.table if rows else FEATURES.arrow_schema.empty_table() pq.write_table(table, path) def merge_parts(parts: Path, ids: list[str], out: Path, split: str, source: str, rows_per_shard: int) -> tuple[pa.Table, pd.DataFrame]: """Per-item parts -> data/{split}-XXXXX.parquet shards + dropped/{source}/{split}.parquet. Shard numbers continue after the split's existing shards, so sources built one after another into the same root share one numbering (SpokenWOZ 00000.., then Seamless). Rebuilding a source means rebuilding the split. """ first = len(list((out / "data").glob(f"{split}-*.parquet"))) table = pa.concat_tables([pq.read_table(parts / f"{i}.parquet") for i in ids]) for n, start in enumerate(range(0, max(len(table), 1), rows_per_shard)): pq.write_table(table.slice(start, rows_per_shard), out / "data" / f"{split}-{first + n:05d}.parquet") dropped = pd.concat([pd.read_parquet(parts / f"{i}.dropped.parquet") for i in ids], ignore_index=True) dropped.to_parquet(out / "dropped" / source / f"{split}.parquet") return table, dropped def duration_baseline(kept: pd.DataFrame, seed: int) -> dict: """Shortcut check for reports: label from log clip duration alone, conversation-level 50/50 split.""" ids = kept.original_data_id.unique() test = set(np.random.default_rng(seed).permutation(ids)[: len(ids) // 2]) te = kept.original_data_id.isin(test).to_numpy() x, y = np.log(kept[["clip_duration_s"]].to_numpy()), (kept.label == "complete").to_numpy() acc = LogisticRegression().fit(x[~te], y[~te]).score(x[te], y[te]) return {"accuracy": acc, "majority": max(y[te].mean(), 1 - y[te].mean())}