File size: 6,058 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
#!/usr/bin/env python3
"""SFR plus language-identification analysis from saved Gemma predictions."""

from __future__ import annotations

import argparse
import json
import sys
from collections import Counter
from pathlib import Path


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

configure_runtime_cache(ROOT)

import pandas as pd
from langdetect import DetectorFactory, LangDetectException, detect

from script_fidelity import SCRIPT_CONFIGS, compute_sfr, dominant_script


DetectorFactory.seed = 42

LANGUAGES = [
    "pashto",
    "urdu",
    "arabic",
    "persian",
    "hindi",
    "bengali",
    "malayalam",
    "tamil",
    "somali",
    "georgian",
]

EXPECTED_LID = {
    "arabic": "ar",
    "bengali": "bn",
    "georgian": "ka",
    "hindi": "hi",
    "malayalam": "ml",
    "persian": "fa",
    "somali": "so",
    "tamil": "ta",
    "urdu": "ur",
}

VARIANTS = {
    "baseline": ("results_gemma4/predictions", "gemma4_{language}_predictions.json"),
    "script_hint": (
        "results_gemma4_prompt_mitigation/predictions",
        "gemma4_script_hint_{language}_predictions.json",
    ),
}


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Run SFR plus LID analysis over saved Gemma prediction JSONs."
    )
    parser.add_argument("--summary-csv", default=str(ROOT / "analysis" / "sfr_lid_hybrid_summary.csv"))
    parser.add_argument("--utterance-csv", default=str(ROOT / "analysis" / "sfr_lid_hybrid_utterances.csv"))
    parser.add_argument("--languages", nargs="+", default=LANGUAGES)
    return parser.parse_args()


def prediction_path(variant: str, language: str) -> Path:
    directory, template = VARIANTS[variant]
    return ROOT / directory / template.format(language=language)


def load_predictions(path: Path) -> tuple[list[str], list[str]]:
    with open(path, encoding="utf-8") as handle:
        data = json.load(handle)
    refs = data.get("references", [])
    preds = data.get("predictions", [])
    if not refs or not preds:
        raise ValueError(f"Missing references/predictions in {path}")
    return refs, preds


def lid_label(text: str) -> str:
    text = (text or "").strip()
    if not text:
        return "empty"
    try:
        return detect(text)
    except LangDetectException:
        return "unknown"


def utterance_rows(languages: list[str]) -> list[dict]:
    rows = []
    for language in languages:
        if language not in SCRIPT_CONFIGS:
            raise ValueError(f"Unknown language: {language}")
        expected_lid = EXPECTED_LID.get(language, "")
        for variant in VARIANTS:
            refs, preds = load_predictions(prediction_path(variant, language))
            for idx, (ref, pred) in enumerate(zip(refs, preds)):
                sfr = compute_sfr(pred, language)
                lid = lid_label(pred)
                dom = dominant_script(pred)
                rows.append(
                    {
                        "language": language,
                        "prompt_variant": variant,
                        "utterance_index": idx,
                        "sfr": None if sfr is None else round(sfr * 100, 2),
                        "dominant_script": dom,
                        "lid_label": lid,
                        "expected_lid_label": expected_lid,
                        "lid_matches_expected": bool(expected_lid and lid == expected_lid),
                        "is_low_sfr": bool(sfr is not None and sfr < 0.10),
                        "is_high_sfr": bool(sfr is not None and sfr >= 0.90),
                        "reference": ref,
                        "prediction": pred,
                    }
                )
    return rows


def top_labels(labels: pd.Series, k: int = 3) -> list[tuple[str, float]]:
    counts = Counter(labels.dropna().tolist())
    total = sum(counts.values()) or 1
    return [(label, round(count / total * 100, 1)) for label, count in counts.most_common(k)]


def summarize(df: pd.DataFrame) -> pd.DataFrame:
    rows = []
    for (language, variant), group in df.groupby(["language", "prompt_variant"], sort=False):
        tops = top_labels(group["lid_label"], 3)
        while len(tops) < 3:
            tops.append(("", 0.0))
        expected = EXPECTED_LID.get(language, "")
        low = group[group["is_low_sfr"]]
        high = group[group["is_high_sfr"]]
        rows.append(
            {
                "language": language,
                "prompt_variant": variant,
                "n": len(group),
                "mean_sfr": round(group["sfr"].dropna().mean(), 2),
                "low_sfr_pct": round(group["is_low_sfr"].mean() * 100, 1),
                "high_sfr_pct": round(group["is_high_sfr"].mean() * 100, 1),
                "expected_lid_label": expected,
                "lid_expected_pct": round(group["lid_matches_expected"].mean() * 100, 1)
                if expected else "",
                "low_sfr_expected_lid_pct": round(low["lid_matches_expected"].mean() * 100, 1)
                if expected and len(low) else "",
                "high_sfr_expected_lid_pct": round(high["lid_matches_expected"].mean() * 100, 1)
                if expected and len(high) else "",
                "top_lid_1": tops[0][0],
                "top_lid_1_pct": tops[0][1],
                "top_lid_2": tops[1][0],
                "top_lid_2_pct": tops[1][1],
                "top_lid_3": tops[2][0],
                "top_lid_3_pct": tops[2][1],
            }
        )
    return pd.DataFrame(rows)


def main() -> None:
    args = parse_args()
    rows = utterance_rows(args.languages)
    utterances = pd.DataFrame(rows)
    summary = summarize(utterances)

    Path(args.utterance_csv).parent.mkdir(parents=True, exist_ok=True)
    utterances.to_csv(args.utterance_csv, index=False)
    summary.to_csv(args.summary_csv, index=False)
    print(f"Wrote {args.summary_csv}")
    print(f"Wrote {args.utterance_csv}")


if __name__ == "__main__":
    main()