File size: 20,482 Bytes
df1dc5e
8554104
 
 
df1dc5e
 
 
 
 
 
8554104
df1dc5e
8554104
 
 
 
05438cf
 
 
 
8554104
05438cf
 
5fed9c7
 
 
df1dc5e
7bd9d87
 
df1dc5e
8554104
5fed9c7
7bd9d87
8554104
7bd9d87
8554104
 
df1dc5e
8554104
 
250635e
df1dc5e
5fed9c7
 
 
3bc94bc
 
 
 
 
 
 
 
 
 
 
8554104
df1dc5e
 
 
 
 
5fed9c7
df1dc5e
5fed9c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8554104
05438cf
8554104
f0021ab
8554104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bc94bc
8554104
 
3bc94bc
 
 
 
8554104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df1dc5e
 
 
8554104
 
df1dc5e
8554104
05438cf
df1dc5e
 
 
 
 
 
 
 
 
 
8554104
df1dc5e
8554104
 
 
df1dc5e
85a9e79
8554104
df1dc5e
 
 
 
7bd9d87
df1dc5e
 
5fed9c7
df1dc5e
7bd9d87
5fed9c7
 
 
 
 
 
 
8554104
 
5fed9c7
 
 
 
f50ee69
5fed9c7
 
 
 
 
 
 
8554104
 
5fed9c7
8554104
 
 
5fed9c7
8554104
 
5fed9c7
 
7bd9d87
5fed9c7
 
 
 
 
 
7bd9d87
5fed9c7
8554104
5fed9c7
 
 
 
 
 
 
 
 
 
df1dc5e
 
8554104
df1dc5e
8554104
 
 
5fed9c7
 
 
 
 
 
 
 
 
 
 
 
 
df1dc5e
 
8554104
5fed9c7
 
 
 
 
 
 
 
 
 
 
 
8554104
 
 
 
 
 
 
5fed9c7
8554104
 
 
 
5fed9c7
8554104
 
 
 
 
 
 
 
 
 
 
 
 
 
df1dc5e
 
 
8e2f769
df1dc5e
 
8554104
df1dc5e
 
8554104
df1dc5e
 
 
 
 
8554104
df1dc5e
 
 
 
 
 
 
8554104
df1dc5e
 
 
 
8554104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df1dc5e
8554104
df1dc5e
a72fa95
05438cf
8e2f769
df1dc5e
8554104
 
 
df1dc5e
8554104
df1dc5e
 
8554104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05438cf
df1dc5e
 
 
 
 
 
8554104
7bd9d87
 
0d12b5d
df1dc5e
 
 
 
 
 
 
8554104
 
 
 
 
 
 
 
0d12b5d
8554104
df1dc5e
 
b1901c7
 
 
 
 
 
0d12b5d
b1901c7
 
 
 
 
 
 
 
 
 
 
 
 
df1dc5e
8e2f769
3bc94bc
8554104
 
 
df1dc5e
8554104
df1dc5e
 
 
8554104
da096ac
8e2f769
 
8554104
 
 
 
 
85a9e79
8554104
 
 
 
 
 
df1dc5e
8554104
 
 
df1dc5e
8554104
8e2f769
 
 
8554104
 
 
 
 
 
 
 
 
 
 
 
 
8e2f769
8554104
df1dc5e
8554104
 
 
 
 
 
 
 
 
 
 
 
8e2f769
5fed9c7
1ada6a4
 
 
 
5fed9c7
8554104
 
 
5fed9c7
 
8554104
05438cf
8554104
61d6302
5fed9c7
 
 
 
8554104
 
85a9e79
 
 
 
8554104
 
 
0d12b5d
df1dc5e
7bd9d87
0d12b5d
df1dc5e
05438cf
df1dc5e
 
 
8554104
 
 
 
 
df1dc5e
 
5fed9c7
8e2f769
 
8554104
6eb9e63
8554104
df1dc5e
05438cf
8554104
5fed9c7
 
8554104
df1dc5e
5fed9c7
df1dc5e
 
8554104
5fed9c7
df1dc5e
b1901c7
 
6eb9e63
08a2468
df1dc5e
 
7bd9d87
 
df1dc5e
6eb9e63
8554104
05438cf
8554104
6eb9e63
8554104
df1dc5e
7bd9d87
df1dc5e
 
 
5fed9c7
fd3a49e
 
 
 
 
 
 
8554104
df1dc5e
5fed9c7
d468f7c
 
