File size: 3,345 Bytes
34e0a18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import json
import sys
from collections import defaultdict
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
GOLD_PATH = ROOT / "data" / "annotated.jsonl"
VALID_LABELS = {"A", "B", "C", "D"}


def load_jsonl(path: Path) -> list[dict]:
    records: list[dict] = []
    with path.open(encoding="utf-8") as handle:
        for line_number, line in enumerate(handle, start=1):
            if not line.strip():
                continue
            try:
                records.append(json.loads(line))
            except json.JSONDecodeError as exc:
                raise ValueError(
                    f"Satır {line_number}: geçersiz JSON: {exc}"
                ) from exc
    return records


def load_predictions(path: Path) -> dict[str, str]:
    predictions: dict[str, str] = {}
    for line_number, record in enumerate(load_jsonl(path), start=1):
        item_id = record.get("id")
        prediction = record.get("prediction")
        if not isinstance(item_id, str) or not item_id:
            raise ValueError(f"Satır {line_number}: geçerli id gerekli")
        if item_id in predictions:
            raise ValueError(f"Satır {line_number}: yinelenen id {item_id}")
        if not isinstance(prediction, str):
            prediction = ""
        predictions[item_id] = prediction.strip()
    return predictions


def percent(correct: int, total: int) -> str:
    return f"{(100 * correct / total):.2f}%" if total else "n/a"


def main() -> int:
    if len(sys.argv) != 2:
        print("Kullanım: python scripts/evaluate.py predictions.jsonl")
        return 2

    items = load_jsonl(GOLD_PATH)
    predictions = load_predictions(Path(sys.argv[1]))
    known_ids = {item["id"] for item in items}
    unknown = sorted(set(predictions) - known_ids)
    if unknown:
        print(f"Uyarı: {len(unknown)} bilinmeyen id yok sayıldı: {unknown[:5]}")

    totals = defaultdict(int)
    corrects = defaultdict(int)
    invalid = 0
    missing = 0

    for item in items:
        prediction = predictions.get(item["id"])
        if prediction is None:
            missing += 1
            prediction = ""
        elif prediction not in VALID_LABELS:
            invalid += 1

        dimensions = (
            ("overall", "all"),
            ("family", item["family"]),
            ("task_type", item["task_type"]),
            ("difficulty", item["difficulty"]),
        )
        for dimension, value in dimensions:
            key = f"{dimension}:{value}"
            totals[key] += 1
            if prediction == item["answer"]:
                corrects[key] += 1

    overall_key = "overall:all"
    print(
        f"Overall: {corrects[overall_key]}/{totals[overall_key]} "
        f"({percent(corrects[overall_key], totals[overall_key])})"
    )
    print(f"Missing: {missing}")
    print(f"Invalid format: {invalid}")

    for dimension in ("family", "task_type", "difficulty"):
        print(f"\n{dimension}:")
        keys = sorted(key for key in totals if key.startswith(f"{dimension}:"))
        for key in keys:
            value = key.split(":", 1)[1]
            print(
                f"  {value}: {corrects[key]}/{totals[key]} "
                f"({percent(corrects[key], totals[key])})"
            )
    return 0


if __name__ == "__main__":
    sys.exit(main())