"""Do the paper's audio-side findings survive when the CONTEXT is heard too? python analysis/07_audio_context_study/02_replication.py python analysis/07_audio_context_study/02_replication.py --skip-models The voice study swapped the voice and held everything else fixed. This study swaps the modality of the conversation history: the same 30 prompts are rated with the history read (the original study) or heard, either in one voice for both speakers (B1) or with a distinct voice per speaker (B2). Every metric is the one _voice_variation_replication.py computes -- imported from there rather than reimplemented, so the two studies cannot drift apart in how a threshold or an ICC is defined. The only differences are which long tables get loaded and which prompt set the reference arms are restricted to (the 30 context prompts, not the 30 voice prompts). B1 is the conservative cell: context modality changes, voice identity does not. B2 adds a second speaker. Reading B2 against B1 rather than against the text baseline is what separates speaker differentiation from audio context itself. """ from __future__ import annotations import argparse import sys from pathlib import Path import numpy as np import pandas as pd sys.path.insert(0, str(Path(__file__).resolve().parent)) from _voice_variation_replication import ( # noqa: E402 CONTEXT_DATA, ROOT, SD, decision_threshold, fit_bias_model, icc, load_lengths, winner, ) DERIVED = ROOT / "results/07_audio_context_study" # Display name -> long table. The two new cells come from the follow-up # pipeline; the two reference arms are the paper's own released tables. ARMS = { "B1 one-voice context": CONTEXT_DATA / "long_audiocontext_onevoice_normalized.csv", "B2 two-voice context": CONTEXT_DATA / "long_audiocontext_normalized.csv", "ORIGINAL af_heart": SD / "long_audio_table_normalized.csv", "ORIGINAL text": SD / "long_text_table_normalized.csv", } def load_arms(prompts: set[str] | None) -> pd.DataFrame: frames = [] for name, f in ARMS.items(): if not f.exists(): print(f"!! {f.relative_to(ROOT)} missing — skipping {name}") continue d = pd.read_csv(f) if "IsAttentionCheck" in d.columns: d = d[~d["IsAttentionCheck"].astype(bool)] d = d.copy() d["Arm"] = name # overwrite the study's own Arm frames.append(d) df = pd.concat(frames, ignore_index=True).dropna(subset=["Rating"]) if prompts is not None: df = df[df["PromptID"].isin(prompts)] return df def threshold_median(g: pd.DataFrame) -> float: """Median of the per-prompt mean gaps -- the paired half of Table 10's pair. The mean is pulled by a handful of prompts where every rater declared a large gap; the paper reports both for that reason. """ d = g[g["overallPreference"].isin(["A", "B"])] gaps = (d.groupby(["ParticipantID", "PromptID"])["Rating"] .agg(lambda x: x.max() - x.min() if len(x) == 2 else np.nan) .dropna()) if gaps.empty: return np.nan return float(gaps.groupby(level="PromptID").mean().median()) def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--skip-models", action="store_true") ap.add_argument("--all-prompts", action="store_true") args = ap.parse_args() lengths = load_lengths() sel = pd.read_csv(ROOT / "stimuli/audio_context_study/prompts.csv")["PromptID"] prompts = None if args.all_prompts else set(sel) if prompts: print(f"restricted to the {len(prompts)} Ablation-B prompts") df = load_arms(prompts) text_win = winner(df[df["Arm"] == "ORIGINAL text"]) b1_win = winner(df[df["Arm"] == "B1 one-voice context"]) rows = [] for arm, g in df.groupby("Arm", sort=True): per_clip = g.groupby("AudioClip").size() thr, _ = decision_threshold(g) w = winner(g) def agree(other): both = w.index.intersection(other.index) return (np.nan if not len(both) else float((w[both] == other[both]).mean())) rec_b = rec_p = len_b = len_p = i1 = ik = kbar = np.nan if not args.skip_models: print(f" fitting {arm} ...") rec_b, rec_p, len_b, len_p = fit_bias_model(g, lengths) i1, ik, kbar = icc(g) rows.append(dict(arm=arm, n=len(g), participants=g["ParticipantID"].nunique(), prompts=g["PromptID"].nunique(), raters_per_clip=f"{per_clip.min()}-{per_clip.max()}", thr_mean=thr, thr_median=threshold_median(g), recency_b=rec_b, recency_p=rec_p, length_b=len_b, length_p=len_p, icc1=i1, icck=ik, k=kbar, agree_text=agree(text_win), agree_b1=agree(b1_win))) res = pd.DataFrame(rows) res.to_csv(DERIVED / "context_replication.csv", index=False) pd.set_option("display.width", 250, "display.max_columns", 50) print("\n" + "=" * 78) print("PAPER'S AUDIO SIGNATURES WITH THE CONTEXT HEARD RATHER THAN READ") print("=" * 78) print(res.to_string(index=False, float_format=lambda x: f"{x:7.3f}")) if __name__ == "__main__": main()