7bd9d87
 
b1901c7
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
# app.py
# Hugging Face Spaces–ready Gradio app (FULL)
#
# Features
# - Student submission JSON:
#   {
#     "andrewid": "zwu",
#     "1": "Answer 1",
#     "2": "Answer 2; Answer 3"
#   }
# - Gold data loaded from HF dataset (private):
#   swzwan/ANLP_S26_Assignment2_leaderboard_qa_gold
#   NOTE: dataset contains ONLY (id, question, answer). No retrieved-doc context.
# - Evaluations include:
#     (a) Token metrics: Answer Recall, Exact Match, F1 (SQuAD-style)
#     (b) ROUGE (rouge1/rouge2/rougeL)
#     (c) LLM-as-judge score (1-5) using OpenAI rubric (NO rationale returned)
# - Total score: uniform mean over normalized sub-metrics (0..1)
#     total = mean([EM, F1, Recall, ROUGE_avg, Judge_norm])
#   Missing components (e.g., judge disabled) are excluded from the mean.
# - Leaderboard update policy:
#     attempts always increase; reject if attempts >= 10
#     best score is kept: overwrite stored scores only if total_score improves
#
# IMPORTANT: Leaderboard persistence is via a *separate HF dataset repo* (Option A).
# This avoids HF Spaces ephemeral filesystem resets.

import json
import os
import re
import string
import tempfile
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple

import gradio as gr
import pandas as pd
import datasets

from rouge_score import rouge_scorer
from openai import OpenAI

from huggingface_hub import HfApi, hf_hub_download
from huggingface_hub.utils import HfHubHTTPError

import nltk
from nltk.corpus import stopwords

# Download stopwords if not already present
try:
    nltk.data.find('corpora/stopwords')
except LookupError:
    nltk.download('stopwords', quiet=True)

STOP_WORDS = set(stopwords.words('english'))


# =========================
# Config
# =========================
MAX_ATTEMPTS = 10

# Gold dataset (read)
GOLD_DATASET_NAME = "swzwan/ANLP_S26_Assignment2_leaderboard_qa_gold"
HF_ACCESS_TOKEN = os.getenv("HF_ACCESS_TOKEN")  # token that can read the private gold dataset

# Leaderboard dataset (read+write)
# Create this dataset repo once, e.g.:
#   swzwan/ANLP_S26_Assignment2_leaderboard_state
# and add an initial file leaderboard.json with {"attempts": {}, "entries": {}}
LEADERBOARD_REPO_ID = os.getenv(
    "LEADERBOARD_REPO_ID",
    "swzwan/ANLP_S26_Assignment2_leaderboard_state",
)
LEADERBOARD_FILENAME = os.getenv("LEADERBOARD_FILENAME", "leaderboard.json")
LEADERBOARD_REPO_TYPE = "dataset"

# Token for leaderboard repo. Needs write permission.
# Recommended: set a *separate* secret HF_LEADERBOARD_TOKEN with write access.
HF_LEADERBOARD_TOKEN = os.getenv("HF_LEADERBOARD_TOKEN") or os.getenv("HF_ACCESS_TOKEN")

# OpenAI judge (optional)
OPENAI_API_KEY = os.getenv("OPENAI_API")
JUDGE_MODEL = os.getenv("OPENAI_MODEL", "gpt-4.1-mini")


# =========================
# Helpers
# =========================

def _now_iso() -> str:
    return datetime.now().isoformat()


def _clamp01(x: float) -> float:
    return 0.0 if x < 0.0 else (1.0 if x > 1.0 else x)


def normalize_text(s: str) -> str:
    """SQuAD-style normalization with NLTK stop words."""
    s = str(s).lower()
    s = "".join(ch for ch in s if ch not in string.punctuation)
    # Remove NLTK English stop words
    tokens = s.split()
    tokens = [t for t in tokens if t not in STOP_WORDS]
    s = " ".join(tokens)
    return s


def tokenize(s: str) -> List[str]:
    return normalize_text(s).split()


def multiset_overlap_count(a_tokens: List[str], b_tokens: List[str]) -> int:
    counts: Dict[str, int] = {}
    for t in a_tokens:
        counts[t] = counts.get(t, 0) + 1
    overlap = 0
    for t in b_tokens:
        if counts.get(t, 0) > 0:
            overlap += 1
            counts[t] -= 1
    return overlap


