File size: 11,462 Bytes
c202fc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2871b55
 
 
 
c202fc8
 
2871b55
c202fc8
2871b55
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
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
"""Do the paper's audio-side findings survive a change of voice?

    python analysis/06_voice_study/05_replication.py
    python analysis/06_voice_study/05_replication.py --skip-models   # fast

The voice study holds the words fixed and swaps the voice. The paper's claim is not
"audio ratings are high" but "audio judgments are behaviourally distinct from
text": raters commit to a winner at smaller gaps, lean on length less, favour
the second-presented item, and agree with the text winner at near chance. If
those signatures only exist for Kokoro af_heart they are properties of one TTS
voice, not of the audio modality. This script recomputes each of them per arm.

Five quantities, matching Section 4 of the paper:

  threshold   Mean per-prompt rating gap on non-tie trials (paper Fig. 1):
              audio 26.0 vs text 39.8 over 100 prompts. The paper's threshold
              text and tables pool trials instead (audio 27.9, text 41.7);
              08_cross_study/01_threshold_summary.py reports that version.
  length      Coefficient on z-scored response character length (paper Table 1;
              audio b = 3.52, text b = 4.92).
  recency     Coefficient on presented-first (paper b = -2.61: first-presented
              rated LOWER, i.e. the second item is favoured).
  icc         ICC(2,1) and ICC(2,k) from crossed random effects
              (paper audio .333 / .821, text .295 / .788).
  agreement   Winner agreement with the ORIGINAL TEXT condition, per prompt.

Every arm-level number is also recomputed for the original af_heart audio and
the original text on the SAME 30 prompts. The published values cover 100
prompts, so comparing a 30-prompt arm against them would confound the voice
with the stimulus subset. The matched columns are the honest comparison; the
published ones are shown only for orientation.
"""

from __future__ import annotations

import argparse
import sys
import warnings
from pathlib import Path

import numpy as np
import pandas as pd

warnings.filterwarnings("ignore")

sys.path.insert(0, str(Path(__file__).resolve().parent))   # for lme4.py

ROOT = Path(__file__).resolve().parent.parent.parent
VOICE_DATA = ROOT / "data/voice_study"
CONTEXT_DATA = ROOT / "data/audio_context_study"
DERIVED = ROOT / "results/06_voice_study"
SD = ROOT / "data/main_study"

# Published values, 100 prompts. Orientation only -- see module docstring.
# ICCs are variance ratios from squared random-effect SDs, matching
# 02_main_study/02_reliability_icc_alpha.py calc_icc and the variances this
# module's own icc() gets from lmer_varcomp. (Earlier values -- audio
# 0.333/0.821, text 0.295/0.788 -- were SD ratios and are not comparable.)
PAPER = {
    "audio": dict(threshold=27.9, length=3.52, recency=-2.61,
                  icc1=0.312, icck=0.806),
    "text": dict(threshold=41.7, length=4.92, recency=-2.61,
                 icc1=0.241, icck=0.738),
}


# --------------------------------------------------------------- loading ----
def load_lengths() -> pd.Series:
    """AudioClip -> response character length."""
    s = pd.read_csv(SD / "survey_long_format.csv")
    return s.set_index("AudioClip")["TextLength"]


def load_arms(prompts: set[str] | None) -> pd.DataFrame:
    """New voice arms, plus original audio and text as reference arms."""
    frames = []

    abl = VOICE_DATA / "long_voice_normalized.csv"
    if abl.exists():
        frames.append(pd.read_csv(abl))
    else:
        print(f"!! {abl.relative_to(ROOT)} missing — run build_long_tables.py")

    for name, f in (("ORIGINAL af_heart", "long_audio_table_normalized.csv"),
                    ("ORIGINAL text", "long_text_table_normalized.csv")):
        d = pd.read_csv(SD / f)
        d = d[~d["IsAttentionCheck"].astype(bool)].copy()
        d["Arm"] = name
        frames.append(d)

    df = pd.concat(frames, ignore_index=True)
    df = df.dropna(subset=["Rating"])
    if prompts is not None:
        df = df[df["PromptID"].isin(prompts)]
    return df


# --------------------------------------------------------------- metrics ----
def decision_threshold(g: pd.DataFrame) -> tuple[float, int]:
    """Mean per-prompt rating gap on trials where a winner was declared.

    One trial contributes two rows (the two clips), so the gap is taken within
    (participant, prompt) and only where overallPreference is not a Tie.
    """
    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, 0
    per_prompt = gaps.groupby(level="PromptID").mean()
    return per_prompt.mean(), len(per_prompt)


def winner(g: pd.DataFrame, col: str = "Rating") -> pd.Series:
    """PromptID -> winning clip, or 'tie' when the two clip means are equal."""
    m = g.groupby(["PromptID", "AudioClip"])[col].mean().reset_index()
    out = {}
    for pid, sub in m.groupby("PromptID"):
        if len(sub) < 2:
            continue
        sub = sub.sort_values(col, ascending=False)
        top, second = sub.iloc[0], sub.iloc[1]
        out[pid] = "tie" if top[col] == second[col] else top["AudioClip"]
    return pd.Series(out, name="winner")


