File size: 7,630 Bytes
4ed7d22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0dd0f72
 
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
"""Data report + issues to review + listening exports for one built Seamless split.

python -m scripts.seamless.report --root <dataset_root> --split validation
Writes <root>/report/{split}/data_report.md, PNGs, and listen/{issue}/*.wav + listen.csv (human review only, never training).
"""
import argparse
import json
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pyarrow.parquet as pq
import soundfile as sf

from scripts.seamless.build import Config
from scripts.utils import duration_baseline

N_LISTEN = 10


def load(root: Path, split: str):
    files = sorted((root / "data").glob(f"{split}-*.parquet"))
    t = pq.ParquetDataset(files).read(columns=["id", "data_source", "original_data_id", "channel", "timestamp_start", "timestamp_end", "label", "meta"]).to_pandas()
    t = t[t.data_source == "seamless"].drop(columns="data_source").reset_index(drop=True)  # shards hold every source
    kept = pd.concat([t.drop(columns=["label", "meta"]), pd.DataFrame([json.loads(m) for m in t.meta])], axis=1)
    kept["label"] = t.label.map({0: "incomplete", 1: "complete"})
    dropped = pd.read_parquet(root / "dropped" / "seamless" / f"{split}.parquet")
    for df in (kept, dropped):  # derived from the columns (not stored in meta)
        df["fire_time"] = df.timestamp_end
        df["clip_duration_s"] = df.timestamp_end - df.timestamp_start
    convs = pd.read_parquet(root / "stats" / "seamless" / f"{split}_conversations.parquet")
    meta = json.loads((root / "stats" / "seamless" / f"{split}_meta.json").read_text())
    return kept, dropped, convs, meta


def savefig(out: Path, name: str) -> str:
    plt.tight_layout()
    plt.savefig(out / name, dpi=120)
    plt.close()
    return f"![{name}]({name})"


def issues(kept: pd.DataFrame, dropped: pd.DataFrame, cfg: Config) -> dict[str, tuple[str, pd.DataFrame]]:
    """name -> (what to check, rows); listened to from clip start to fire + tail."""
    return {
        "no_word": ("VAD stop with no word of the speaker ending within 0.5 s. Laugh / breath / noise, or a word the transcript missed?",
                    dropped[dropped.drop_reason == "no_word"]),
        "overlap": ("Speaker stopped while the other was mid-utterance. Backchannel / interjection (right to drop), or a real turn?",
                    dropped[dropped.drop_reason == "overlap"]),
        "collision": ("Both started within 0.2 s after the stop. Who really took the floor?", dropped[dropped.drop_reason == "collision"]),
        "complete_short_reply": ("Complete, but the other's reply is only a few words. Real turn change, or a backchannel the word list missed?",
                                 kept[(kept.label == "complete") & (kept.other_words.str.split().str.len() <= 3)]),
        "capped_clip": (f"Clip cut to {cfg.max_clip_s:.0f} s (long monologue). Does the turn start make sense?",
                        kept[kept.clip_duration_s >= cfg.max_clip_s - 0.01]),
    }