def exact_match(pred: str, gold: str) -> int:
    return int(normalize_text(pred) == normalize_text(gold))


def token_f1(pred: str, gold: str) -> float:
    pt = tokenize(pred)
    gt = tokenize(gold)
    if len(pt) == 0 and len(gt) == 0:
        return 1.0
    if len(pt) == 0 or len(gt) == 0:
        return 0.0
    overlap = multiset_overlap_count(pt, gt)
    if overlap == 0:
        return 0.0
    precision = overlap / len(pt)
    recall = overlap / len(gt)
    return (2 * precision * recall) / (precision + recall)


def answer_recall(pred: str, gold: str) -> float:
    pt = tokenize(pred)
    gt = tokenize(gold)
    if len(gt) == 0:
        return 1.0 if len(pt) == 0 else 0.0
    if len(pt) == 0:
        return 0.0
    overlap = multiset_overlap_count(pt, gt)
    return overlap / len(gt)


def compute_rouge(pred: str, gold: str) -> Dict[str, float]:
    scorer = rouge_scorer.RougeScorer(["rouge1", "rouge2", "rougeL"], use_stemmer=True)
    scores = scorer.score(gold, pred)
    return {
        "rouge1": float(scores["rouge1"].fmeasure),
        "rouge2": float(scores["rouge2"].fmeasure),
        "rougeL": float(scores["rougeL"].fmeasure),
    }


# =========================
# Gold loading (HF datasets)
# =========================
_GOLD_CACHE: Optional[Dict[str, Dict[str, Any]]] = None


def load_gold_map() -> Dict[str, Dict[str, Any]]:
    """Returns: { qid: {"question": str, "gold_answer": str} }"""
    global _GOLD_CACHE
    if _GOLD_CACHE is not None:
        return _GOLD_CACHE

    if not HF_ACCESS_TOKEN:
        raise RuntimeError("HF_ACCESS_TOKEN is not set.")

    ds = datasets.load_dataset(GOLD_DATASET_NAME, token=HF_ACCESS_TOKEN)
    split = "test" if "test" in ds else ("validation" if "validation" in ds else "train")

    gold: Dict[str, Dict[str, Any]] = {}
    for ex in ds[split]:
        qid = str(ex.get("id", ex.get("qid", ""))).strip()
        if not qid:
            continue
        gold[qid] = {
            "question": str(ex.get("question", ex.get("query", ""))).strip(),
            "gold_answer": str(ex.get("answer", ex.get("gold", ex.get("reference", "")))).strip(),
        }

    _GOLD_CACHE = gold
    return gold


# =========================
# Leaderboard storage (HF dataset repo)
# =========================

_api = HfApi(token=HF_LEADERBOARD_TOKEN) if HF_LEADERBOARD_TOKEN else None


def _empty_lb() -> Dict[str, Any]:
    return {"attempts": {}, "entries": {}}


def load_leaderboard() -> Dict[str, Any]:
    """Schema: {"attempts": {id:int}, "entries": {id: entry}}"""
    if not HF_LEADERBOARD_TOKEN:
        # Read-only fallback: try anonymous read; if private, this will fail and we return empty.
        pass

    try:
        path = hf_hub_download(
            repo_id=LEADERBOARD_REPO_ID,
            filename=LEADERBOARD_FILENAME,
            repo_type=LEADERBOARD_REPO_TYPE,
            token=HF_LEADERBOARD_TOKEN,
        )
        with open(path, "r", encoding="utf-8") as f:
            obj = json.load(f)
        if not isinstance(obj, dict):
            return _empty_lb()
        obj.setdefault("attempts", {})
        obj.setdefault("entries", {})
        if not isinstance(obj["attempts"], dict) or not isinstance(obj["entries"], dict):
            return _empty_lb()
        return obj
    except Exception:
        return _empty_lb()


def save_leaderboard(obj: Dict[str, Any], commit_message: str = "Update leaderboard") -> None:
    """Atomically overwrite leaderboard.json in the dataset repo."""
    if _api is None:
        raise RuntimeError(
            "HF_LEADERBOARD_TOKEN is not set (needs write access to leaderboard dataset)."
        )

    with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".json", encoding="utf-8") as f:
        json.dump(obj, f, indent=2, ensure_ascii=False)
        tmp_path = f.name

    _api.upload_file(
        path_or_fileobj=tmp_path,
        path_in_repo=LEADERBOARD_FILENAME,
        repo_id=LEADERBOARD_REPO_ID,
        repo_type=LEADERBOARD_REPO_TYPE,
        commit_message=commit_message,
        token=HF_LEADERBOARD_TOKEN,
    )


