File size: 10,062 Bytes
6b40934
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24abcf7
 
6b40934
 
 
 
c0fa15d
6b40934
 
24abcf7
6b40934
 
 
 
 
34884b9
 
 
24abcf7
34884b9
 
 
6b40934
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0fa15d
6b40934
 
 
 
 
 
 
 
 
 
 
 
 
c0fa15d
24abcf7
 
 
34884b9
 
24abcf7
c0fa15d
 
 
 
 
24abcf7
34884b9
24abcf7
34884b9
 
24abcf7
c0fa15d
 
 
 
 
6b40934
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
eval_gemini.py
==============
Evaluate Gemini models on GomParam-v1 via the Gemini API.
Since APIs do not expose raw log-probabilities, this script uses
a generation-based prompt where the model is asked to output the
index (0, 1, 2, or 3) of the correct answer.

Usage:
  export GEMINI_API_KEY="your_api_key_here"
  python scripts/eval_gemini.py \
    --model gemini-2.5-flash \
    --data_dir data/ \
    --output_dir results/gemini/

Output:
  results/gemini/predictions.csv   — per-item predictions
  results/gemini/summary.json      — per-module and global accuracy
"""

import argparse
import csv
import json
import os
import re
import time
from pathlib import Path

# pip install google-genai
from google import genai
from google.genai import types

def load_dataset(data_dir: Path):
    items = []
    for f in sorted(data_dir.glob("*.json")):
        module = f.stem
        with open(f, encoding="utf-8") as fp:
            data = json.load(fp)
        for it in data:
            it["module"] = module
            items.append(it)
    return items

def build_prompt(item: dict) -> str:
    """Constructs a strict prompt asking for just the integer index."""
    context = item.get("context", "") or item.get("sentence", "") or item.get("passage", "") or ""
    question = item.get("question", "") or ""
    candidates = item.get("candidates", [])
    
    prompt = "You are an expert in Goan Konkani linguistics and culture.\n\n"
    if context:
        prompt += f"Context: {context}\n"
    if question:
        prompt += f"Question: {question}\n\n"
    else:
        prompt += "Complete the sentence or identify the correct relation:\n\n"
        
    prompt += "Options:\n"
    for i, c in enumerate(candidates):
        prompt += f"[{i}] {c}\n"
        
    prompt += "\nOutput ONLY the integer index (0, 1, 2, or 3) of the correct option. Do not provide any explanation."
    return prompt

def extract_prediction(text: str) -> int:
    """Extracts the first number from the model's response."""
    match = re.search(r'\d+', text)
    if match:
        pred = int(match.group())
        if pred in [0, 1, 2, 3]:
            return pred
    return -1 # Invalid prediction

# Module weights (same as standard eval)
MODULE_WEIGHTS = {
    "morphology":0.15, "cloze":0.12, "para_qa":0.10, "idioms_proverbs":0.08,
    "pragmatics":0.08, "cultural_grounding":0.07, "homograph_disambiguation":0.07,
    "entailment":0.06, "coreference":0.06, "register_discrimination":0.05,
    "sentiment":0.04, "spatio_temporal":0.04, "kinship":0.04,
    "numerical_reasoning":0.03, "medical":0.03, "coherence":0.03,
    "cross_scripting":0.02, "code_switching":0.02, "dialect":0.02, "perplexity":0.02,
}
_total_w = sum(MODULE_WEIGHTS.values())
MODULE_WEIGHTS = {k: v / _total_w for k, v in MODULE_WEIGHTS.items()}

