File size: 5,372 Bytes
c202fc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()