def get_leaderboard_display() -> pd.DataFrame:
    lb = load_leaderboard()
    entries = lb.get("entries", {})

    if not entries:
        return pd.DataFrame(
            columns=[
                "Rank",
                "AndrewID",
                "Attempts Used",
                "Total (%)",
                "F1 (%)",
                "Recall (%)",
                "ROUGE (%)",
                "LLM Judge (1-5)",
                "Timestamp",
            ]
        )

    rows = []
    for andrewid, e in entries.items():
        rows.append(
            {
                "AndrewID": andrewid,
                "Attempts Used": int(lb.get("attempts", {}).get(andrewid, 0)),
                "Total (%)": f"{float(e.get('total_score', 0.0)) * 100:.2f}%",
                "F1 (%)": f"{float(e.get('f1', 0.0)) * 100:.2f}%",
                "Recall (%)": f"{float(e.get('recall', 0.0)) * 100:.2f}%",
                "ROUGE (%)": f"{float(e.get('rouge_avg', 0.0)) * 100:.2f}%",
                "LLM Judge (1-5)": "" if e.get("judge") is None else f"{float(e['judge']):.3f}",
                "Timestamp": str(e.get("timestamp", ""))[:19].replace("T", " "),
            }
        )

    def sort_key(r):
        def pct(x):
            try:
                return float(str(x).replace("%", ""))
            except Exception:
                return 0.0

        try:
            judge = float(r.get("LLM Judge (1-5)") or 0.0)
        except Exception:
            judge = 0.0

        return (
            pct(r.get("Total (%)", "0")),
            pct(r.get("F1 (%)", "0")),
            pct(r.get("Recall (%)", "0")),
            judge,
        )

    rows_sorted = sorted(rows, key=sort_key, reverse=True)
    for i, r in enumerate(rows_sorted, 1):
        r["Rank"] = i

    df = pd.DataFrame(rows_sorted)
    cols = ["Rank"] + [c for c in df.columns if c != "Rank"]
    return df[cols]


# =========================
# Student submission parsing
# =========================

def parse_submission_json(text: str) -> Tuple[str, Dict[str, str]]:
    obj = json.loads(text)
    if "andrewid" not in obj:
        raise ValueError("Missing 'andrewid' in submission.")

    andrewid = str(obj["andrewid"]).strip()
    if not andrewid:
        raise ValueError("'andrewid' cannot be empty.")

    answers: Dict[str, str] = {}
    for k, v in obj.items():
        if k == "andrewid":
            continue
        if str(k).isdigit():
            answers[str(k)] = str(v).strip()

    if not answers:
        raise ValueError("No answers found (expected numeric keys).")

    return andrewid, answers


# =========================
# LLM-as-judge (OpenAI) 1-5 rubric (NO rationale)
# =========================
JUDGE_RUBRIC = {
    "criteria": "Is the response factually accurate and directly addressing the query?",
    "score1_description": "The response contains major factual errors or is completely unrelated to the query.",
    "score2_description": "The response has some factual errors or partially misses the query intent.",
    "score3_description": "The response is mostly factually correct with occasional minor errors and generally addresses the query.",
    "score4_description": "The response is factually accurate with minimal errors and clearly addresses the query.",
    "score5_description": "The response is completely factually accurate and comprehensively addresses all aspects of the query.",
}

JUDGE_SYSTEM = (
    "You are an evaluator. Assign an integer score from 1 to 5 using the rubric. "
    "Return JSON ONLY: {\"score\": 1..5}"
)


def openai_judge(question: str, answer: str) -> Optional[int]:
    if not OPENAI_API_KEY:
        return None

    client = OpenAI(api_key=OPENAI_API_KEY, base_url="https://ai-gateway.andrew.cmu.edu/v1")
    payload = {"rubric": JUDGE_RUBRIC, "question": question, "response": answer}

    resp = client.responses.create(
        model=JUDGE_MODEL,
        instructions=JUDGE_SYSTEM,
        input=json.dumps(payload, ensure_ascii=False),
        temperature=0,
        max_output_tokens=40,
    )

    text = (resp.output_text or "").strip()
    try:
        obj = json.loads(text)
    except Exception:
        m = re.search(r"\{.*\}", text, flags=re.DOTALL)
        if not m:
            return None
        obj = json.loads(m.group(0))

    try:
        score = int(obj.get("score"))
    except Exception:
        return None

    if score < 1 or score > 5:
        return None
    return score