def fit_bias_model(g: pd.DataFrame, lengths: pd.Series):
    """Paper Table 1, one arm at a time.

    Rating ~ presented_first + char_len_z + trial_z + (1|participant) + (1|clip)

    Crossed random effects, so lme4. Not via pymer4: 0.9.2 cannot convert a
    DataFrame under rpy2 3.6, so lme4.py drives R directly. That substitution
    reproduces the paper's Table 1 exactly -- see validate_against_paper.py.
    Returns (recency_b, recency_p, length_b, length_p) or NaNs.
    """
    from _lme4 import lmer_fixed

    d = g.copy()
    d["char_len"] = d["AudioClip"].map(lengths)
    d = d.dropna(subset=["char_len", "Rating", "TrialNumber"])
    if d["ParticipantID"].nunique() < 3 or len(d) < 40:
        return (np.nan,) * 4
    for src, dst in (("char_len", "char_len_z"), ("TrialNumber", "trial_z")):
        sd = d[src].std()
        d[dst] = 0.0 if not sd else (d[src] - d[src].mean()) / sd
    d["presented_first"] = d["PresentedFirst"].astype(int)

    try:
        fit = lmer_fixed(d, "Rating ~ presented_first + char_len_z + trial_z "
                            "+ (1|ParticipantID) + (1|AudioClip)")
        pick = lambda t, c: (float(fit.loc[t, c]) if t in fit.index else np.nan)
        return (pick("presented_first", "estimate"),
                pick("presented_first", "p"),
                pick("char_len_z", "estimate"),
                pick("char_len_z", "p"))
    except Exception as e:                                   # noqa: BLE001
        print(f"    model failed: {type(e).__name__}: {e}")
        return (np.nan,) * 4


def icc(g: pd.DataFrame):
    """ICC(2,1) and ICC(2,k) from a crossed random-effects decomposition.

    Uses the paper's model on raw ratings, with order and trial position as
    fixed effects:
    Rating ~ presented_first + trial_z + (1|AudioClip) + (1|ParticipantID).

    Variance attributable to the stimulus over stimulus + rater + residual.
    k is the mean number of raters per clip, so ICC(2,k) answers "how reliable
    is the mean of the raters we actually have".
    """
    from _lme4 import lmer_varcomp

    d = g.dropna(subset=["Rating", "TrialNumber", "AudioClip"]).copy()
    if d["ParticipantID"].nunique() < 3 or d["AudioClip"].nunique() < 3:
        return np.nan, np.nan, np.nan
    d["pf"] = d["PresentedFirst"].astype(int)
    sd = d["TrialNumber"].std()
    d["trial_z"] = (d["TrialNumber"] - d["TrialNumber"].mean()) / (sd if sd else 1)
    try:
        rv = lmer_varcomp(
            d, "Rating ~ pf + trial_z + (1|AudioClip) + (1|ParticipantID)")
        v_stim = float(rv.get("AudioClip", np.nan))
        v_rater = float(rv.get("ParticipantID", np.nan))
        v_res = float(rv.get("Residual", np.nan))
        k = d.groupby("AudioClip").size().mean()
        icc1 = v_stim / (v_stim + v_rater + v_res)
        icck = v_stim / (v_stim + (v_rater + v_res) / k)
        return icc1, icck, k
    except Exception as e:                                   # noqa: BLE001
        print(f"    icc failed: {type(e).__name__}: {e}")
        return np.nan, np.nan, np.nan


# ------------------------------------------------------------------ main ----
def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--skip-models", action="store_true",
                    help="threshold and agreement only; no lme4 fits")
    ap.add_argument("--all-prompts", action="store_true",
                    help="do not restrict the reference arms to the 30")
    args = ap.parse_args()

    lengths = load_lengths()

    sel = pd.read_csv(ROOT / "stimuli/voice_study/prompts.csv")["PromptID"]
    prompts = None if args.all_prompts else set(sel)
    if prompts:
        print(f"restricted to the {len(prompts)} Ablation-A prompts "
              f"(reference arms recomputed on the same set)")

    df = load_arms(prompts)
    text_win = winner(df[df["Arm"] == "ORIGINAL text"])

    rows = []
    for arm, g in df.groupby("Arm", sort=True):
        n_part = g["ParticipantID"].nunique()
        n_prompt = g["PromptID"].nunique()
        per_clip = g.groupby("AudioClip").size()
        thr, n_thr = decision_threshold(g)

        w = winner(g)
        both = w.index.intersection(text_win.index)
        agree = (np.nan if len(both) == 0
                 else float((w[both] == text_win[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=n_part,
                         prompts=n_prompt,
                         raters_per_clip=f"{per_clip.min()}-{per_clip.max()}",
                         threshold=thr, recency_b=rec_b, recency_p=rec_p,
                         length_b=len_b, length_p=len_p,
                         icc1=i1, icck=ik, k=kbar,
                         agree_with_text=agree, n_agree=len(both)))

    res = pd.DataFrame(rows)
    out = DERIVED / "voice_replication.csv"
    res.to_csv(out, index=False)

    pd.set_option("display.width", 200, "display.max_columns", 50)
    print("\n" + "=" * 78)
    print("REPLICATION OF THE PAPER'S AUDIO SIGNATURES, BY VOICE")
    print("=" * 78)
    show = res[["arm", "participants", "prompts", "raters_per_clip",
                "threshold", "recency_b", "length_b", "icc1", "icck",
                "agree_with_text"]]
    print(show.to_string(index=False, float_format=lambda x: f"{x:7.3f}"))

    print("\npublished (100 prompts, for orientation only):")
    for k, v in PAPER.items():
        print(f"  {k:6} threshold {v['threshold']:.1f}  length b {v['length']:.2f}"
              f"  recency b {v['recency']:.2f}  ICC(2,1) {v['icc1']:.3f}"
              f"  ICC(2,k) {v['icck']:.3f}")

    thin = res[res["participants"] < 10]
    if not thin.empty:
        print("\n!! UNDERPOWERED — fewer than 10 raters in: "
              + ", ".join(thin["arm"]))
        print("   The design targets 10 ratings per item. Treat every number "
              "above as a pipeline check, not a result.")
    print(f"\nwrote {out.relative_to(ROOT)}")


if __name__ == "__main__":
    sys.exit(main())