r"""AI Hub 정제 결과(aihub_A.jsonl)에 점검 보정을 적용해 DB 갱신용 파일을 만든다. (비용·외부 쓰기 없음) python scripts\21_aihub_fix.py # -> data/aihub_normalized/aihub_A_fixed.jsonl + 요약 python scripts\21_aihub_fix.py --list sub # 규칙으로 고친 소문항 번호 목록 보기 입력 data/aihub_normalized/aihub_A.jsonl 04 정제 결과 (그대로 두고 읽기만 함) data/aihub_normalized/review/aihub_overrides.jsonl 문항별 손 보정 (나중 줄 우선, 필드별 덮어쓰기) {"source_ref", "stem_md"?, "choices"?, "answer"?, "accepted_answers"?, "solution_md"?, "stem_subs"?: [[old, new]], "choice_set"?: [[번호, 새 보기]], "solution_from_raw"?: true, "solution_subs"?: [[old, new]], "exclude"?: "사유", "keep_circled"?: true, "note"} 덮어쓰기 파일은 python tools/review/aihub_ov_all.py 로 다시 만든다 (aihub_ov_batch*.py 순서대로). 규칙 (보정 전·후를 source_meta.fix 에 남김) R1 지문 끝 소문항 번호: 원본의 여러 소문항을 한 문항으로 쪼갤 때 남은 번호 하나 ("다음을 계산하시오. ② $…$", "② $a=2$ 일 때 …") -> 번호만 지움. 지문에 원문자가 딱 하나이고 지시문 바로 뒤나 맨 앞에 있을 때만. keep_circled 로 끌 수 있음. R2 주관식 정답 앞 소문항 번호 / R3 지문 속 ①~⑤ 보기형 주관식 -> 객관식 / R4 소문항 답 묶음 제외 R5 보기의 $ 짝·표 조각 찌꺼기 / R6 지문 맨 앞 원본 문항 번호('03 다음 …') 출력 data/aihub_normalized/aihub_A_fixed.jsonl exclude 된 문항은 빠짐 -> 07 로 퇴역 처리 DB 반영 (사용자가 직접) python scripts\06_load_supabase.py --file data\aihub_normalized\aihub_A_fixed.jsonl --refresh --with-solution --dry-run python scripts\07_retire_missing.py --file data\aihub_normalized\aihub_A_fixed.jsonl (미리보기 후 --apply) """ from __future__ import annotations import argparse, json, re from collections import Counter from pathlib import Path ROOT = Path(__file__).resolve().parents[1] SRC = ROOT / "data/aihub_normalized/aihub_A.jsonl" OV = ROOT / "data/aihub_normalized/review/aihub_overrides.jsonl" OUT = ROOT / "data/aihub_normalized/aihub_A_fixed.jsonl" C = "①②③④⑤⑥⑦⑧⑨⑩" INSTR = r"(?:시오|여라|하라|보자)\s*\.?|\?|\|\s|" R1_AFTER = re.compile(rf"({INSTR})\s*(\$?)\s*[{C}]\s*(?:\\;|\\,)?\s*") R1_START = re.compile(rf"^\s*(\$?)\s*[{C}]\s*") LABEL = re.compile(rf"^\s*[{C}]\s*") # R6 지문 맨 앞의 원본 문항 번호 ('03 다음은 …', '3-1 다음 …', '$1-1$ 다음 …') STEM_NO = re.compile(r"^\s*(?:\d{1,3}(?:-\d)?|\$\d-\d\$)\.?\s+(?=(?:다음|아래|위|오른쪽|왼쪽|그림|표)\S*)") def load_overrides(): ov = {} if OV.exists(): for line in open(OV, encoding="utf-8"): if line.strip(): o = json.loads(line) ov.setdefault(o["source_ref"], {}).update({k: v for k, v in o.items() if k != "source_ref"}) return ov def rule_sub_label(stem: str) -> str | None: if len(re.findall(f"[{C}]", stem)) != 1: return None if R1_AFTER.search(stem): return R1_AFTER.sub(lambda m: m.group(1).rstrip() + " " + m.group(2), stem, count=1) if R1_START.match(stem): return R1_START.sub(lambda m: m.group(1), stem, count=1) # 원문자가 하나뿐이고 빈칸 '(\text{ ① })'·참조 '①에서/①의…'가 아니면 소문항 번호로 본다 m = re.search(rf"[{C}]\s*", stem) if m and not re.search(rf"\\text\s*\{{\s*[{C}]", stem) and not re.match(r"(에서|의|과|와|을|를|번|\))", stem[m.end():]): return (stem[:m.start()].rstrip() + " " + stem[m.end():]).strip() return None def safe_sub_label(stem: str) -> str | None: """rule_sub_label 결과가 수식 경계($ 짝)를 깨면 쓰지 않는다.""" new = rule_sub_label(stem) if new is None or new.count("$") % 2 or new.count("$") != stem.count("$"): return None return new def rule_answer_label(r) -> bool: """R2: 주관식 정답 앞의 소문항 번호 하나를 지운다 ('③ x^{6}' -> 'x^{6}'). 번호만 있는 답('⑤')은 그대로.""" a = str(r.get("answer") or "") if r["qtype"] != "short_answer" or len(re.findall(f"[{C}]", a)) != 1 or not LABEL.match(a): return False rest = LABEL.sub("", a) if not rest.strip(): return False r["answer"] = rest acc = [LABEL.sub("", x) for x in (r.get("accepted_answers") or [])] r["accepted_answers"] = [x for x in dict.fromkeys(acc) if x.strip()] return True JUNK = re.compile(r"\\end\{array\}|\\text\s*\{|\\\\|(? bool: t = re.sub(r"\\[{}$]", "", c) return bool(t.count("$") % 2 or re.search(r"\$\s*\$|\\[ ;,]\s*[-\d]|\}\s*[-\d+]|\\text\s*\{\s*$", c)) def rule_choices(r) -> list[str] | None: """R5: 보기의 $ 짝·표 조각 찌꺼기를 걷어 낸다. 걷어 낸 내용이 단순한 수·식일 때만 바꾼다.""" ch = r.get("choices") or [] if r["qtype"] != "multiple_choice" or not any(_choice_broken(c) for c in ch): return None out = [] for c in ch: if not _choice_broken(c): out.append(c) continue lab = c.strip()[0] if c.strip()[:1] in C else "" body = c.strip()[1:] if lab else c.strip() clean = re.sub(r"\s+", " ", JUNK.sub(" ", body)).strip().rstrip(".").strip() if not SIMPLE.match(clean): return None mu = re.fullmatch(r"(-?[\d.]+)\s*([가-힣]+)", clean) out.append(f"{lab} ${mu.group(1)}${mu.group(2)}" if mu else f"{lab} ${clean}$") return out def _norm(t): t = re.sub(r"\$|\\left|\\right|\s", "", str(t)) return t.replace("\\geq", "\\ge").replace("\\leq", "\\le") def rule_sa_to_mc(r) -> str | None: """R3: 지문 안에 ① … ⑤ 보기가 들어 있는 '주관식'을 객관식으로. 정답을 번호로 맞추지 못하면 None(제외 대상).""" if r["qtype"] != "short_answer": return None s = r["stem_md"] pos = [s.find(ch) for ch in C[:5]] if any(p < 0 for p in pos) or pos != sorted(pos) or s.count("①") != 1: return None head, body = s[:pos[0]].rstrip(), s[pos[0]:] if not re.search(r"(것은|것을|것만을|것끼리|\?)\s*\??\s*(\(.*\))?\s*$", head): return None parts = re.split(f"(?=[{C[:5]}])", body) choices = [p.strip() for p in parts if p.strip()] if len(choices) != 5: return None a = str(r.get("answer") or "").strip() m = re.fullmatch(f"[{C[:5]}]", a) if m: idx = C.index(a) + 1 else: hit = [i + 1 for i, ch in enumerate(choices) if _norm(LABEL.sub("", ch)) == _norm(a)] if len(hit) != 1: return "nomatch" idx = hit[0] r["stem_md"], r["choices"], r["qtype"] = head, choices, "multiple_choice" r["answer"], r["accepted_answers"] = str(idx), [] return "ok" def main(): ap = argparse.ArgumentParser() ap.add_argument("--list", choices=["sub"]) a = ap.parse_args() ov = load_overrides() rows = [json.loads(l) for l in open(SRC, encoding="utf-8")] cnt, out, listed, excluded = Counter(), [], [], [] for r in rows: o = ov.get(r["source_ref"], {}) fix = [] auto_ex = None conv = rule_sa_to_mc(r) if conv == "ok": fix.append("R3_sa_to_mc"); cnt["R3_sa_to_mc"] += 1 elif conv == "nomatch": auto_ex = "R3 보기형 주관식인데 정답을 보기 번호로 맞추지 못함" if r["qtype"] == "short_answer" and (len(re.findall(f"[{C}]", str(r.get("answer")))) >= 2 or re.search(r"\(1\).*\(2\)", str(r.get("answer")))): auto_ex = "R4 소문항 여러 개의 답이 한 칸에 있음" if rule_answer_label(r): fix.append("R2_answer_label"); cnt["R2_answer_label"] += 1 if not o.get("keep_circled") and conv != "ok": new = safe_sub_label(r["stem_md"]) if new is not None: listed.append((r["source_ref"], r["stem_md"][:90], new[:90])) r["stem_md"] = new fix.append("R1_sub_label") cnt["R1_sub_label"] += 1 newc = rule_choices(r) if newc: r["choices"] = newc fix.append("R5_choices"); cnt["R5_choices"] += 1 sol = r.get("solution_md") or "" if ("R1_sub_label" in fix or "R2_answer_label" in fix) and LABEL.match(sol) and len(re.findall(f"[{C}]", sol)) == 1: r["solution_md"] = LABEL.sub("", sol) fix.append("R2b_solution_label"); cnt["R2b_solution_label"] += 1 for idx, text in o.get("choice_set", []): r["choices"][idx - 1] = text fix.append("ov_choice_set"); cnt["ov_choice_set"] += 1 for old, new in o.get("stem_subs", []): if r["stem_md"].count(old) != 1: raise SystemExit(f"{r['source_ref']}: stem_subs '{old}' 가 {r['stem_md'].count(old)}곳 (1곳이어야 함)") r["stem_md"] = r["stem_md"].replace(old, new) fix.append("ov_stem_subs"); cnt["ov_stem_subs"] += 1 new_stem = STEM_NO.sub("", r["stem_md"], count=1) if new_stem != r["stem_md"] and "stem_md" not in o: r["stem_md"] = new_stem fix.append("R6_stem_number"); cnt["R6_stem_number"] += 1 if o.get("solution_from_raw"): raw = (r.get("source_meta") or {}).get("solution_raw_broken") or "" for old, new in o.get("solution_subs", []): if raw.count(old) < 1: raise SystemExit(f"{r['source_ref']}: solution_subs '{old}' 없음") raw = raw.replace(old, new) r["solution_md"] = raw.strip() fix.append("ov_solution_from_raw"); cnt["ov_solution_from_raw"] += 1 for k in ("stem_md", "choices", "answer", "accepted_answers", "solution_md"): if k in o: r[k] = o[k] fix.append("ov_" + k) cnt["ov_" + k] += 1 if fix: r["source_meta"] = {**(r.get("source_meta") or {}), "fix": fix, "fix_note": o.get("note", "")} if o.get("include"): auto_ex = None if o.get("exclude") or auto_ex: cnt["excluded:" + (o.get("exclude") or auto_ex)[:2]] += 1 excluded.append((r["source_ref"], o.get("exclude") or auto_ex)) continue out.append(r) with open(OUT, "w", encoding="utf-8") as f: for r in out: f.write(json.dumps(r, ensure_ascii=False) + "\n") with open(OUT.with_name("aihub_excluded.jsonl"), "w", encoding="utf-8") as f: for ref, why in excluded: f.write(json.dumps({"source_ref": ref, "reason": why}, ensure_ascii=False) + "\n") nosol = sum(not (r.get("solution_md") or "").strip() for r in out) print(f"{len(rows)} -> {len(out)}행 {OUT}") print("보정:", dict(cnt), "| 해설 없음 남은 수:", nosol) if a.list == "sub": for s in listed: print(" | ".join(s)) if __name__ == "__main__": main()