# =========================
# Total score (uniform mean)
# =========================

def compute_total_score(
    f1: float,
    recall: float,
    rouge_avg: float,
    judge_score: Optional[float],
) -> float:
    parts: List[float] = []
    parts.append(_clamp01(f1))
    parts.append(_clamp01(recall))
    parts.append(_clamp01(rouge_avg))

    # judge in [1,5] -> [0,1]
    if judge_score is not None:
        parts.append(_clamp01((float(judge_score) - 1.0) / 4.0))

    return sum(parts) / len(parts) if parts else 0.0


# =========================
# Submission processing
# =========================

def process_submission(file):
    try:
        if file is None:
            return "❌ Please upload a submission JSON file.", get_leaderboard_display()

        path = file if isinstance(file, str) else file.name
        with open(path, "r", encoding="utf-8") as f:
            content = f.read()

        andrewid, user_answers = parse_submission_json(content)

        lb = load_leaderboard()
        attempts_map: Dict[str, int] = lb.get("attempts", {})
        entries_map: Dict[str, Any] = lb.get("entries", {})

        used = int(attempts_map.get(andrewid, 0))
        if used >= MAX_ATTEMPTS:
            return (
                f"❌ Submission rejected: {andrewid} has already used {used}/{MAX_ATTEMPTS} attempts.",
                get_leaderboard_display(),
            )

        gold_map = load_gold_map()
        
        # Validate that submission has the same number of entries as gold
        if len(user_answers) != len(gold_map):
            return (
                f"❌ Submission rejected: Expected {len(gold_map)} answers, but got {len(user_answers)}. "
                f"Your submission must contain answers for all questions in the gold dataset.",
                get_leaderboard_display(),
            )
        
        # Validate that all question IDs in submission exist in gold
        missing_qids = set(gold_map.keys()) - set(user_answers.keys())
        extra_qids = set(user_answers.keys()) - set(gold_map.keys())
        
        if missing_qids or extra_qids:
            error_msg = "❌ Submission rejected: Question ID mismatch.\n"
            if missing_qids:
                error_msg += f"Missing question IDs: {sorted(missing_qids)}\n"
            if extra_qids:
                error_msg += f"Extra/invalid question IDs: {sorted(extra_qids)}\n"
            return error_msg, get_leaderboard_display()

        attempted = 0
        f1_sum = rec_sum = 0.0
        rouge1_sum = rouge2_sum = rougeL_sum = 0.0
        judge_sum = 0
        judge_n = 0

        for qid, pred in user_answers.items():
            if qid not in gold_map:
                continue

            pred = str(pred).strip()
            
            attempted += 1
            gold = gold_map[qid]["gold_answer"]
            question = gold_map[qid]["question"]

            f1 = token_f1(pred, gold)
            rec = answer_recall(pred, gold)
            rouge = compute_rouge(pred, gold)
            judge = openai_judge(question, pred)

            f1_sum += f1
            rec_sum += rec
            rouge1_sum += rouge["rouge1"]
            rouge2_sum += rouge["rouge2"]
            rougeL_sum += rouge["rougeL"]

            if judge is not None:
                judge_sum += int(judge)
                judge_n += 1

        denom = attempted if attempted > 0 else 1

        avg_f1 = f1_sum / denom
        avg_rec = rec_sum / denom
        avg_rouge1 = rouge1_sum / denom
        avg_rouge2 = rouge2_sum / denom
        avg_rougeL = rougeL_sum / denom
        avg_rouge = (avg_rouge1 + avg_rouge2 + avg_rougeL) / 3.0

        avg_judge = (judge_sum / judge_n) if judge_n > 0 else None

        total_score = compute_total_score(
            f1=avg_f1,
            recall=avg_rec,
            rouge_avg=avg_rouge,
            judge_score=avg_judge,
        )

        entry = {
            "andrewid": andrewid,
            "attempt": used + 1,
            "timestamp": _now_iso(),
            "f1": round(avg_f1, 6),
            "recall": round(avg_rec, 6),
            "rouge1": round(avg_rouge1, 6),
            "rouge2": round(avg_rouge2, 6),
            "rougeL": round(avg_rougeL, 6),
            "rouge_avg": round(avg_rouge, 6),
            "judge": None if avg_judge is None else round(float(avg_judge), 6),
            "total_score": round(float(total_score), 6),
            "judge_model": JUDGE_MODEL if avg_judge is not None else None,
        }

        # best-score-wins
        prev_entry = entries_map.get(andrewid)
        if prev_entry is None or float(total_score) > float(prev_entry.get("total_score", -1.0)):
            entries_map[andrewid] = entry

        # attempts always increment
        attempts_map[andrewid] = used + 1
        lb["entries"] = entries_map
        lb["attempts"] = attempts_map

        save_leaderboard(lb, commit_message=f"Update leaderboard: {andrewid} attempt {used + 1}")

        # concise status
        lines = [
            f"βœ… Submission {andrewid} (attempt #{used + 1}/{MAX_ATTEMPTS}).",
            f"Total score: {total_score:.4f} ({total_score * 100:.2f}%)",
            f"F1:          {avg_f1:.4f} ({avg_f1 * 100:.2f}%)",
            f"Recall:      {avg_rec:.4f} ({avg_rec * 100:.2f}%)",
            f"ROUGE(avg):  {avg_rouge:.4f} ({avg_rouge * 100:.2f}%)",
        ]
        if avg_judge is None:
            if not OPENAI_API_KEY:
                lines.append("LLM judge:    NA (set OPENAI_API to enable)")
            else:
                lines.append("LLM judge:    NA (questions not available in gold dataset)")
        else:
            lines.append(f"LLM judge:    {avg_judge:.3f} (1-5)")

        return "\n".join(lines), get_leaderboard_display()

    except Exception as e:
        return f"❌ Error: {e}", get_leaderboard_display()


