File size: 4,321 Bytes
b5ab17a f41ad2d b5ab17a | 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 | import argparse
import json
import re
from collections import defaultdict
from pathlib import Path
def read_jsonl(path):
with Path(path).open(encoding="utf-8") as handle:
return [json.loads(line) for line in handle if line.strip()]
def tokens(text):
return re.findall(r"[a-z0-9çğıöşü]+", str(text).lower())
def token_f1(prediction, reference):
pred = tokens(prediction)
ref = tokens(reference)
if not pred or not ref:
return float(pred == ref)
pred_counts = defaultdict(int)
ref_counts = defaultdict(int)
for token in pred:
pred_counts[token] += 1
for token in ref:
ref_counts[token] += 1
overlap = sum(min(count, ref_counts[token]) for token, count in pred_counts.items())
if overlap == 0:
return 0.0
precision = overlap / len(pred)
recall = overlap / len(ref)
return 2 * precision * recall / (precision + recall)
def section(text, name, following):
end = "|".join(re.escape(item) for item in following)
pattern = rf"{re.escape(name)}\s*:\s*(.*?)(?=(?:{end})\s*:|$)"
match = re.search(pattern, text, flags=re.IGNORECASE | re.DOTALL)
return match.group(1).strip() if match else ""
def score_one(response, reference):
rationale = section(response, "Gerekçe", ["Karar", "Öneriler"])
decision = section(response, "Karar", ["Öneriler"])
recommendations = section(response, "Öneriler", [])
expected_recommendations = " ".join(reference["expected_recommendations"])
format_score = sum(
bool(re.search(rf"{heading}\s*:", response, re.IGNORECASE))
for heading in ("Gerekçe", "Karar", "Öneriler")
) / 3
return {
"rationale_f1": token_f1(rationale, reference["reasoning_summary"]),
"decision_f1": token_f1(decision, reference["expected_decision"]),
"recommendations_f1": token_f1(recommendations, expected_recommendations),
"format_score": format_score,
}
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--predictions", required=True)
parser.add_argument("--reference", default="benchmark/reference.jsonl")
parser.add_argument("--questions", default="benchmark/questions.jsonl")
parser.add_argument("--output", required=True)
args = parser.parse_args()
predictions = {row["id"]: row for row in read_jsonl(args.predictions)}
references = {row["id"]: row for row in read_jsonl(args.reference)}
questions = {row["id"]: row for row in read_jsonl(args.questions)}
details = []
for uid, reference in references.items():
prediction = predictions.get(uid, {})
response = prediction.get("response", "")
metrics = score_one(response, reference)
total = 100 * (
0.30 * metrics["rationale_f1"]
+ 0.40 * metrics["decision_f1"]
+ 0.20 * metrics["recommendations_f1"]
+ 0.10 * metrics["format_score"]
)
details.append({
"id": uid,
"category": questions[uid]["category"],
"difficulty": questions[uid]["difficulty"],
"manual": questions[uid]["manual"],
"score": total,
**metrics,
"error": prediction.get("error") or ("missing_prediction" if uid not in predictions else None),
})
by_category = defaultdict(list)
for row in details:
by_category[row["category"]].append(row["score"])
report = {
"num_questions": len(details),
"num_predictions": len(predictions),
"overall_score": sum(row["score"] for row in details) / len(details),
"manual_subset_score": sum(row["score"] for row in details if row["manual"]) / sum(row["manual"] for row in details),
"category_scores": {
key: sum(values) / len(values)
for key, values in sorted(by_category.items())
},
"errors": sum(row["error"] is not None for row in details),
"details": details,
}
output = Path(args.output)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps({key: value for key, value in report.items() if key != "details"}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
|