| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | from __future__ import annotations |
| 18 | |
| 19 | import json |
| 20 | import os |
| 21 | import re |
| 22 | import sys |
| 23 | |
| 24 | BASE = os.path.dirname(os.path.abspath(__file__)) |
| 25 | if BASE not in sys.path: |
| 26 | sys.path.insert(0, BASE) |
| 27 | |
| 28 | import config as C |
| 29 | import content_tr as TXT |
| 30 | |
| 31 | LANGLE = "⟨" |
| 32 | RANGLE = "⟩" |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | TOKEN = re.compile(r""" |
| 39 | (?P<record>[A-Za-z_][A-Za-z0-9_]*:⟨[^⟩]*⟩) |
| 40 | | (?P<string>'(?:\\.|[^'\\])*') |
| 41 | | (?P<dstring>"(?:\\.|[^"\\])*") |
| 42 | | (?P<number>-?\d+(?:\.\d+)?) |
| 43 | | (?P<none>\bNONE\b|\bNULL\b) |
| 44 | | (?P<bool>\btrue\b|\bfalse\b) |
| 45 | | (?P<punct>[\{\}\[\],:]) |
| 46 | | (?P<ident>[A-Za-z_][A-Za-z0-9_.*]*) |
| 47 | """, re.VERBOSE) |
| 48 | |
| 49 | |
| 50 | class Parser: |
| 51 | def __init__(self, text): |
| 52 | self.tokens = [m for m in TOKEN.finditer(text)] |
| 53 | self.i = 0 |
| 54 | |
| 55 | def peek(self): |
| 56 | return self.tokens[self.i] if self.i < len(self.tokens) else None |
| 57 | |
| 58 | def next(self): |
| 59 | m = self.tokens[self.i] |
| 60 | self.i += 1 |
| 61 | return m |
| 62 | |
| 63 | def value(self): |
| 64 | m = self.next() |
| 65 | kind = m.lastgroup |
| 66 | text = m.group() |
| 67 | if kind == "record": |
| 68 | table, key = text.split(":", 1) |
| 69 | return ("record", table, key[1:-1]) |
| 70 | if kind in ("string", "dstring"): |
| 71 | return _unescape(text[1:-1]) |
| 72 | if kind == "number": |
| 73 | return float(text) if "." in text else int(text) |
| 74 | if kind == "none": |
| 75 | return None |
| 76 | if kind == "bool": |
| 77 | return text == "true" |
| 78 | if kind == "punct" and text == "[": |
| 79 | out = [] |
| 80 | while True: |
| 81 | nxt = self.peek() |
| 82 | if nxt is None: |
| 83 | break |
| 84 | if nxt.group() == "]": |
| 85 | self.next() |
| 86 | break |
| 87 | if nxt.group() == ",": |
| 88 | self.next() |
| 89 | continue |
| 90 | out.append(self.value()) |
| 91 | return out |
| 92 | if kind == "punct" and text == "{": |
| 93 | return self.object_body() |
| 94 | raise ValueError("beklenmeyen belirteç: %r" % text) |
| 95 | |
| 96 | def object_body(self): |
| 97 | obj = {} |
| 98 | while True: |
| 99 | m = self.peek() |
| 100 | if m is None: |
| 101 | break |
| 102 | if m.group() == "}": |
| 103 | self.next() |
| 104 | break |
| 105 | if m.group() == ",": |
| 106 | self.next() |
| 107 | continue |
| 108 | key = self.next().group() |
| 109 | colon = self.next() |
| 110 | assert colon.group() == ":", colon.group() |
| 111 | obj[key] = self.value() |
| 112 | return obj |
| 113 | |
| 114 | |
| 115 | def _unescape(text): |
| 116 | return (text.replace("\\\\", "\x00").replace("\\'", "'").replace('\\"', '"') |
| 117 | .replace("\\n", "\n").replace("\\r", "\r").replace("\\t", "\t") |
| 118 | .replace("\x00", "\\")) |
| 119 | |
| 120 | |
| 121 | def parse_row(line): |
| 122 | p = Parser(line.strip().rstrip(",")) |
| 123 | first = p.next() |
| 124 | assert first.group() == "{", first.group() |
| 125 | return p.object_body() |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
| 130 | |
| 131 | |
| 132 | ENUM_FIELDS = { |
| 133 | ("user", "role"): ["parent", "student", "teacher", "manager", "admin"], |
| 134 | ("user", "theme"): ["light", "dark"], |
| 135 | ("user", "language"): ["tr", "en"], |
| 136 | ("message", "sender_folder"): ["sent", "archive", "trash"], |
| 137 | ("message", "recipient_folder"): ["inbox", "archive", "trash"], |
| 138 | ("message", "sender_origin"): ["sent", "inbox", "archive", "trash"], |
| 139 | ("message", "recipient_origin"): ["sent", "inbox", "archive", "trash"], |
| 140 | ("chatbot_message", "role"): ["user", "assistant"], |
| 141 | ("chatbot_message", "status"): ["pending", "complete", "failed"], |
| 142 | ("appointment", "status"): ["pending", "approved", "rejected", "cancelled"], |
| 143 | ("meal_booking", "status"): ["booked", "cancelled"], |
| 144 | ("meal_attendance", "status"): ["served", "missed"], |
| 145 | ("meal_ledger", "kind"): ["charge", "credit", "reversal"], |
| 146 | ("payment_ledger", "kind"): ["charge", "credit", "reversal", "refund"], |
| 147 | ("course", "kind"): ["course", "study", "club"], |
| 148 | ("exam", "mode"): ["sync", "async", "open"], |
| 149 | ("exam", "kind"): C.EXAM_KINDS, |
| 150 | ("exam_question", "kind"): ["choice", "text"], |
| 151 | ("bank_question", "kind"): ["choice", "text"], |
| 152 | ("bank_question", "visibility"): ["private", "school"], |
| 153 | ("homework_result", "status"): ["done", "incomplete", "missing"], |
| 154 | ("pool_question", "status"): ["pending", "approved"], |
| 155 | ("board_stroke", "kind"): ["stroke", "clear"], |
| 156 | ("attendance", "status"): ["present", "absent", "late", "excused"], |
| 157 | ("session_attendance", "status"): ["present", "absent", "late", "excused"], |
| 158 | ("menu", "slot"): C.MEAL_SLOTS, |
| 159 | ("question_image", "content_type"): ["image/png", "image/jpeg", "image/webp", |
| 160 | "image/gif"], |
| 161 | ("bank_question_image", "content_type"): ["image/png", "image/jpeg", "image/webp", |
| 162 | "image/gif"], |
| 163 | ("badge_award", "badge"): [b[0] for b in C.BADGES], |
| 164 | } |
| 165 | |
| 166 | |
| 167 | COUNTER_CHECKS = [ |
| 168 | ("course", "enrollment_count", "enrollment", "course", None), |
| 169 | ("subject", "exam_question_count", "exam_question", "subject", None), |
| 170 | ("subject", "homework_count", "homework", "subject", None), |
| 171 | ("exam", "result_count", "exam_result", "exam", None), |
| 172 | ("class_group", "class_member_count", "class_member", "class", None), |
| 173 | ("class_group", "class_course_count", "class_course", "class", None), |
| 174 | ("event", "registration_count", "registration", "event", None), |
| 175 | ("note", "file_count", "note_file", "note", None), |
| 176 | ("course_note", "file_count", "course_note_file", "course_note", None), |
| 177 | ("homework_submission", "file_count", "homework_file", "submission", None), |
| 178 | ("menu", "seats_booked", "meal_booking", "menu", ("status", "booked")), |
| 179 | ("fee_plan", "assignment_count", "fee_plan_assignment", "plan", None), |
| 180 | ("board", "total_stroke_count", "board_stroke", "board", None), |
| 181 | ("user", "board_count", "board", "creator", None), |
| 182 | ("user", "chatbot_thread_count", "chatbot_thread", "user_id", None), |
| 183 | ] |
| 184 | |
| 185 | MONEY_FIELDS = {("menu_dish", "price_minor"): C.MAX_DISH_PRICE_MINOR, |
| 186 | ("meal_booking", "price_minor"): C.MAX_LEDGER_AMOUNT_MINOR, |
| 187 | ("meal_ledger", "amount_minor"): C.MAX_LEDGER_AMOUNT_MINOR, |
| 188 | ("payment_ledger", "amount_minor"): C.MAX_LEDGER_AMOUNT_MINOR} |
| 189 | |
| 190 | |
| 191 | FLEXIBLE_FIELDS = {("rag_output", "payload")} |
| 192 | |
| 193 | |
| 194 | |
| 195 | ULID_TIME_FIELDS = { |
| 196 | "board": "created_at", "board_stroke": "created_at", "message": "sent_at", |
| 197 | "pool_question": "asked_at", "solution": "offered_at", |
| 198 | "chatbot_thread": "created_at", "chatbot_message": "created_at", |
| 199 | "homework": "created_at", "homework_file": "created_at", |
| 200 | "appointment": "created_at", "appointment_slot": "created_at", |
| 201 | "menu_dish": "created_at", "bank_question": "created_at", |
| 202 | "rag_output": "generated_at", "pomodoro_session": "started_at", |
| 203 | "course_session": "starts_at", |
| 204 | } |
| 205 | |
| 206 | CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" |
| 207 | |
| 208 | |
| 209 | def ulid_time(key): |
| 210 | value = 0 |
| 211 | for ch in key[:10]: |
| 212 | idx = CROCKFORD.find(ch) |
| 213 | if idx < 0: |
| 214 | return None |
| 215 | value = value * 32 + idx |
| 216 | return value |
| 217 | |
| 218 | |
| 219 | |
| 220 | |
| 221 | |
| 222 | |
| 223 | |
| 224 | |
| 225 | MIN_UNIQUE_CHOICE_TEXTS = 3000 |
| 226 | MAX_CHOICE_TEXT_SHARE = 0.02 |
| 227 | |
| 228 | |
| 229 | MIN_UNIQUE_QUESTION_STEMS = 2500 |
| 230 | |
| 231 | |
| 232 | |
| 233 | |
| 234 | MAX_SAME_EXAM_DUPLICATE_STEMS = 0 |
| 235 | |
| 236 | |
| 237 | MAX_ANSWER_TEXT_LEN = 400 |
| 238 | ANSWER_TEXT_ENDINGS = (".", "!", "?", ")", "\u2026") |
| 239 | |
| 240 | |
| 241 | |
| 242 | BACKSLASH_QUOTE = "\\'" |
| 243 | |
| 244 | |
| 245 | |
| 246 | MAX_TOPIC_MISMATCH_SHARE = 0.02 |
| 247 | |
| 248 | _SUBJECT_POOLS = TXT.SUBJECT_CONCEPTS |
| 249 | |
| 250 | _SUBJECT_NAMES_BY_LEN = sorted(_SUBJECT_POOLS, key=len, reverse=True) |
| 251 | _ALL_TOPIC_CONCEPTS = set() |
| 252 | for _pool in _SUBJECT_POOLS.values(): |
| 253 | _ALL_TOPIC_CONCEPTS.update(_pool) |
| 254 | |
| 255 | _UNIT_WORDS = {u for lst in TXT.UNITS.values() for u in lst} |
| 256 | _UNIT_WORDS |= {u for lst in TXT.SUBJECT_UNITS.values() for u in lst} |
| 257 | _ALL_TOPIC_CONCEPTS -= _UNIT_WORDS |
| 258 | |
| 259 | |
| 260 | |
| 261 | _CONCEPT_RE = {c: re.compile(r"(?<!\w)%s(?!\w)" % re.escape(c), re.IGNORECASE) |
| 262 | for c in _ALL_TOPIC_CONCEPTS} |
| 263 | |
| 264 | |
| 265 | def _has_concept(blob, concept): |
| 266 | return _CONCEPT_RE[concept].search(blob) is not None |
| 267 | |
| 268 | FUTURE_FORBIDDEN = [("course_session", "starts_at"), ("exam_answer", "updated_at"), |
| 269 | ("pomodoro_session", "started_at"), ("homework_submission", "submitted_at"), |
| 270 | ("exam_attempt", "started_at")] |
| 271 | |
| 272 | |
| 273 | class Checker: |
| 274 | def __init__(self, seed_dir, schema_path): |
| 275 | self.dir = seed_dir |
| 276 | with open(schema_path, "r", encoding="utf-8") as fh: |
| 277 | self.schema = json.load(fh) |
| 278 | with open(os.path.join(seed_dir, "MANIFEST.json"), "r", encoding="utf-8") as fh: |
| 279 | self.manifest = json.load(fh) |
| 280 | self.t_now = self.manifest["uretim"]["t_now_ms"] |
| 281 | self.errors = [] |
| 282 | self.warnings = [] |
| 283 | self.seen_ids = set() |
| 284 | self.counts = {} |
| 285 | self.counter_values = {} |
| 286 | self.ref_counts = {} |
| 287 | self.user_roles = {} |
| 288 | self.choice_texts = {} |
| 289 | self.stem_texts = {} |
| 290 | self.exam_stem_pairs = {} |
| 291 | self.answer_len_sum = 0 |
| 292 | self.answer_len_n = 0 |
| 293 | self.answer_len_max = 0 |
| 294 | self.answer_lens = [] |
| 295 | self.subject_names = {} |
| 296 | self.topic_checked = 0 |
| 297 | self.topic_violations = 0 |
| 298 | self.topic_examples = [] |
| 299 | self.topic_by_concept = {} |
| 300 | self.syntax_stats = {"dosya": 0, "tek_tirnakli": 0, "cift_tirnakli": 0, |
| 301 | "ters_bolu_tirnak": 0, "kacisli_cift_tirnak": 0} |
| 302 | |
| 303 | def fail(self, msg): |
| 304 | if len(self.errors) < 60: |
| 305 | self.errors.append(msg) |
| 306 | |
| 307 | |
| 308 | def run(self): |
| 309 | files = sorted(f for f in os.listdir(self.dir) |
| 310 | if f.endswith(".surql") and f[0].isdigit()) |
| 311 | for name in files: |
| 312 | |
| 313 | self.check_syntax(os.path.join(self.dir, name)) |
| 314 | for name in files: |
| 315 | if name.startswith("00_") or name.startswith("99_"): |
| 316 | continue |
| 317 | self.scan_file(os.path.join(self.dir, name)) |
| 318 | self.check_counters() |
| 319 | self.check_text_quality() |
| 320 | self.check_topic_match() |
| 321 | self.check_manifest_counts() |
| 322 | return self.errors |
| 323 | |
| 324 | |
| 325 | def check_syntax(self, path): |
| 326 | |
| 327 | |
| 328 | |
| 329 | |
| 330 | |
| 331 | fname = os.path.basename(path) |
| 332 | self.syntax_stats["dosya"] += 1 |
| 333 | depth_sq = 0 |
| 334 | depth_br = 0 |
| 335 | with open(path, "r", encoding="utf-8") as fh: |
| 336 | for lineno, line in enumerate(fh, 1): |
| 337 | if BACKSLASH_QUOTE in line: |
| 338 | self.fail("%s:%d ters bölülü tırnak kaçışı (\\') bulundu — " |
| 339 | "kaçış varsayıma bırakılmamalı" % (fname, lineno)) |
| 340 | self.syntax_stats["ters_bolu_tirnak"] += 1 |
| 341 | i = 0 |
| 342 | n = len(line) |
| 343 | in_str = None |
| 344 | while i < n: |
| 345 | ch = line[i] |
| 346 | if in_str is None: |
| 347 | if ch == "-" and line[i:i + 2] == "--": |
| 348 | break |
| 349 | if ch in ("'", '"'): |
| 350 | in_str = ch |
| 351 | self.syntax_stats["tek_tirnakli" if ch == "'" |
| 352 | else "cift_tirnakli"] += 1 |
| 353 | elif ch == "[": |
| 354 | depth_sq += 1 |
| 355 | elif ch == "]": |
| 356 | depth_sq -= 1 |
| 357 | elif ch == "{": |
| 358 | depth_br += 1 |
| 359 | elif ch == "}": |
| 360 | depth_br -= 1 |
| 361 | if depth_sq < 0 or depth_br < 0: |
| 362 | self.fail("%s:%d fazladan kapanış parantezi" % (fname, lineno)) |
| 363 | return |
| 364 | else: |
| 365 | if ch == "\\": |
| 366 | if in_str == '"' and line[i + 1:i + 2] == '"': |
| 367 | self.syntax_stats["kacisli_cift_tirnak"] += 1 |
| 368 | i += 2 |
| 369 | continue |
| 370 | if ch == in_str: |
| 371 | in_str = None |
| 372 | i += 1 |
| 373 | if in_str is not None: |
| 374 | self.fail("%s:%d satır sonunda kapanmamış dize (%s)" |
| 375 | % (fname, lineno, in_str)) |
| 376 | return |
| 377 | if depth_sq != 0 or depth_br != 0: |
| 378 | self.fail("%s: dosya sonunda dengesiz parantez ([]=%d, {}=%d)" |
| 379 | % (fname, depth_sq, depth_br)) |
| 380 | |
| 381 | def scan_file(self, path): |
| 382 | table = None |
| 383 | fields = None |
| 384 | with open(path, "r", encoding="utf-8") as fh: |
| 385 | for lineno, line in enumerate(fh, 1): |
| 386 | stripped = line.strip() |
| 387 | if stripped.startswith("INSERT INTO "): |
| 388 | table = stripped[len("INSERT INTO "):].split()[0] |
| 389 | if (table not in self.schema["tables"] |
| 390 | and table not in self.schema["control_tables"]): |
| 391 | self.fail("%s: bilinmeyen tablo %s" % (os.path.basename(path), table)) |
| 392 | fields = {} |
| 393 | else: |
| 394 | fields = self.schema["tables"].get(table) or \ |
| 395 | self.schema["control_tables"][table] |
| 396 | fields = fields["fields"] |
| 397 | continue |
| 398 | if not stripped.startswith("{"): |
| 399 | continue |
| 400 | try: |
| 401 | row = parse_row(stripped) |
| 402 | except Exception as exc: |
| 403 | self.fail("%s:%d ayrıştırma hatası: %s" % (path, lineno, exc)) |
| 404 | continue |
| 405 | self.check_row(os.path.basename(path), lineno, table, fields, row) |
| 406 | |
| 407 | def check_row(self, fname, lineno, table, fields, row): |
| 408 | self.counts[table] = self.counts.get(table, 0) + 1 |
| 409 | rid = row.get("id") |
| 410 | if not isinstance(rid, tuple): |
| 411 | self.fail("%s:%d %s satırında id yok veya kaçışlanmamış" % (fname, lineno, table)) |
| 412 | return |
| 413 | _, rtable, rkey = rid |
| 414 | if rtable != table: |
| 415 | self.fail("%s:%d id tablosu (%s) satır tablosuyla (%s) uyuşmuyor" |
| 416 | % (fname, lineno, rtable, table)) |
| 417 | full_id = "%s:%s" % (rtable, rkey) |
| 418 | if full_id in self.seen_ids: |
| 419 | self.fail("%s:%d yinelenen kimlik %s" % (fname, lineno, full_id)) |
| 420 | self.seen_ids.add(full_id) |
| 421 | |
| 422 | |
| 423 | if table in ("exam_attempt", "exam_answer", "exam_result", "answer_image"): |
| 424 | if rkey.endswith("_1"): |
| 425 | self.fail("%s:%d E3 ihlali: seq=1 kimliğinde _1 eki (%s)" |
| 426 | % (fname, lineno, full_id)) |
| 427 | seq = row.get("seq") |
| 428 | if seq == 1 and rkey.count("_") > 1 and rkey.split("_")[-1].isdigit(): |
| 429 | self.fail("%s:%d seq=1 ama kimlikte sıra eki var (%s)" |
| 430 | % (fname, lineno, full_id)) |
| 431 | if isinstance(seq, int) and seq > 1 and not rkey.endswith("_%d" % seq): |
| 432 | self.fail("%s:%d seq=%s ama kimlik eki yok (%s)" |
| 433 | % (fname, lineno, seq, full_id)) |
| 434 | |
| 435 | for key, value in row.items(): |
| 436 | if key == "id": |
| 437 | continue |
| 438 | if key not in fields: |
| 439 | self.fail("%s:%d %s.%s şemada yok" % (fname, lineno, table, key)) |
| 440 | continue |
| 441 | self.check_value(fname, lineno, table, key, value, fields) |
| 442 | |
| 443 | if table == "user": |
| 444 | self.user_roles[full_id] = row.get("role") |
| 445 | if table == "message": |
| 446 | s = row.get("sender") |
| 447 | r = row.get("recipient") |
| 448 | if isinstance(s, tuple) and isinstance(r, tuple): |
| 449 | sr = self.user_roles.get("user:%s" % s[2]) |
| 450 | rr = self.user_roles.get("user:%s" % r[2]) |
| 451 | if sr in ("student", "parent") and rr in ("student", "parent"): |
| 452 | self.fail("%s:%d rol kısıtı ihlali: %s -> %s" % (fname, lineno, sr, rr)) |
| 453 | |
| 454 | |
| 455 | for tname, field in FUTURE_FORBIDDEN: |
| 456 | if table == tname and isinstance(row.get(field), int) and row[field] > self.t_now: |
| 457 | self.fail("%s:%d %s.%s T_NOW sonrası (%d)" |
| 458 | % (fname, lineno, table, field, row[field])) |
| 459 | if table == "user": |
| 460 | for field in ("study_streak_last_day", "pomodoro_counted_day"): |
| 461 | v = row.get(field) |
| 462 | if isinstance(v, int) and v > 1_000_000: |
| 463 | self.fail("%s:%d E2 ihlali: %s ms gibi görünüyor (%d)" |
| 464 | % (fname, lineno, field, v)) |
| 465 | if isinstance(v, int) and 0 < v < 700_000: |
| 466 | self.fail("%s:%d E2 ihlali: %s gün numarası değil (%d)" |
| 467 | % (fname, lineno, field, v)) |
| 468 | if table == "exam_question": |
| 469 | pts = row.get("points") |
| 470 | if not isinstance(pts, int) or not (1 <= pts <= 100): |
| 471 | self.fail("%s:%d exam_question.points aralık dışı: %r" % (fname, lineno, pts)) |
| 472 | if table in ("exam_result", "homework_result"): |
| 473 | mark = row.get("mark") |
| 474 | if mark is not None and not (0 <= mark <= 100): |
| 475 | self.fail("%s:%d %s.mark aralık dışı: %r" % (fname, lineno, table, mark)) |
| 476 | if table == "subject": |
| 477 | self.subject_names[full_id] = row.get("name") |
| 478 | |
| 479 | |
| 480 | if table == "exam_question": |
| 481 | stem = row.get("text") |
| 482 | if isinstance(stem, str): |
| 483 | self.stem_texts[stem] = self.stem_texts.get(stem, 0) + 1 |
| 484 | self._check_topic(fname, lineno, stem, row.get("choices")) |
| 485 | exam = row.get("exam") |
| 486 | if isinstance(exam, tuple): |
| 487 | pair = ("%s:%s" % (exam[1], exam[2]), stem) |
| 488 | self.exam_stem_pairs[pair] = self.exam_stem_pairs.get(pair, 0) + 1 |
| 489 | choices = row.get("choices") |
| 490 | if isinstance(choices, list): |
| 491 | local = set() |
| 492 | for ch in choices: |
| 493 | txt = ch.get("text") if isinstance(ch, dict) else None |
| 494 | if not isinstance(txt, str): |
| 495 | continue |
| 496 | self.choice_texts[txt] = self.choice_texts.get(txt, 0) + 1 |
| 497 | if txt in local: |
| 498 | self.fail("%s:%d aynı sorunun iki şıkkı aynı metne sahip: %r" |
| 499 | % (fname, lineno, txt[:40])) |
| 500 | local.add(txt) |
| 501 | if table == "exam_answer": |
| 502 | txt = row.get("text") |
| 503 | if isinstance(txt, str): |
| 504 | n = len(txt) |
| 505 | self.answer_len_sum += n |
| 506 | self.answer_len_n += 1 |
| 507 | self.answer_len_max = max(self.answer_len_max, n) |
| 508 | if len(self.answer_lens) < 400000: |
| 509 | self.answer_lens.append(n) |
| 510 | if n > MAX_ANSWER_TEXT_LEN: |
| 511 | self.fail("%s:%d exam_answer.text %d karakter (üst sınır %d)" |
| 512 | % (fname, lineno, n, MAX_ANSWER_TEXT_LEN)) |
| 513 | if not txt.rstrip().endswith(ANSWER_TEXT_ENDINGS): |
| 514 | self.fail("%s:%d exam_answer.text kelime ortasından kesilmiş: %r" |
| 515 | % (fname, lineno, txt[-30:])) |
| 516 | |
| 517 | if table == "menu" and len(row.get("date") or "") != 10: |
| 518 | self.fail("%s:%d menu.date 10 karakter değil" % (fname, lineno)) |
| 519 | |
| 520 | |
| 521 | ts_field = ULID_TIME_FIELDS.get(table) |
| 522 | if ts_field and not rkey.startswith("open_") and len(rkey) == 26: |
| 523 | want = row.get(ts_field) |
| 524 | got = ulid_time(rkey) |
| 525 | if isinstance(want, int) and got is not None and got != want: |
| 526 | self.fail("%s:%d %s kimliğinin zaman öneki %s ile uyuşmuyor (%d != %d)" |
| 527 | % (fname, lineno, table, ts_field, got, want)) |
| 528 | |
| 529 | |
| 530 | for t, field, _c, _r, _f in COUNTER_CHECKS: |
| 531 | if table == t and field in row and row[field] is not None: |
| 532 | self.counter_values.setdefault((t, field), {})[full_id] = row[field] |
| 533 | for _t, _field, counted, ref_field, extra in COUNTER_CHECKS: |
| 534 | if table == counted: |
| 535 | if extra and row.get(extra[0]) != extra[1]: |
| 536 | continue |
| 537 | target = row.get(ref_field) |
| 538 | if isinstance(target, tuple): |
| 539 | k = "%s:%s" % (target[1], target[2]) |
| 540 | d = self.ref_counts.setdefault((_t, _field), {}) |
| 541 | d[k] = d.get(k, 0) + 1 |
| 542 | |
| 543 | def check_value(self, fname, lineno, table, key, value, fields): |
| 544 | spec = fields[key] |
| 545 | ftype = spec["type"] |
| 546 | if value is None: |
| 547 | if not spec["optional"] and spec.get("default") is None: |
| 548 | self.fail("%s:%d %s.%s zorunlu ama NONE" % (fname, lineno, table, key)) |
| 549 | return |
| 550 | if isinstance(value, tuple) and value[0] == "record": |
| 551 | target = "%s:%s" % (value[1], value[2]) |
| 552 | if "record<" in ftype: |
| 553 | want = ftype.split("record<")[1].split(">")[0] |
| 554 | if value[1] != want: |
| 555 | self.fail("%s:%d %s.%s %s bekleniyordu, %s geldi" |
| 556 | % (fname, lineno, table, key, want, value[1])) |
| 557 | if target not in self.seen_ids: |
| 558 | self.fail("%s:%d %s.%s henüz üretilmemiş kimliğe işaret ediyor: %s" |
| 559 | % (fname, lineno, table, key, target)) |
| 560 | else: |
| 561 | |
| 562 | if target not in self.seen_ids: |
| 563 | self.warnings.append("%s.%s ileri referans: %s" % (table, key, target)) |
| 564 | return |
| 565 | enum = ENUM_FIELDS.get((table, key)) |
| 566 | if enum is not None and isinstance(value, str) and value not in enum: |
| 567 | self.fail("%s:%d %s.%s geçersiz enum: %r" % (fname, lineno, table, key, value)) |
| 568 | limit = MONEY_FIELDS.get((table, key)) |
| 569 | if limit is not None and isinstance(value, int) and not (0 <= value <= limit): |
| 570 | self.fail("%s:%d %s.%s para sınırı dışı: %d" % (fname, lineno, table, key, value)) |
| 571 | if ftype.replace("option<", "").rstrip(">") == "int" and isinstance(value, float): |
| 572 | self.fail("%s:%d %s.%s int olmalı, ondalık yazıldı" % (fname, lineno, table, key)) |
| 573 | if isinstance(value, list): |
| 574 | for item in value: |
| 575 | if isinstance(item, tuple) and item[0] == "record": |
| 576 | target = "%s:%s" % (item[1], item[2]) |
| 577 | if target not in self.seen_ids: |
| 578 | self.fail("%s:%d %s.%s dizi öğesi üretilmemiş kimliğe işaret ediyor: %s" |
| 579 | % (fname, lineno, table, key, target)) |
| 580 | if isinstance(value, dict): |
| 581 | if (table, key) in FLEXIBLE_FIELDS: |
| 582 | return |
| 583 | for sub, subval in value.items(): |
| 584 | path = "%s.%s" % (key, sub) |
| 585 | if path not in fields: |
| 586 | self.fail("%s:%d %s.%s şemada yok" % (fname, lineno, table, path)) |
| 587 | |
| 588 | def check_counters(self): |
| 589 | for table, field, counted, _ref, _extra in COUNTER_CHECKS: |
| 590 | values = self.counter_values.get((table, field), {}) |
| 591 | actual = self.ref_counts.get((table, field), {}) |
| 592 | for rid, value in values.items(): |
| 593 | real = actual.get(rid, 0) |
| 594 | if value != real: |
| 595 | self.fail("SAYAÇ: %s.%s = %s, gerçek %s (%s)" |
| 596 | % (table, field, value, real, rid)) |
| 597 | for rid, real in actual.items(): |
| 598 | if rid not in values and real > 0: |
| 599 | self.fail("SAYAÇ: %s.%s yazılmamış ama %d satır var (%s)" |
| 600 | % (table, field, real, rid)) |
| 601 | |
| 602 | def _check_topic(self, fname, lineno, stem, choices): |
| 603 | |
| 604 | |
| 605 | |
| 606 | |
| 607 | |
| 608 | |
| 609 | topic = None |
| 610 | for name in _SUBJECT_NAMES_BY_LEN: |
| 611 | if name in stem: |
| 612 | topic = name |
| 613 | break |
| 614 | if topic is None: |
| 615 | return |
| 616 | own = set(_SUBJECT_POOLS[topic]) |
| 617 | blob = stem |
| 618 | if isinstance(choices, list): |
| 619 | for ch in choices: |
| 620 | if isinstance(ch, dict) and isinstance(ch.get("text"), str): |
| 621 | blob += " " + ch["text"] |
| 622 | |
| 623 | |
| 624 | blob = blob.replace(topic, " ") |
| 625 | self.topic_checked += 1 |
| 626 | for concept in _ALL_TOPIC_CONCEPTS - own: |
| 627 | if not _has_concept(blob, concept): |
| 628 | continue |
| 629 | |
| 630 | if any(concept in o and _has_concept(blob, o) for o in own): |
| 631 | continue |
| 632 | self.topic_violations += 1 |
| 633 | self.topic_by_concept[concept] = self.topic_by_concept.get(concept, 0) + 1 |
| 634 | if len(self.topic_examples) < 5: |
| 635 | self.topic_examples.append("%s:%d [%s] yabancı kavram: %r" |
| 636 | % (fname, lineno, topic, concept)) |
| 637 | return |
| 638 | |
| 639 | def check_topic_match(self): |
| 640 | if not self.topic_checked: |
| 641 | return |
| 642 | share = self.topic_violations / self.topic_checked |
| 643 | self.topic_share = share |
| 644 | if share > MAX_TOPIC_MISMATCH_SHARE: |
| 645 | self.fail("KONU: kavram uyumsuzluğu %%%.2f (eşik %%%.1f) — %d / %d soru" |
| 646 | % (share * 100, MAX_TOPIC_MISMATCH_SHARE * 100, |
| 647 | self.topic_violations, self.topic_checked)) |
| 648 | top = sorted(self.topic_by_concept.items(), key=lambda kv: -kv[1])[:8] |
| 649 | self.fail("KONU en sık uyumsuz kavramlar: %s" |
| 650 | % ", ".join("%s (%d)" % (c, n) for c, n in top)) |
| 651 | for ex in self.topic_examples: |
| 652 | self.fail("KONU örneği: %s" % ex) |
| 653 | |
| 654 | def check_text_quality(self): |
| 655 | |
| 656 | total_choices = sum(self.choice_texts.values()) |
| 657 | uniq = len(self.choice_texts) |
| 658 | if total_choices: |
| 659 | if uniq < MIN_UNIQUE_CHOICE_TEXTS: |
| 660 | self.fail("METİN: tekil şık metni %d, eşik %d" |
| 661 | % (uniq, MIN_UNIQUE_CHOICE_TEXTS)) |
| 662 | top_text, top_n = max(self.choice_texts.items(), key=lambda kv: kv[1]) |
| 663 | share = top_n / total_choices |
| 664 | if share > MAX_CHOICE_TEXT_SHARE: |
| 665 | self.fail("METİN: en sık şık metni payı %%%.2f (eşik %%%.1f) — %r" |
| 666 | % (share * 100, MAX_CHOICE_TEXT_SHARE * 100, top_text[:50])) |
| 667 | self.text_stats = { |
| 668 | "sik_toplam": total_choices, "sik_tekil": uniq, |
| 669 | "sik_en_sik_pay_pct": round(share * 100, 3), |
| 670 | "sik_en_sik_metin": top_text, |
| 671 | } |
| 672 | uniq_stems = len(self.stem_texts) |
| 673 | if self.stem_texts and uniq_stems < MIN_UNIQUE_QUESTION_STEMS: |
| 674 | self.fail("METİN: tekil soru kökü %d, eşik %d" |
| 675 | % (uniq_stems, MIN_UNIQUE_QUESTION_STEMS)) |
| 676 | total_stems = sum(self.stem_texts.values()) |
| 677 | |
| 678 | |
| 679 | same_exam_dups = sum(n - 1 for n in self.exam_stem_pairs.values() if n > 1) |
| 680 | cross_exam_reuse = total_stems - uniq_stems |
| 681 | self.stem_stats = {"kok_toplam": total_stems, "kok_tekil": uniq_stems, |
| 682 | "sinav_ici_tekrar": same_exam_dups, |
| 683 | "sinavlar_arasi_yeniden_kullanim": cross_exam_reuse} |
| 684 | if same_exam_dups > MAX_SAME_EXAM_DUPLICATE_STEMS: |
| 685 | self.fail("METİN: aynı sınav içinde tekrar eden soru kökü %d (eşik %d)" |
| 686 | % (same_exam_dups, MAX_SAME_EXAM_DUPLICATE_STEMS)) |
| 687 | worst = sorted((kv for kv in self.exam_stem_pairs.items() if kv[1] > 1), |
| 688 | key=lambda kv: -kv[1])[:3] |
| 689 | for (exam, stem), n in worst: |
| 690 | self.fail("METİN örneği: %s içinde %d kez: %r" % (exam, n, stem[:60])) |
| 691 | |
| 692 | def check_manifest_counts(self): |
| 693 | for table, expected in self.manifest["tablo_satir_sayilari"].items(): |
| 694 | got = self.counts.get(table, 0) |
| 695 | if got != expected: |
| 696 | self.fail("MANIFEST: %s %d satır bildiriyor, dosyada %d var" |
| 697 | % (table, expected, got)) |
| 698 | |
| 699 | |
| 700 | def main(argv): |
| 701 | seed_dir = argv[1] if len(argv) > 1 else os.path.normpath( |
| 702 | os.path.join(BASE, "..", "seed")) |
| 703 | schema = argv[2] if len(argv) > 2 else os.path.normpath( |
| 704 | os.path.join(BASE, "..", "spec", "schema.json")) |
| 705 | checker = Checker(seed_dir, schema) |
| 706 | errors = checker.run() |
| 707 | total = sum(checker.counts.values()) |
| 708 | print("Denetlenen dizin : %s" % seed_dir) |
| 709 | print("Tablo / satır : %d / %d" % (len(checker.counts), total)) |
| 710 | print("Tekil kimlik : %d" % len(checker.seen_ids)) |
| 711 | stats = getattr(checker, "text_stats", None) |
| 712 | if stats: |
| 713 | print("Şık metni : %d şık / %d tekil / en sık %%%.3f" |
| 714 | % (stats["sik_toplam"], stats["sik_tekil"], stats["sik_en_sik_pay_pct"])) |
| 715 | stems = getattr(checker, "stem_stats", None) |
| 716 | if stems: |
| 717 | print("Soru kökü : %d soru / %d tekil kök" |
| 718 | % (stems["kok_toplam"], stems["kok_tekil"])) |
| 719 | print(" sınav içi tekrar: %d (eşik %d) / sınavlar arası yeniden kullanım: %d" |
| 720 | % (stems["sinav_ici_tekrar"], MAX_SAME_EXAM_DUPLICATE_STEMS, |
| 721 | stems["sinavlar_arasi_yeniden_kullanim"])) |
| 722 | if checker.answer_len_n: |
| 723 | lens = sorted(checker.answer_lens) |
| 724 | med = lens[len(lens) // 2] |
| 725 | print("Metin cevabı : %d cevap / ortanca %d / azami %d karakter" |
| 726 | % (checker.answer_len_n, med, checker.answer_len_max)) |
| 727 | if checker.topic_checked: |
| 728 | print("Konu-kavram uyumu: %d sayısal soru / %d uyumsuz (%%%.2f)" |
| 729 | % (checker.topic_checked, checker.topic_violations, |
| 730 | 100.0 * checker.topic_violations / checker.topic_checked)) |
| 731 | st = checker.syntax_stats |
| 732 | print("Sözdizimi : %d dosya dengeli / %d tek tırnaklı, %d çift tırnaklı dize" |
| 733 | % (st["dosya"], st["tek_tirnakli"], st["cift_tirnakli"])) |
| 734 | print("Tırnak kaçışı : \\' sayısı %d (sıfır olmalı) / çift tırnakta kaçış %d" |
| 735 | % (st["ters_bolu_tirnak"], st["kacisli_cift_tirnak"])) |
| 736 | if checker.warnings: |
| 737 | print("Uyarı : %d ileri referans (tipsiz option<record>)" |
| 738 | % len(checker.warnings)) |
| 739 | for w in checker.warnings[:3]: |
| 740 | print(" %s" % w) |
| 741 | if errors: |
| 742 | print("\nHATA (%d):" % len(errors)) |
| 743 | for e in errors: |
| 744 | print(" - %s" % e) |
| 745 | return 1 |
| 746 | print("\nTEMİZ: şema, enum, referans, sayaç ve zaman kontrolleri geçti.") |
| 747 | return 0 |
| 748 | |
| 749 | |
| 750 | if __name__ == "__main__": |
| 751 | raise SystemExit(main(sys.argv)) |