# =========================
# UI
# =========================

def sample_submission_text():
    return json.dumps({"andrewid": "user123", "1": "Paris", "2": "Answer A"}, indent=2)


with gr.Blocks(title="Leaderboard QA Judge", theme=gr.themes.Soft()) as app:
    gr.Markdown(
        f"""
# πŸ† Assignment 2 Public Leaderboard

We compute multiple metrics:
- **Standard metrics:** Answer Recall, F1, and ROUGE-1/2/L (reported as an average)
- **LLM-as-judge:** rubric-based score (1–5)

**Total score** is the uniform mean of the available normalized metrics (0–1).

**Attempts:** up to **{MAX_ATTEMPTS}**. Attempts always increase. Your leaderboard score updates only if your **total score improves**.

**Submission format (JSON):**
```json
{{
  "andrewid": "YOUR_ANDREWID",
  "1": "Answer 1",
  "2": "Answer 2"
}}
```

**Important:** Your submission must include answers for ALL questions in the dataset. The number of answers must exactly match the number of questions in the gold dataset.

**Please don't refresh or redirect the page during evaluation. It may take some time to finish.**
"""
    )

    with gr.Tabs():
        with gr.Tab("πŸ“€ Submit"):
            file_input = gr.File(label="Upload submission in json", file_types=[".json"])
            submit_btn = gr.Button("πŸš€ Submit & Evaluate", variant="primary")
            status = gr.Textbox(label="Result", lines=10, interactive=False)

            gr.Markdown("### Sample submission")
            sample = gr.Textbox(value=sample_submission_text(), lines=6)

        with gr.Tab("πŸ… Leaderboard"):
            leaderboard_df = gr.Dataframe(value=get_leaderboard_display(), interactive=False)
            refresh_btn = gr.Button("πŸ”„ Refresh")

    # Keep the leaderboard static during evaluation; update it only after scoring finishes.
    def process_and_return_status(file):
        status_text, _ = process_submission(file)
        return status_text
    
    submit_btn.click(fn=process_and_return_status, inputs=[file_input], outputs=[status]).then(
        fn=get_leaderboard_display, outputs=[leaderboard_df]
    )
    refresh_btn.click(fn=get_leaderboard_display, outputs=[leaderboard_df])

    # Ensure leaderboard loads from HF dataset for every new browser session / hard refresh.
    app.load(fn=get_leaderboard_display, outputs=[leaderboard_df])


if __name__ == "__main__":
    app.launch(share=True)