def report(kept, dropped, convs, meta, found, out: Path, cfg: Config) -> str:
    md = ["# EoT data report (Seamless Interaction, naturalistic)",
          f"Conversations: {meta['n_conversations']} · {convs.duration.sum() / 3600:.1f} h · VAD at {meta['vad']['sr']} Hz"]

    md += ["## Counts", kept.label.value_counts().to_frame().to_markdown(),
           f"Complete share: **{(kept.label == 'complete').mean():.1%}**",
           "### Drop reasons", dropped.drop_reason.value_counts().to_frame().to_markdown()]

    md += ["## Issues to review",
           "Listening files are in `listen/{issue}/` (clip start → 2 s after fire time; `listen.csv` has the metadata)."]
    md.append(pd.DataFrame([{"issue": k, "count": len(v[1]), "what to check": v[0]} for k, v in found.items()]).to_markdown(index=False))

    shares = pd.concat([convs.speech_share_0, convs.speech_share_1])
    md += ["## Participants",
           f"Participants skipped (< {cfg.min_speech_share:.0%} speech): {(shares < cfg.min_speech_share).sum()} of {len(shares)}",
           shares.describe(percentiles=[0.1, 0.5, 0.9]).round(3).to_frame("speech share").T.to_markdown(),
           "Clip run breaks:", kept.run_break_reason.value_counts().to_frame().to_markdown()]

    minutes = convs.duration.sum() / 60
    d = kept.clip_duration_s
    md += ["## Clip length",
           f"median {d.median():.2f} s · p90 {d.quantile(0.9):.2f} s · max {d.max():.2f} s · share > 8 s **{(d > 8).mean():.1%}** · "
           f"at the {cfg.max_clip_s:.0f} s cap {(d >= cfg.max_clip_s - 0.01).mean():.1%} · points per minute of conversation {len(kept) / minutes:.1f}"]
    for label, g in kept.groupby("label"):
        g.clip_duration_s.hist(bins=100, alpha=0.5, label=label)
    plt.axvline(8, color="k", lw=0.8)
    plt.xlabel("clip duration (s)")
    plt.legend()
    md.append(savefig(out, "clip_duration.png"))

    md.append("## Pauses before resuming (incomplete) and reply gaps (complete)")
    kept.loc[kept.label == "incomplete", "gap_to_next_same_s"].clip(upper=3).hist(bins=100, alpha=0.5, label="incomplete: pause before resuming")
    kept.loc[kept.label == "complete", "gap_to_next_other_s"].clip(-0.5, 3).hist(bins=100, alpha=0.5, label="complete: reply gap")
    plt.xlabel("s (from speech_end)")
    plt.legend()
    md.append(savefig(out, "gaps.png"))

    md += ["## Word timing at the stop", "Distance from the VAD speech_end to the nearest word end of the speaker (kept points):",
           kept.word_end_offset_s.describe(percentiles=[0.5, 0.9]).round(3).to_frame().T.to_markdown()]

    dur = duration_baseline(kept, cfg.seed)
    md += ["## Clip-duration-only baseline (shortcut check)",
           f"Logistic regression on log(clip_duration_s), conversation-level 50/50 split: accuracy **{dur['accuracy']:.1%}** vs majority {dur['majority']:.1%}."]
    return "\n\n".join(md) + "\n"


def listen(found: dict, split: str, out: Path, cfg: Config) -> None:
    rng = np.random.default_rng(cfg.seed)
    sel = pd.concat([g.iloc[rng.permutation(len(g))[:N_LISTEN]].assign(issue=name) for name, (_, g) in found.items() if len(g)], ignore_index=True)
    sel["wav"] = sel.issue + "/" + sel.id + ".wav"
    for issue in sel.issue.unique():
        (out / issue).mkdir(parents=True, exist_ok=True)
    raw = Path(cfg.raw_dir) / split
    for r in sel.itertuples():  # clip + listen_tail_s after fire_time: for humans only, never training
        a, e = round(r.timestamp_start * cfg.sr), round((r.timestamp_end + cfg.listen_tail_s) * cfg.sr)
        audio, _ = sf.read(raw / f"{r.original_data_id}_{r.participant}.flac", start=a, stop=e, dtype="float32")
        sf.write(out / r.wav, audio, cfg.sr)
    sel["fire_at_s_in_wav"] = sel.timestamp_end - sel.timestamp_start
    cols = ["wav", "issue", "id", "participant", "label", "drop_reason", "fire_at_s_in_wav", "gap_to_next_same_s",
            "gap_to_next_other_s", "run_break_reason", "text", "other_words"]
    sel.reindex(columns=cols).to_csv(out / "listen.csv", index=False)


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--root", type=Path, required=True)
    p.add_argument("--split", default="validation")
    args = p.parse_args()

    cfg = Config()
    out = args.root / "report" / "seamless" / args.split
    out.mkdir(parents=True, exist_ok=True)
    kept, dropped, convs, meta = load(args.root, args.split)
    found = issues(kept, dropped, cfg)
    (out / "data_report.md").write_text(report(kept, dropped, convs, meta, found, out, cfg))
    listen(found, args.split, out / "listen", cfg)


if __name__ == "__main__":
    main()