def main():
    parser = argparse.ArgumentParser(description="Evaluate Gemini on GomParam-v1")
    parser.add_argument("--model", default="gemini-3.1-flash-lite",
                        help="Gemini model ID (e.g., gemini-3.1-flash-lite, gemini-flash-lite-latest)")
    parser.add_argument("--api_key", default=os.getenv("GEMINI_API_KEY", ""),
                        help="Gemini API Key. Can also use GEMINI_API_KEY env var.")
    parser.add_argument("--data_dir", default="data/", help="Path to GomParam-v1 data directory")
    parser.add_argument("--output_dir", default="results/gemini/", help="Path to save results")
    parser.add_argument("--delay", type=float, default=4.0, help="Delay between API calls to avoid rate limits (4s = 15 RPM)")
    args = parser.parse_args()

    # API Key check bypassed since we are using hardcoded API_KEYS list

    out_dir = Path(args.output_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    data_dir = Path(args.data_dir)

    api_key = os.getenv("GEMINI_API_KEY")
    if not api_key:
        print("ERROR: GEMINI_API_KEY environment variable is not set!")
        return
        
    print(f"Initializing Gemini Client with model: {args.model}")
    client = genai.Client(api_key=api_key)
    
    # Configure generation to be as strict as possible
    config = types.GenerateContentConfig(
        temperature=0.0,
        max_output_tokens=5, # We only want a single integer
    )

    items = load_dataset(data_dir)
    print(f"Loaded {len(items)} items from {data_dir}")

    rows = []
    module_stats = {}
    
    # Check if resuming from previous run
    csv_path = out_dir / "predictions.csv"
    processed_ids = set()
    if csv_path.exists():
        print(f"Resuming from existing predictions at {csv_path}")
        with open(csv_path, "r", encoding="utf-8") as f:
            reader = csv.DictReader(f)
            for row in reader:
                processed_ids.add(row["id"])
                
                # Rebuild module stats from existing data
                mod = row["module"]
                if mod not in module_stats:
                    module_stats[mod] = {"correct": 0, "total": 0}
                module_stats[mod]["total"] += 1
                module_stats[mod]["correct"] += int(row["predicted_correct"])
                rows.append(row)

    print(f"Starting evaluation... (Skipping {len(processed_ids)} already processed items)")
    
    # Open CSV in append mode if resuming, write mode if starting fresh
    mode = "a" if processed_ids else "w"
    with open(csv_path, mode, newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=["id", "module", "correct", "predicted", "predicted_correct", "raw_response"])
        if not processed_ids:
            writer.writeheader()
            
        for i, item in enumerate(items):
            item_id = item.get("id", f"item_{i}")
            if item_id in processed_ids:
                continue
                
            mod = item["module"]
            gold = int(item["correct"])
            prompt = build_prompt(item)
            
            # API Call with basic retry logic
            max_retries = 5
            pred = -1
            raw_text = ""
            for attempt in range(max_retries):
                try:
                    response = client.models.generate_content(
                        model=args.model,
                        contents=prompt,
                        config=config
                    )
                    raw_text = response.text.strip()
                    pred = extract_prediction(raw_text)
                    break
                except Exception as e:
                    error_msg = str(e)
                    
                    # Handle API Key Invalid or Expired
                    if "API_KEY_INVALID" in error_msg or "expired" in error_msg:
                        print(f"  API Key is INVALID or EXPIRED. Exiting.")
                        return

                    if "429" in error_msg or "RESOURCE_EXHAUSTED" in error_msg:
                        wait_time = 35.0
                        m = re.search(r"retry in (\d+\.?\d*)s", error_msg)
                        if m:
                            wait_time = float(m.group(1)) + 2.0
                            
                        # If daily limit hit, exit
                        if "GenerateRequestsPerDay" in error_msg or wait_time > 60.0:
                            print(f"  Hit Daily Quota. Exiting.")
                            return
                            
                        print(f"  Rate limited on {item_id}. Waiting {wait_time:.1f}s (Attempt {attempt+1}/{max_retries})")
                        time.sleep(wait_time)
                    else:
                        print(f"  API Error on {item_id} (Attempt {attempt+1}/{max_retries}): {e}")
                        time.sleep(5 * (attempt + 1))
            
            is_correct = int(pred == gold)
            
            row = {
                "id": item_id,
                "module": mod,
                "correct": gold,
                "predicted": pred,
                "predicted_correct": is_correct,
                "raw_response": raw_text.replace("\n", " ")
            }
            writer.writerow(row)
            f.flush() # Force write to disk to prevent data loss
            
            if mod not in module_stats:
                module_stats[mod] = {"correct": 0, "total": 0}
            module_stats[mod]["correct"] += is_correct
            module_stats[mod]["total"] += 1
            
            if (i + 1) % 10 == 0:
                print(f"  Processed {i+1}/{len(items)} items. Last pred: {pred} (Gold: {gold})")
                
            time.sleep(args.delay) # Rate limit protection

    print("\nEvaluation Complete! Calculating metrics...")
    
    # Calculate global and module accuracies
    comp_score = 0.0
    comp_weight = 0.0
    
    summary = {
        "model": args.model,
        "total_items": sum(s["total"] for s in module_stats.values()),
        "per_module": {}
    }
    
    print(f"\n{'='*60}")
    print(f"Gemini API Results: {args.model}")
    print(f"{'='*60}")
    
    for mod in sorted(module_stats.keys()):
        st = module_stats[mod]
        acc = st["correct"] / st["total"] if st["total"] > 0 else 0.0
        summary["per_module"][mod] = {
            "accuracy": round(acc, 4),
            "correct": st["correct"],
            "total": st["total"]
        }
        
        if mod in MODULE_WEIGHTS:
            comp_score += acc * MODULE_WEIGHTS[mod]
            comp_weight += MODULE_WEIGHTS[mod]
            
        print(f"  {mod:35s}  {acc*100:5.1f}%  ({st['correct']}/{st['total']})")

    final_comp = comp_score / comp_weight if comp_weight > 0 else 0.0
    summary["composite_accuracy"] = round(final_comp, 4)
    
    print(f"{'-'*60}")
    print(f"  Composite Accuracy:                  {final_comp*100:5.1f}%")
    print(f"{'='*60}")
    
    summary_path = out_dir / "gemini_summary.json"
    with open(summary_path, "w", encoding="utf-8") as f:
        json.dump(summary, f, indent=2)
        
    print(f"Saved summary to {summary_path}")

if __name__ == "__main__":
    main()