| 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 | from __future__ import annotations |
| 27 | |
| 28 | import argparse |
| 29 | import json |
| 30 | import random |
| 31 | import sys |
| 32 | from collections import defaultdict |
| 33 | from pathlib import Path |
| 34 | from typing import Any |
| 35 | |
| 36 | REPO = Path(__file__).resolve().parents[1] |
| 37 | sys.path.insert(0, str(REPO / "service")) |
| 38 | |
| 39 | from src.compute import segments as seg |
| 40 | from src.compute.recommend import ( |
| 41 | STUDENT_SEGMENT_DIMENSIONS, |
| 42 | for_class_segments, |
| 43 | for_student_segments, |
| 44 | ) |
| 45 | from src.segment.runner import load_answers |
| 46 | |
| 47 | NOW_MS = 1_776_000_000_000 |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | GOLD_DELTA = -0.5 |
| 54 | |
| 55 | |
| 56 | GREY_DELTA = -0.15 |
| 57 | |
| 58 | |
| 59 | |
| 60 | MEASURED_LABEL_ACCURACY = { |
| 61 | "okuma_yuku": 0.983, |
| 62 | "dikkat_tuzagi": 0.975, |
| 63 | "bilissel_talep": 0.917, |
| 64 | } |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | |
| 72 | def load_gold_labels(path: Path) -> dict[str, dict[str, str]]: |
| 73 | data = json.loads(path.read_text(encoding="utf-8")) |
| 74 | items = data["items"] if isinstance(data, dict) else data |
| 75 | out: dict[str, dict[str, str]] = {} |
| 76 | for item in items: |
| 77 | dims = (item.get("gold") or {}).get("dims") or {} |
| 78 | if not dims: |
| 79 | continue |
| 80 | out[item["question_id"]] = { |
| 81 | d: dims[d] for d in seg.PRODUCTION_DIMENSIONS if d in dims |
| 82 | } |
| 83 | return out |
| 84 | |
| 85 | |
| 86 | def load_keys(path: Path) -> dict[str, str | None]: |
| 87 | data = json.loads(path.read_text(encoding="utf-8")) |
| 88 | items = data["items"] if isinstance(data, dict) else data |
| 89 | return {i["question_id"]: i.get("correct_choice_id") for i in items} |
| 90 | |
| 91 | |
| 92 | def load_students(path: Path) -> dict[str, dict[str, Any]]: |
| 93 | data = json.loads(path.read_text(encoding="utf-8")) |
| 94 | return {s["user"]: s for s in data.get("students", [])} |
| 95 | |
| 96 | |
| 97 | def perturb( |
| 98 | labels: dict[str, dict[str, str]], seed: int |
| 99 | ) -> dict[str, dict[str, str]]: |
| 100 | |
| 101 | |
| 102 | |
| 103 | |
| 104 | |
| 105 | |
| 106 | |
| 107 | rng = random.Random(seed) |
| 108 | order = ("hatirlama", "uygulama", "analiz") |
| 109 | out: dict[str, dict[str, str]] = {} |
| 110 | for question, row in labels.items(): |
| 111 | new: dict[str, str] = {} |
| 112 | for dimension, label in row.items(): |
| 113 | accuracy = MEASURED_LABEL_ACCURACY.get(dimension, 1.0) |
| 114 | if rng.random() < accuracy: |
| 115 | new[dimension] = label |
| 116 | continue |
| 117 | if dimension == "bilissel_talep": |
| 118 | idx = min(order.index(label) + 1, len(order) - 1) |
| 119 | new[dimension] = order[idx] |
| 120 | else: |
| 121 | options = [ |
| 122 | x for x in seg.PRODUCTION_DIMENSIONS[dimension] if x != label |
| 123 | ] |
| 124 | new[dimension] = rng.choice(options) |
| 125 | out[question] = new |
| 126 | return out |
| 127 | |
| 128 | |
| 129 | |
| 130 | |
| 131 | |
| 132 | |
| 133 | |
| 134 | def build_profiles( |
| 135 | answers: list[tuple[str, str, str | None]], |
| 136 | labels: dict[str, dict[str, str]], |
| 137 | keys: dict[str, str | None], |
| 138 | school: str, |
| 139 | ) -> dict[str, list]: |
| 140 | by_student: dict[str, list[tuple[str, int]]] = defaultdict(list) |
| 141 | for question, student, selected in answers: |
| 142 | if selected is None: |
| 143 | continue |
| 144 | key = keys.get(question) |
| 145 | if not key or question not in labels: |
| 146 | continue |
| 147 | by_student[student].append((question, 1 if selected == key else 0)) |
| 148 | return { |
| 149 | student: seg.student_profiles(school, student, rows, labels, NOW_MS) |
| 150 | for student, rows in by_student.items() |
| 151 | } |
| 152 | |
| 153 | |
| 154 | def gold_targets(student: dict[str, Any]) -> tuple[set[tuple[str, str]], set[tuple[str, str]]]: |
| 155 | |
| 156 | positives: set[tuple[str, str]] = set() |
| 157 | grey: set[tuple[str, str]] = set() |
| 158 | for dimension, labels in (student.get("dim_delta") or {}).items(): |
| 159 | for label, delta in labels.items(): |
| 160 | if delta <= GOLD_DELTA: |
| 161 | positives.add((dimension, label)) |
| 162 | elif delta <= GREY_DELTA: |
| 163 | grey.add((dimension, label)) |
| 164 | return positives, grey |
| 165 | |
| 166 | |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | def calibrate( |
| 173 | profiles: dict[str, list], students: dict[str, dict[str, Any]], reference |
| 174 | ) -> dict[str, Any]: |
| 175 | |
| 176 | control = [ |
| 177 | uid for uid, s in students.items() if not (s.get("dim_delta") or {}) |
| 178 | ] |
| 179 | buckets: dict[str, list[float]] = defaultdict(list) |
| 180 | n_values: dict[str, list[int]] = defaultdict(list) |
| 181 | for uid in control: |
| 182 | for profile in profiles.get(uid, []): |
| 183 | rel = seg.relative_contrast(profile, reference) |
| 184 | if rel is None: |
| 185 | continue |
| 186 | key = f"{profile.dimension}={profile.label}" |
| 187 | buckets[key].append(rel) |
| 188 | n_values[key].append(profile.n_answers) |
| 189 | |
| 190 | out: dict[str, Any] = {"kontrol_ogrenci": len(control), "segmentler": {}} |
| 191 | for key, values in sorted(buckets.items()): |
| 192 | mean = sum(values) / len(values) |
| 193 | sd = seg._sd(values, mean) |
| 194 | out["segmentler"][key] = { |
| 195 | "n_ogrenci": len(values), |
| 196 | "ortalama_goreli_kontrast": round(mean, 4), |
| 197 | "sd": round(sd, 4), |
| 198 | "en_dusuk": round(min(values), 4), |
| 199 | "mean_eksi_3sd": round(mean - 3 * sd, 4), |
| 200 | "segment_basina_cevap_medyani": sorted(n_values[key])[ |
| 201 | len(n_values[key]) // 2 |
| 202 | ], |
| 203 | } |
| 204 | return out |
| 205 | |
| 206 | |
| 207 | def gate_sweep( |
| 208 | profiles: dict[str, list], |
| 209 | students: dict[str, dict[str, Any]], |
| 210 | reference, |
| 211 | n_candidates: tuple[int, ...], |
| 212 | ) -> list[dict[str, Any]]: |
| 213 | |
| 214 | rows: list[dict[str, Any]] = [] |
| 215 | for min_n in n_candidates: |
| 216 | false_positive = 0 |
| 217 | fired_control = 0 |
| 218 | for uid, student in students.items(): |
| 219 | if student.get("dim_delta"): |
| 220 | continue |
| 221 | for profile in profiles.get(uid, []): |
| 222 | if profile.n_answers < min_n: |
| 223 | continue |
| 224 | rel = seg.relative_contrast(profile, reference) |
| 225 | gate = seg.RELATIVE_CONTRAST_GATE.get(profile.dimension) |
| 226 | if rel is None or gate is None: |
| 227 | continue |
| 228 | if rel <= gate: |
| 229 | false_positive += 1 |
| 230 | fired_control += 1 |
| 231 | rows.append( |
| 232 | { |
| 233 | "min_cevap": min_n, |
| 234 | "kontrol_yanlis_pozitif_satir": false_positive, |
| 235 | "kontrol_ateslenen": fired_control, |
| 236 | } |
| 237 | ) |
| 238 | return rows |
| 239 | |
| 240 | |
| 241 | |
| 242 | |
| 243 | |
| 244 | |
| 245 | |
| 246 | def evaluate( |
| 247 | profiles: dict[str, list], |
| 248 | students: dict[str, dict[str, Any]], |
| 249 | reference, |
| 250 | school: str, |
| 251 | ) -> dict[str, Any]: |
| 252 | |
| 253 | fired: dict[str, set[tuple[str, str]]] = defaultdict(set) |
| 254 | rule_of: dict[tuple[str, str], str] = {} |
| 255 | evidence_missing = 0 |
| 256 | produced = 0 |
| 257 | |
| 258 | for uid, rows in profiles.items(): |
| 259 | payload = seg.profile_payload(rows, reference) |
| 260 | recs = for_student_segments(school, uid, payload, NOW_MS) |
| 261 | for rec in recs: |
| 262 | produced += 1 |
| 263 | payload_evidence = { |
| 264 | k: v for k, v in rec.evidence.items() if k != "limitation" |
| 265 | } |
| 266 | if not payload_evidence: |
| 267 | evidence_missing += 1 |
| 268 | dimension = rec.evidence["dimension"] |
| 269 | label = rec.evidence["label"] |
| 270 | fired[uid].add((dimension, label)) |
| 271 | rule_of[(dimension, label)] = rec.rule_id |
| 272 | |
| 273 | |
| 274 | targets = { |
| 275 | "A8 (ezberci)": ("bilissel_talep", "analiz"), |
| 276 | "A4 (aceleci)": ("dikkat_tuzagi", "var"), |
| 277 | "A7 (okuma guclugu)": ("okuma_yuku", "yuksek"), |
| 278 | } |
| 279 | per_target: dict[str, Any] = {} |
| 280 | for name, target in targets.items(): |
| 281 | tp = fp = fn = 0 |
| 282 | grey_hits = 0 |
| 283 | for uid, student in students.items(): |
| 284 | positives, grey = gold_targets(student) |
| 285 | hit = target in fired.get(uid, set()) |
| 286 | if target in positives: |
| 287 | tp += int(hit) |
| 288 | fn += int(not hit) |
| 289 | elif target in grey: |
| 290 | grey_hits += int(hit) |
| 291 | elif hit: |
| 292 | fp += 1 |
| 293 | precision = tp / (tp + fp) if (tp + fp) else None |
| 294 | recall = tp / (tp + fn) if (tp + fn) else None |
| 295 | f1 = ( |
| 296 | 2 * precision * recall / (precision + recall) |
| 297 | if precision and recall |
| 298 | else None |
| 299 | ) |
| 300 | per_target[name] = { |
| 301 | "segment": f"{target[0]}={target[1]}", |
| 302 | "kural": rule_of.get(target, "-"), |
| 303 | "altin_pozitif_ogrenci": tp + fn, |
| 304 | "dogru_pozitif": tp, |
| 305 | "yanlis_pozitif": fp, |
| 306 | "yanlis_negatif": fn, |
| 307 | "gri_bolge_ateslenen": grey_hits, |
| 308 | "kesinlik": None if precision is None else round(precision, 4), |
| 309 | "duyarlilik": None if recall is None else round(recall, 4), |
| 310 | "f1": None if f1 is None else round(f1, 4), |
| 311 | } |
| 312 | |
| 313 | |
| 314 | control_students = [ |
| 315 | uid for uid, s in students.items() if not (s.get("dim_delta") or {}) |
| 316 | ] |
| 317 | control_fp_rows = 0 |
| 318 | control_fp_students = 0 |
| 319 | control_detail: dict[str, int] = defaultdict(int) |
| 320 | for uid in control_students: |
| 321 | hits = fired.get(uid, set()) |
| 322 | if hits: |
| 323 | control_fp_students += 1 |
| 324 | control_fp_rows += len(hits) |
| 325 | for dimension, label in hits: |
| 326 | control_detail[f"{dimension}={label}"] += 1 |
| 327 | |
| 328 | return { |
| 329 | "uretilen_tavsiye": produced, |
| 330 | "kanitsiz_tavsiye": evidence_missing, |
| 331 | "arketipler": per_target, |
| 332 | "kontrol_grubu": { |
| 333 | "ogrenci": len(control_students), |
| 334 | "yanlis_pozitif_ogrenci": control_fp_students, |
| 335 | "yanlis_pozitif_satir": control_fp_rows, |
| 336 | "segment_dagilimi": dict(sorted(control_detail.items())), |
| 337 | }, |
| 338 | } |
| 339 | |
| 340 | |
| 341 | def evaluate_class_rule( |
| 342 | profiles: dict[str, list], |
| 343 | students: dict[str, dict[str, Any]], |
| 344 | reference, |
| 345 | school: str, |
| 346 | ) -> dict[str, Any]: |
| 347 | |
| 348 | by_class: dict[str, list] = defaultdict(list) |
| 349 | for uid, rows in profiles.items(): |
| 350 | class_id = (students.get(uid) or {}).get("class") |
| 351 | if class_id: |
| 352 | by_class[class_id].extend(rows) |
| 353 | class_stats = seg.class_contrasts(by_class, reference) |
| 354 | |
| 355 | fired: dict[str, list[str]] = {} |
| 356 | total = 0 |
| 357 | for class_id, dims in sorted(class_stats.items()): |
| 358 | recs = for_class_segments( |
| 359 | school, |
| 360 | class_id, |
| 361 | class_segments=dims, |
| 362 | class_teachers=["ogretmen-ornek"], |
| 363 | now_ms=NOW_MS, |
| 364 | ) |
| 365 | total += len(recs) |
| 366 | if recs: |
| 367 | fired[class_id] = [ |
| 368 | f"{r.evidence['dimension']}={r.evidence['label']} " |
| 369 | f"({r.evidence['mean_relative_contrast']}, " |
| 370 | f"n={r.evidence['n_students']})" |
| 371 | for r in recs |
| 372 | ] |
| 373 | |
| 374 | |
| 375 | |
| 376 | |
| 377 | |
| 378 | |
| 379 | synthetic = [ |
| 380 | p |
| 381 | for uid, rows in profiles.items() |
| 382 | if (students.get(uid) or {}).get("archetype") == "A8" |
| 383 | for p in rows |
| 384 | ] |
| 385 | synth_stats = seg.class_contrasts({"YAPAY-A8": synthetic}, reference) |
| 386 | synth_recs = for_class_segments( |
| 387 | school, |
| 388 | "YAPAY-A8", |
| 389 | class_segments=synth_stats.get("YAPAY-A8", {}), |
| 390 | class_teachers=["ogretmen-ornek"], |
| 391 | now_ms=NOW_MS, |
| 392 | ) |
| 393 | |
| 394 | return { |
| 395 | "sinif": len(class_stats), |
| 396 | "uretilen_tavsiye": total, |
| 397 | "ateslenen_siniflar": fired, |
| 398 | "pozitif_kontrol": { |
| 399 | "aciklama": ( |
| 400 | "Yapay sinif: tum A8 (ezberci) ogrenciler tek sinifta. Kural " |
| 401 | "ATESLEMELI; ateslemezse kural olu demektir." |
| 402 | ), |
| 403 | "uretilen_tavsiye": len(synth_recs), |
| 404 | "maddeler": [ |
| 405 | f"{r.evidence['dimension']}={r.evidence['label']} " |
| 406 | f"({r.evidence['mean_relative_contrast']}, " |
| 407 | f"n={r.evidence['n_students']})" |
| 408 | for r in synth_recs |
| 409 | ], |
| 410 | }, |
| 411 | "sinif_ozeti": { |
| 412 | class_id: { |
| 413 | f"{d}={lab}": row["mean_relative_contrast"] |
| 414 | for d, labels in dims.items() |
| 415 | for lab, row in labels.items() |
| 416 | } |
| 417 | for class_id, dims in sorted(class_stats.items()) |
| 418 | }, |
| 419 | } |
| 420 | |
| 421 | |
| 422 | |
| 423 | |
| 424 | |
| 425 | def main(argv: list[str] | None = None) -> int: |
| 426 | parser = argparse.ArgumentParser(description=__doc__) |
| 427 | parser.add_argument("--items", default=str(REPO / "work" / "items_enriched.json")) |
| 428 | parser.add_argument( |
| 429 | "--manifest", default=str(REPO / "seed" / "_seed_manifest.json") |
| 430 | ) |
| 431 | parser.add_argument( |
| 432 | "--answers", default=str(REPO / "seed" / "11_exam_answer.surql") |
| 433 | ) |
| 434 | parser.add_argument("--json", default=None, help="raporu bu dosyaya yaz") |
| 435 | parser.add_argument( |
| 436 | "--noise", |
| 437 | action="store_true", |
| 438 | help="olculmus LLM hata oranlarini altin etiketlere uygula (MODELLEME)", |
| 439 | ) |
| 440 | parser.add_argument("--seed", type=int, default=20260915) |
| 441 | args = parser.parse_args(argv) |
| 442 | |
| 443 | items_path = Path(args.items) |
| 444 | labels = load_gold_labels(items_path) |
| 445 | keys = load_keys(items_path) |
| 446 | students = load_students(Path(args.manifest)) |
| 447 | answers = load_answers(Path(args.answers)) |
| 448 | manifest = json.loads(Path(args.manifest).read_text(encoding="utf-8")) |
| 449 | school = manifest.get("school_slug") or "okul" |
| 450 | |
| 451 | if args.noise: |
| 452 | labels = perturb(labels, args.seed) |
| 453 | |
| 454 | profiles = build_profiles(answers, labels, keys, school) |
| 455 | flat = [p for rows in profiles.values() for p in rows] |
| 456 | reference = seg.reference_contrasts(flat) |
| 457 | |
| 458 | report: dict[str, Any] = { |
| 459 | "kip": "MODELLENMIS ETIKET GURULTUSU" if args.noise else "ALTIN ETIKET", |
| 460 | "ne_olculuyor": ( |
| 461 | "Kurallar dogru calisiyor mu (etiketler dogruyken arketipleri " |
| 462 | "buluyor mu). LLM'in dogru etiketleyip etiketlemedigi OLCULMEZ." |
| 463 | ), |
| 464 | "veri": { |
| 465 | "etiketli_soru": len(labels), |
| 466 | "cevap_satiri": len(answers), |
| 467 | "ogrenci": len(profiles), |
| 468 | "profil_satiri": len(flat), |
| 469 | }, |
| 470 | "esikler": { |
| 471 | "min_cevap": seg.MIN_ANSWERS_PER_SEGMENT, |
| 472 | "goreli_kontrast_kapisi": seg.RELATIVE_CONTRAST_GATE, |
| 473 | "sinif_kapisi": seg.CLASS_RELATIVE_CONTRAST_GATE, |
| 474 | "min_sinif_ogrencisi": seg.MIN_CLASS_STUDENTS, |
| 475 | "bakilan_boyutlar": list(STUDENT_SEGMENT_DIMENSIONS), |
| 476 | }, |
| 477 | "referans_kontrastlar": reference, |
| 478 | "kalibrasyon": calibrate(profiles, students, reference), |
| 479 | "kapi_taramasi": gate_sweep( |
| 480 | profiles, students, reference, (30, 50, 75, 100, 125, 150, 200, 300) |
| 481 | ), |
| 482 | "kural_degerlendirmesi": evaluate(profiles, students, reference, school), |
| 483 | "sinif_kurali": evaluate_class_rule( |
| 484 | profiles, students, reference, school |
| 485 | ), |
| 486 | } |
| 487 | text = json.dumps(report, ensure_ascii=False, indent=2) |
| 488 | if args.json: |
| 489 | Path(args.json).write_text(text, encoding="utf-8") |
| 490 | print(f"yazildi: {args.json}", file=sys.stderr) |
| 491 | print(text) |
| 492 | return 0 |
| 493 | |
| 494 | |
| 495 | if __name__ == "__main__": |
| 496 | raise SystemExit(main()) |