File size: 4,325 Bytes
849f535
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Compare what each voice arm actually says, against the af_heart baseline.

    python analysis/06_voice_study/02_transcript_consistency.py

For a voice manipulation the thing that must hold constant is *content*: every
arm has to say the same words, so that only delivery varies. Measuring each
arm against the written script conflates two different failures — whisper
mishearing a proper noun (harmless, and identical in every arm) versus an
engine actually saying something different (fatal, because then content
covaries with arm).

So this reports two numbers per clip:

  wer_vs_text      arm transcript vs the exact script fed to TTS
  wer_vs_baseline  arm transcript vs the af_heart transcript of the same text

wer_vs_baseline is the one that matters. Whisper's own quirks — "colour" ->
"color", "NASCAER" -> "NASCAR" — appear in every arm's transcript and cancel
out, leaving only genuine divergence between engines.

Input is the shipped whisper transcript table (whisper small.en, one row per
rendered clip). Writes stimuli/voice_study/arm_consistency.csv and prints a
per-arm summary plus the worst offenders.
"""

from __future__ import annotations

import csv
import sys
from collections import defaultdict
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "common"))
from _text_utils import normalize, wer  # noqa: E402

VERIF = ROOT / "stimuli/voice_study/whisper_verification.csv"
OUT = ROOT / "stimuli/voice_study/arm_consistency.csv"

BASELINE = "kokoro_af_heart"
# Divergence above this between an arm and the baseline is treated as the arm
# saying something different, not as transcription noise.
DIVERGENCE = 0.15


def main():
    rows = list(csv.DictReader(open(VERIF)))
    by_key: dict[tuple[str, str], dict[str, dict]] = defaultdict(dict)
    for r in rows:
        by_key[(r["PromptID"], r["clip"])][r["arm"]] = r

    if not any(BASELINE in v for v in by_key.values()):
        print(f"!! no {BASELINE} transcripts in {VERIF.name}.")
        print("   (the transcripts come from the stimulus-generation QA step)")
        return

    out, per_arm = [], defaultdict(list)
    for (pid, clip), arms in sorted(by_key.items()):
        base = arms.get(BASELINE)
        if base is None:
            continue
        base_hyp = normalize(base["transcript"])
        for arm, r in arms.items():
            if arm == BASELINE:
                continue
            hyp = normalize(r["transcript"])
            d = wer(base_hyp, hyp)
            out.append(dict(PromptID=pid, clip=clip, arm=arm,
                            wer_vs_text=float(r["wer"]),
                            wer_vs_baseline=round(d, 4),
                            baseline_wer_vs_text=float(base["wer"]),
                            diverges=int(d > DIVERGENCE),
                            arm_transcript=r["transcript"],
                            baseline_transcript=base["transcript"]))
            per_arm[arm].append(d)

    if not out:
        print("no overlapping prompts between the baseline and any other arm")
        return

    with open(OUT, "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(out[0]))
        w.writeheader()
        w.writerows(out)

    print(f"{'arm':22s} {'n':>5} {'median':>8} {'mean':>8} {'p90':>8} "
          f"{'diverging':>10}")
    for arm, ds in sorted(per_arm.items()):
        s = sorted(ds)
        med = s[len(s) // 2]
        p90 = s[min(len(s) - 1, int(0.9 * len(s)))]
        n_div = sum(1 for d in ds if d > DIVERGENCE)
        print(f"{arm:22s} {len(s):5d} {med:8.1%} {sum(s)/len(s):8.1%} "
              f"{p90:8.1%} {n_div:6d} ({n_div/len(s):4.0%})")

    worst = sorted(out, key=lambda r: -r["wer_vs_baseline"])[:15]
    print(f"\nworst divergence from {BASELINE}:")
    for r in worst:
        if r["wer_vs_baseline"] <= DIVERGENCE:
            break
        print(f"  {r['PromptID']:9s} {r['clip']:8s} {r['arm']:18s} "
              f"vs-baseline {r['wer_vs_baseline']:6.1%}  "
              f"(vs-text {r['wer_vs_text']:.1%})")
        print(f"      base: {r['baseline_transcript'][:110]}")
        print(f"      arm : {r['arm_transcript'][:110]}")

    print(f"\nwrote {OUT} ({len(out)} arm-clip comparisons)")


if __name__ == "__main__":
    main()