File size: 8,673 Bytes
cc7d399
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Merge Gemma 4 results into the main sf_results.csv and regenerate figures.

Run after eval_multilang.py --run-gemma4 finishes:
    uv run python scripts/merge_gemma4.py
"""
import sys
from pathlib import Path

ROOT = Path(__file__).parent.parent
sys.path.insert(0, str(Path(__file__).parent))
from runtime_cache import configure_runtime_cache

configure_runtime_cache(ROOT)

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

GEMMA4_CSV  = ROOT / 'results_gemma4' / 'sf_results.csv'
MAIN_CSV    = ROOT / 'analysis' / 'sf_results.csv'
FIGURES_DIR = ROOT / 'figures'
PAPER_FAMILIES = {'Whisper', 'MMS', 'SeamlessM4T', 'Gemma4'}


def paper_rows(df: pd.DataFrame) -> pd.DataFrame:
    """Rows included in the main paper benchmark."""
    return df[df['family'].isin(PAPER_FAMILIES)].copy()


def merge() -> pd.DataFrame:
    if not GEMMA4_CSV.exists():
        sys.exit(f'Gemma 4 results not found at {GEMMA4_CSV}')

    g4 = pd.read_csv(GEMMA4_CSV)
    print(f'Gemma 4 rows: {len(g4)}')
    print(g4[['model', 'language', 'sfr_mean', 'sfr_zero_pct']].to_string(index=False))

    main = pd.read_csv(MAIN_CSV)
    print(f'\nExisting rows: {len(main)}')

    # Drop any existing Gemma 4 rows in main (in case of re-run)
    gemma_models = g4['model'].unique()
    main = main[~main['model'].isin(gemma_models)]

    merged = pd.concat([main, g4], ignore_index=True)
    merged.to_csv(MAIN_CSV, index=False)
    print(f'Merged rows: {len(merged)} → saved to {MAIN_CSV}')
    return merged


def make_heatmap(df: pd.DataFrame) -> None:
    df = paper_rows(df)
    pivot = df.pivot_table(
        index='model', columns='language', values='sfr_mean', aggfunc='first')
    if pivot.empty:
        return

    short_names = (
        pivot.index
        .str.replace('openai/whisper-large-v3-turbo', 'Whisper turbo')
        .str.replace('openai/whisper-', 'Whisper ')
        .str.replace('facebook/mms-1b-all', 'MMS 1B')
        .str.replace('facebook/seamless-m4t-v2-large', 'SeamlessM4T v2')
        .str.replace('unsloth/gemma-4-E2B-it', 'Gemma 4 E2B')
    )

    # Sort: Whisper family first (by size), then MMS, Seamless, Gemma
    order = ['tiny', 'base', 'small', 'medium', 'large', 'turbo', 'MMS', 'Seamless', 'Gemma']
    def sort_key(name):
        for i, k in enumerate(order):
            if k.lower() in name.lower():
                return i
        return 99
    sorted_pairs = sorted(zip(short_names.tolist(), pivot.index.tolist()), key=lambda x: sort_key(x[0]))
    sorted_short, sorted_model = zip(*sorted_pairs)
    pivot = pivot.loc[list(sorted_model)]

    fig, ax = plt.subplots(figsize=(max(10, len(pivot.columns) * 1.4),
                                    max(6, len(pivot) * 0.55)))
    sns.heatmap(
        pivot.values,
        xticklabels=pivot.columns.tolist(),
        yticklabels=list(sorted_short),
        annot=True, fmt='.1f',
        cmap='RdYlGn', vmin=0, vmax=100,
        linewidths=0.5, ax=ax,
        cbar_kws={'label': 'Script Fidelity (%)'},
    )
    ax.set_title('Script Fidelity (%) by Model and Language — FLEURS Test Sets')
    ax.set_xlabel('Language')
    ax.set_ylabel('Model')
    plt.tight_layout()

    FIGURES_DIR.mkdir(exist_ok=True)
    for ext in ('pdf', 'png'):
        out = FIGURES_DIR / f'sfr_heatmap.{ext}'
        fig.savefig(out, bbox_inches='tight', dpi=150)
        print(f'Saved: {out}')
    plt.close(fig)


def make_scatter(df: pd.DataFrame) -> None:
    df = paper_rows(df)
    languages = sorted(df['language'].unique())
    n = len(languages)
    ncols = 5
    nrows = int(np.ceil(n / ncols))
    fig, axes = plt.subplots(nrows, ncols, figsize=(17, 7.5), sharex=True, sharey=False)
    axes = np.array(axes).reshape(-1)

    zone_colors = {
        'collapse': '#d73027',
        'mixed': '#fdae61',
        'high': '#1a9850',
    }
    for ax, lang in zip(axes, languages):
        sub = df[df['language'] == lang].dropna(subset=['wer_pct', 'sfr_mean'])
        if sub.empty:
            ax.set_title(lang)
            continue
        point_colors = [
            zone_colors['collapse'] if v < 10 else
            zone_colors['mixed'] if v <= 90 else
            zone_colors['high']
            for v in sub['sfr_mean']
        ]
        ax.scatter(sub['sfr_mean'], sub['wer_pct'], color=point_colors,
                   s=55, zorder=5, edgecolor='black', linewidth=0.25)
        ax.axvline(10, color=zone_colors['collapse'], linestyle='--', linewidth=1)
        ax.axvline(90, color=zone_colors['high'], linestyle='--', linewidth=1)
        ax.set_xlabel('Script Fidelity (%)')
        ax.set_ylabel('WER (%)')
        ax.set_title(lang.capitalize())
        ax.set_xlim(-5, 105)

    for ax in axes[n:]:
        ax.axis('off')

    handles = [
        plt.Line2D([0], [0], marker='o', color='w', label='SFR < 10%',
                   markerfacecolor=zone_colors['collapse'], markeredgecolor='black', markersize=7),
        plt.Line2D([0], [0], marker='o', color='w', label='10-90%',
                   markerfacecolor=zone_colors['mixed'], markeredgecolor='black', markersize=7),
        plt.Line2D([0], [0], marker='o', color='w', label='> 90%',
                   markerfacecolor=zone_colors['high'], markeredgecolor='black', markersize=7),
    ]
    fig.legend(handles=handles, loc='lower center', ncol=3, frameon=False)
    plt.suptitle('WER vs Script Fidelity - FLEURS test sets', y=0.98)
    plt.tight_layout(rect=(0, 0.05, 1, 0.95))

    for ext in ('pdf', 'png'):
        out = FIGURES_DIR / f'wer_vs_sfr_scatter.{ext}'
        fig.savefig(out, bbox_inches='tight', dpi=150)
        print(f'Saved: {out}')
    plt.close(fig)


def make_georgian_detail(df: pd.DataFrame) -> None:
    df = paper_rows(df)
    sub = df[df['language'] == 'georgian'].dropna(subset=['wer_pct', 'sfr_mean']).copy()
    if sub.empty:
        return

    order = [
        'openai/whisper-tiny',
        'openai/whisper-base',
        'openai/whisper-small',
        'openai/whisper-medium',
        'openai/whisper-large-v2',
        'openai/whisper-large-v3',
        'openai/whisper-large-v3-turbo',
        'facebook/mms-1b-all',
        'facebook/seamless-m4t-v2-large',
        'unsloth/gemma-4-E2B-it',
    ]
    labels = {
        'openai/whisper-tiny': 'Whisper tiny',
        'openai/whisper-base': 'Whisper base',
        'openai/whisper-small': 'Whisper small',
        'openai/whisper-medium': 'Whisper medium',
        'openai/whisper-large-v2': 'Whisper large-v2',
        'openai/whisper-large-v3': 'Whisper large-v3',
        'openai/whisper-large-v3-turbo': 'Whisper turbo',
        'facebook/mms-1b-all': 'MMS-1B',
        'facebook/seamless-m4t-v2-large': 'SeamlessM4T-v2',
        'unsloth/gemma-4-E2B-it': 'Gemma 4 E2B',
    }
    sub['model'] = pd.Categorical(sub['model'], categories=order, ordered=True)
    sub = sub.sort_values('model')
    names = [labels[str(m)] for m in sub['model']]
    colors = [
        '#d73027' if v < 10 else '#fdae61' if v <= 90 else '#1a9850'
        for v in sub['sfr_mean']
    ]

    fig, ax1 = plt.subplots(figsize=(11, 4.8))
    x = np.arange(len(sub))
    ax1.bar(x, sub['sfr_mean'], color=colors, edgecolor='black', linewidth=0.4)
    ax1.axhline(10, color='#b2182b', linestyle='--', linewidth=1)
    ax1.axhline(90, color='#2166ac', linestyle='--', linewidth=1)
    ax1.set_ylim(0, 105)
    ax1.set_ylabel('Script Fidelity Rate (%)')
    ax1.set_xticks(x)
    ax1.set_xticklabels(names, rotation=35, ha='right')

    ax2 = ax1.twinx()
    ax2.plot(x, sub['wer_pct'], color='black', marker='o', linewidth=1.5)
    ax2.set_ylabel('WER (%)')
    ax2.set_ylim(0, max(420, float(sub['wer_pct'].max()) * 1.1))

    ax1.set_title('Georgian SFR and WER by model')
    fig.tight_layout()

    for ext in ('pdf', 'png'):
        out = FIGURES_DIR / f'georgian_collapse_detail.{ext}'
        fig.savefig(out, bbox_inches='tight', dpi=150)
        print(f'Saved: {out}')
    plt.close(fig)


def print_summary(df: pd.DataFrame) -> None:
    df = paper_rows(df)
    pivot = df.pivot_table(
        index='model', columns='language', values='sfr_mean', aggfunc='first')
    print('\n=== SF% summary ===')
    print(pivot.round(1).to_string())

    # Collapse pairs: SFR < 10%
    collapse = df[df['sfr_mean'] < 10][['model', 'language', 'sfr_mean', 'wer_pct']]
    print(f'\n=== Collapse pairs (SFR < 10%): {len(collapse)} ===')
    print(collapse.sort_values('sfr_mean').to_string(index=False))


if __name__ == '__main__':
    merged = merge()
    make_heatmap(merged)
    make_scatter(merged)
    make_georgian_detail(merged)
    print_summary(merged)