"""AI Hub 수학 라벨링 zip(TL_*, VL_*) -> 정제된 문항 JSONL. ETL(Extract, Transform, Load: 꺼내서 -> 고쳐서 -> DB에 넣는 과정) 중 앞의 두 단계(Extract, Transform)입니다. Supabase 적재(Load)는 다음 단계에서 이 JSONL 을 읽어 처리합니다. 사용법 (저장소 루트에서) python scripts/04_normalize_aihub.py --root "D:\\수학" --out data/aihub_normalized python scripts/04_normalize_aihub.py --root "D:\\수학" --out data/aihub_normalized --limit 500 # 맛보기 입력 : --root 아래의 TL_*.zip, VL_*.zip (압축을 풀지 않고 zip 안의 JSON 을 바로 읽습니다) 출력 : --out 폴더 aihub_A.jsonl 텍스트로 완비된 문항 (표는 표 형식 글자로 바꿔 포함) <- 바로 쓸 수 있는 풀 aihub_B.jsonl 그림이 필요한 문항 (원천 이미지에서 잘라 쓸 때까지 보류) aihub_C.jsonl 검수가 필요한 문항 (글자 깨짐, 정답·선택지 누락 등; 이유가 reasons 에 있음) normalize_report.txt 무엇을 얼마나 고쳤는지 / 등급 / 이유별 개수 coverage_after.csv 단원 x 난이도별 문항 수 (A, A+B) tables_failed.jsonl 표를 못 바꾼 원본 (있을 때만) - 이 파일을 보내 주시면 변환 규칙을 고칩니다 등급 (3.2판 조사의 정의를 이어받되, '해설'은 나중에 새로 만들 것이므로 따로 취급) A : 문항 본문·선택지·정답이 글자로 완비. 표는 표 형식 글자로 바꿔 넣음. B : A 이지만 문항이나 선택지에 그림이 필요함 (그림 위치는 source_meta.figure_boxes) C : 문항 본문이 없음 / 정답을 못 읽음 / 객관식 선택지 5개가 안 맞음 / 문항·선택지·정답이 깨짐 / 표 변환 실패 해설은 등급과 별개입니다. 해설이 없거나, 글자가 깨졌거나, 그림이 필요하면 solution_md 를 비우고(null) 플래그를 남깁니다. (깨진 해설을 학생에게 보여 주지 않기 위해서이며, 원본은 source_meta.solution_raw_broken 에 보관) 이후 단계에서 해설을 새로 생성하고 정답과 대조해 채웁니다. 고치는 것(전부 source_meta.flags 에 기록) HTML 껍데기(
, ) 제거, 엔티티(<) 복원, ```html 코드 울타리 제거, 표(, Mathpix 식
) -> 마크다운 표(병합 칸이 있으면 정리된 HTML 표), '이다$. $A$' 같은 구분자 이탈, '0. 9455' 소수점 뒤 공백, 수식 밖의 < > 는 < > 로, 수식 안의 < > 는 \\lt \\gt 로 (화면에서 태그로 오인되어 글자가 사라지는 것 방지) 안 고치는 것: 수식 속 글자 깨짐($..$0, f② 등) - 억지로 복구하지 않고 C(문항 쪽) 또는 해설 재생성(해설 쪽)으로 보냅니다. """ from __future__ import annotations import argparse import csv import html import json import re import sys import zipfile from collections import Counter, defaultdict from dataclasses import dataclass, field from html.parser import HTMLParser from pathlib import Path from typing import Any if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8", errors="replace") ROOT = Path(__file__).resolve().parents[1] PATTERNS = ("TL_*.zip", "VL_*.zip") GRADE_CODE = { ("중학교", "1학년"): "m1", ("중학교", "2학년"): "m2", ("중학교", "3학년"): "m3", ("고등학교", "1학년"): "h1", } DIFF_CODE = {"하": "low", "중": "mid", "상": "high"} QTYPE = {"객관식": "multiple_choice", "주관식": "short_answer"} CIRCLED = "①②③④⑤" # ---- 3.2판 조사에서 검증한 손상 탐지 규칙 (그대로 이어받음) ---- GLUED_DIGIT = re.compile(r"(?<=[A-Za-z0-9)\]}])\$\d") CIRCLED_AFTER_LETTER = re.compile(r"(?·/ 인 경우만 HTML 로 본다 KNOWN_TAGS = ("table|thead|tbody|tfoot|tr|td|th|caption|colgroup|col|span|div|br|p|html|head|body|style|script|" "title|meta|b|i|u|strong|em|sub|sup|h[1-6]|ul|ol|li|center|font") HTML_TAG = re.compile(rf"/])", re.IGNORECASE) NOT_A_TAG = re.compile(rf"<(?!/?(?:{KNOWN_TAGS})(?=[\s>/])|!--|!DOCTYPE)", re.IGNORECASE) HTML_TABLE = re.compile(r" '이다. $A$는' DECIMAL_SPACE = re.compile(r"(?<=\d)\. (?=\d)") # '0. 9455' -> '0.9455' MATH_SPLIT = re.compile(r"(\$\$.*?\$\$|\$[^$]*\$|\\\[.*?\\\])", re.DOTALL) TEXT_CLASSES = ("문항(텍스트)", "정답(텍스트)", "오답(텍스트)", "해설(텍스트)") IMAGE_CLASSES = ("문항(이미지)", "정답(이미지)", "오답(이미지)", "해설(이미지)") # ================================================================ HTML -> 글자 VOID = {"br", "hr", "img", "meta", "link", "input", "col", "area", "base", "wbr"} BLOCK = {"div", "p", "tr", "li", "ul", "ol", "h1", "h2", "h3", "h4", "h5", "h6", "center", "caption", "body", "html"} DROP = {"style", "script", "head", "title"} class Node: __slots__ = ("tag", "attrs", "kids") def __init__(self, tag: str, attrs: list | None = None): self.tag = tag self.attrs = {k: (v or "") for k, v in (attrs or [])} self.kids: list[Node | str] = [] class _Builder(HTMLParser): def __init__(self) -> None: super().__init__(convert_charrefs=True) self.root = Node("#root") self.stack = [self.root] def handle_starttag(self, tag, attrs): n = Node(tag, attrs) self.stack[-1].kids.append(n) if tag not in VOID: self.stack.append(n) def handle_startendtag(self, tag, attrs): self.stack[-1].kids.append(Node(tag, attrs)) def handle_endtag(self, tag): for i in range(len(self.stack) - 1, 0, -1): if self.stack[i].tag == tag: del self.stack[i:] return def handle_data(self, data): self.stack[-1].kids.append(data) def parse_html(s: str) -> Node: b = _Builder() b.feed(NOT_A_TAG.sub("<", s)) # 태그가 아닌 '<' 는 글자로 지킨다 b.close() return b.root def has_tag(n: Node, tag: str) -> bool: return any(isinstance(k, Node) and (k.tag == tag or has_tag(k, tag)) for k in n.kids) def find_rows(n: Node) -> list[Node]: rows = [] for k in n.kids: if isinstance(k, Node): if k.tag == "tr": rows.append(k) elif k.tag != "table": # 표 안의 표는 따라가지 않음 rows.extend(find_rows(k)) return rows def esc_pipes(cell: str) -> str: """마크다운 표 칸 안의 '|' 처리: 수식 속은 \\vert, 그 밖은 \\|""" out = [] for part in MATH_SPLIT.split(cell): out.append(part.replace("|", "\\vert ") if MATH_SPLIT.fullmatch(part) else part.replace("|", "\\|")) return "".join(out) def cell_text(n: Node, stats: Counter) -> str: return re.sub(r"\s+", " ", render_children(n, stats)).strip() def grid_to_md(grid: list[list[str]], spans: bool, stats: Counter, spans_info: list[list[tuple[int, int]]]) -> str: width = max(len(r) for r in grid) if spans: # 병합 칸이 있으면 마크다운 표로 못 나타내므로 정리된 HTML 표(태그는 table/tr/td/th, 속성은 병합만) stats["tables_html_fallback"] += 1 lines = ["
"] for r, info in zip(grid, spans_info): tds = [] for text, (cs, rs) in zip(r, info): attr = (f' colspan="{cs}"' if cs > 1 else "") + (f' rowspan="{rs}"' if rs > 1 else "") tds.append(f"{html.escape(text, quote=False)}") lines.append("" + "".join(tds) + "") lines.append("
") return "\n".join(lines) stats["tables_md"] += 1 rows = [r + [""] * (width - len(r)) for r in grid] md = ["| " + " | ".join(esc_pipes(c) for c in rows[0]) + " |", "|" + " --- |" * width] md += ["| " + " | ".join(esc_pipes(c) for c in r) + " |" for r in rows[1:]] return "\n".join(md) def table_to_md(n: Node, stats: Counter) -> str: rows = find_rows(n) grid, info, spans = [], [], False for tr in rows: cells = [k for k in tr.kids if isinstance(k, Node) and k.tag in ("td", "th")] if not cells: continue grid.append([cell_text(c, stats) for c in cells]) row_info = [] for c in cells: try: cs, rs = int(c.attrs.get("colspan", 1) or 1), int(c.attrs.get("rowspan", 1) or 1) except ValueError: cs = rs = 1 row_info.append((cs, rs)) spans = spans or cs > 1 or rs > 1 info.append(row_info) if not grid: stats["tables_failed"] += 1 return "[[TABLE_FAILED]]" return grid_to_md(grid, spans, stats, info) def grid_div_to_md(n: Node, stats: Counter) -> str: """ 태그가 없는 div 격자: 자식 = 행, 손자 = 칸 이라고 보고 읽는다 (읽기 실패 시 실패로 기록).""" rows = [k for k in n.kids if isinstance(k, Node)] grid = [] for r in rows: cells = [k for k in r.kids if isinstance(k, Node)] if cells: grid.append([cell_text(c, stats) for c in cells]) if len(grid) < 1 or max(len(r) for r in grid) < 1: stats["tables_failed"] += 1 return "[[TABLE_FAILED]]" stats["tables_div_grid"] += 1 return grid_to_md(grid, False, stats, []) def render_children(n: Node, stats: Counter) -> str: return "".join(k if isinstance(k, str) else render_el(k, stats) for k in n.kids) def render_el(n: Node, stats: Counter) -> str: t = n.tag if t in DROP: return "" if t == "br": return "\n" if t == "table": stats["tables_found"] += 1 return "\n\n" + table_to_md(n, stats) + "\n\n" cls = n.attrs.get("class", "") if t == "div" and "table_tabular" in cls and not has_tag(n, "table"): stats["tables_found"] += 1 return "\n\n" + grid_div_to_md(n, stats) + "\n\n" inner = render_children(n, stats) if t == "span" and "math-block" in cls: body = inner.strip() for d in ("$$", "$"): # 이미 달러로 감싸져 있으면 벗기고 아래에서 $$ 로 다시 감싼다 if len(body) > 2 * len(d) and body.startswith(d) and body.endswith(d): body = body[len(d):-len(d)].strip() break return "\n$$" + body + "$$\n" if body else "" if t in BLOCK: return "\n" + inner + "\n" return inner # ================================================================ 글자 다듬기 @dataclass class Cleaned: text: str has_table: bool = False table_failed: bool = False html_cleaned: bool = False notes: set = field(default_factory=set) def tidy(s: str, notes: set) -> str: s = s.replace("\u00a0", " ").replace("\u200b", "") s = re.sub(r"[ \t]+", " ", s) s = re.sub(r" *\n *", "\n", s) s = re.sub(r"\n{3,}", "\n\n", s).strip() s2 = DELIM_FIX.sub(r"\1\2 $", s) if s2 != s: notes.add("delimiter_fixed") s = s2 def dec(m: re.Match) -> str: text, j = m.string, m.start() while j > 0 and text[j - 1].isdigit(): j -= 1 return m.group(0) if (j == 0 or text[j - 1] == "\n") else "." # 줄 맨 앞 '1. 2번' 은 번호라서 둠 s2 = DECIMAL_SPACE.sub(dec, s) if s2 != s: notes.add("decimal_space_fixed") s = s2 return s def clean_box(raw: str, stats: Counter) -> Cleaned: out = Cleaned(text="") s = FENCE.sub("", raw or "") if s != (raw or ""): out.notes.add("code_fence_removed") if HTML_TAG.search(s): out.html_cleaned = True out.has_table = bool(HTML_TABLE.search(s)) before = stats["tables_failed"] s = render_children(parse_html(s), stats) if "[[TABLE_FAILED]]" in s or stats["tables_failed"] > before: out.table_failed = True elif ENTITY.search(s): s = html.unescape(s) out.notes.add("entity_unescaped") out.text = tidy(s, out.notes) return out def finalize_md(s: str) -> str: """저장 직전: 수식 밖 < > 는 < > 로, 수식 안은 \\lt \\gt 로 (화면에서 태그로 오인되지 않게).""" out = [] for part in MATH_SPLIT.split(s): if MATH_SPLIT.fullmatch(part): out.append(part.replace("<", "\\lt ").replace(">", "\\gt ")) else: out.append(re.sub(r"]*>", lambda m: m.group(0), part) if part.lstrip().startswith("
") else part.replace("<", "<").replace(">", ">")) return "".join(out) def finalize_with_tables(s: str) -> str: """정리된 HTML 표(
...
)는 그대로 두고 그 밖의 글자만 finalize_md 로 처리.""" pieces = re.split(r"(.*?
)", s, flags=re.DOTALL) return "".join(p if p.startswith("") else finalize_md(p) for p in pieces) def is_pure_math(text: str) -> bool: rest = MATH_SPAN.sub("", text) return len(HANGUL.findall(rest)) < 5 def damage_of(text: str) -> list[str]: return [name for name, rx in DAMAGE_CHECKS if rx.search(text)] # ================================================================ 문항 한 개 정제 @dataclass class Item: cls: str kind: str # text / formula / figure / table text: str y: float x: float bbox: list table_failed: bool = False def bbox_of(box: dict) -> list[float]: try: tv = box.get("Type_value") v = tv[0] if tv and isinstance(tv[0], (list, tuple)) else tv return [float(v[0]), float(v[1]), float(v[2]), float(v[3])] except Exception: return [0.0, 0.0, 0.0, 0.0] def join_pieces(pieces: list[str]) -> str: """상자 조각들을 이어 붙임: 표시 수식($$, \\[ )과 표는 줄을 바꾸고, 문장 조각은 공백으로 잇는다.""" out = "" for p in pieces: p = p.strip() if not p: continue if not out: out = p elif (p.startswith(("$$", "\\[", "|", "")) or out.rsplit("\n", 1)[-1].lstrip().startswith("|")): # 표 바로 뒤 문장은 새 문단으로(표 줄에 붙으면 사라짐) after_table = out.endswith("
") or out.rsplit("\n", 1)[-1].lstrip().startswith("|") out += "\n\n" + p if (p.startswith(("|", " dict[str, str]: """'② 5 ③ 7' -> {'②': '5', '③': '7'} (동그라미 숫자 기준으로 쪼갬)""" ms = list(re.finditer(f"[{CIRCLED}]", text)) res: dict[str, list[str]] = {} for i, m in enumerate(ms): end = ms[i + 1].start() if i + 1 < len(ms) else len(text) res.setdefault(m.group(0), []).append(text[m.end():end].strip()) return {k: v for k, v in ((d, vs) for d, vs in res.items())} and {k: "\u0000".join(v) for k, v in res.items()} def strip_dollars(s: str) -> str: s = re.sub(r"\\text\s*\{([^{}]*)\}", r"\1", s) s = s.replace("$", "").replace("\\,", "").replace("\\;", "").replace("\\!", "") return re.sub(r"\s+", " ", s).strip().rstrip(".").strip() def load_unit_map(path: Path) -> dict[str, dict[str, dict[str, str]]]: """{"2022": {2022코드: 행}, "2015": {2015코드: 행}} - 두 교육과정의 코드가 같은 글자여도 뜻이 다를 수 있어 따로 보관""" if not path.exists(): return {} with path.open(encoding="utf-8-sig", newline="") as f: rows = list(csv.DictReader(f)) return {"2022": {r["code_2022_primary"]: r for r in rows if r.get("code_2022_primary")}, "2015": {r["code_2015_primary"]: r for r in rows if r.get("code_2015_primary")}} def normalize_one(data: dict, origin: dict, unit_map: dict, stats: Counter, html_dump: list | None = None): raw = data.get("raw_data_info") or {} src = data.get("source_data_info") or {} ref = str(src.get("source_data_name") or "").strip() gcode = GRADE_CODE.get((raw.get("school"), raw.get("grade"))) if not ref or not gcode: stats["skipped_no_ref_or_grade"] += 1 return None diff_txt, ptype_txt = str(src.get("level_of_difficulty")), str(src.get("types_of_problems")) qtype = QTYPE.get(ptype_txt) s2015 = " / ".join(x.strip() for x in src.get("2015_achievement_standard", []) or [] if x.strip()) s2022 = " / ".join(x.strip() for x in src.get("2022_achievement_standard", []) or [] if x.strip()) codes = CODE_RE.findall(s2015) codes22 = CODE_RE.findall(s2022) # 2022 개정 교육과정 기준을 우선 사용하고, 2022 코드가 비었거나 표에 없을 때만 2015 코드로 보충한다 um, unit_basis = None, None if codes22 and unit_map.get("2022", {}).get(codes22[0]): um, unit_basis = unit_map["2022"][codes22[0]], "2022" elif codes and unit_map.get("2015", {}).get(codes[0]): um, unit_basis = unit_map["2015"][codes[0]], "2015_fallback" classes: dict[str, list] = {} for block in data.get("learning_data_info", []) or []: classes.setdefault(str(block.get("class_name")), []).extend(block.get("class_info_list", []) or []) flags: set[str] = set() reasons: list[str] = [] local = Counter() def items_of(*names: str) -> list[Item]: res = [] for cn in names: for b in classes.get(cn, []): rawt = str(b.get("text_description", "") or "") c = clean_box(rawt, local) if c.html_cleaned or c.notes: flags.update(c.notes) if c.html_cleaned: flags.add("html_cleaned") if c.has_table: flags.add("table_rendered") if html_dump is not None and (HTML_TABLE.search(rawt)): html_dump.append({"source_ref": ref, "class": cn, "raw": rawt, "converted": c.text}) if cn.endswith("(이미지)"): kind = "table" if c.has_table else ("formula" if is_pure_math(c.text) else "figure") else: kind = "text" bb = bbox_of(b) res.append(Item(cn, kind, c.text, bb[1], bb[0], bb, c.table_failed)) return sorted(res, key=lambda it: (it.y, it.x)) # ---- 문항 본문 stem_items = items_of("문항(텍스트)", "문항(이미지)") has_stem_text = bool(classes.get("문항(텍스트)")) and any(i.kind == "text" and i.text for i in stem_items) if not has_stem_text: reasons.append("no_stem_text") stem_vis = [i for i in stem_items if i.kind != "figure"] stem_figs = [i for i in stem_items if i.kind == "figure"] stem_raw = join_pieces([i.text for i in stem_vis]) if re.search(r"(?:물음|질문)에\s*답하시오\.?\s*$", stem_raw.strip()): # 묻는 문장 없이 끝남 -> 질문이 빠진 문항 reasons.append("stem_incomplete") # ---- 정답 / 선택지 ans_items = items_of("정답(텍스트)", "정답(이미지)") wrong_items = items_of("오답(텍스트)", "오답(이미지)") choice_items = sorted(ans_items + wrong_items, key=lambda it: (it.y, it.x)) choice_figs = [i for i in choice_items if i.kind == "figure"] if any(i.table_failed for i in stem_items + choice_items): reasons.append("table_convert_failed") if not ans_items: reasons.append("no_answer") choices: list[str] = [] answer = "" answer_display = "" accepted: list[str] = [] # 객관식이라고 적혀 있지만 오답 상자가 없고 정답에도 ①~⑤ 가 없으면(예: 정답이 '㉠') 단답형으로 취급 if (qtype == "multiple_choice" and ans_items and not wrong_items and not any(c in CIRCLED for it in ans_items for c in it.text)): qtype = "short_answer" flags.add("mc_without_choices") if qtype == "multiple_choice": merged: dict[str, str] = {} conflict = False for it in choice_items: if it.kind == "figure": # 그림 선택지: 설명문 속 번호를 쪼개지 않고 맨 앞 번호만 쓴다 for dd in re.findall(rf"([{CIRCLED}])\s*(?:이미지|그림)", it.text) or re.findall(rf"^\s*([{CIRCLED}])", it.text): merged.setdefault(dd, "(그림)") flags.add("choices_are_figures") continue for d, txt in split_marked(it.text).items(): for one in txt.split("\u0000"): if d in merged and merged[d] != one: conflict = True merged.setdefault(d, one) # 정답 상자에만 번호가 빠진 경우: 번호가 붙은 선택지가 4개이고 번호 없는 정답 상자가 1개면, 빠진 번호가 정답이다 inferred = None plain = [it for it in ans_items if it.kind != "figure"] if (not conflict and len(plain) == 1 and not any(c in CIRCLED for c in plain[0].text) and len([d for d in CIRCLED if d not in merged]) == 1 and plain[0].text.strip()): inferred = next(d for d in CIRCLED if d not in merged) merged[inferred] = plain[0].text.strip() flags.add("answer_marker_inferred") if conflict: reasons.append("choice_conflict") if all(d in merged and merged[d] for d in CIRCLED): choices = [f"{d} {merged[d]}" for d in CIRCLED] else: reasons.append("choices_incomplete") ans_digits = [] for it in ans_items: if it.kind == "figure": ans_digits += (re.findall(rf"([{CIRCLED}])\s*(?:이미지|그림)", it.text) or re.findall(rf"^\s*([{CIRCLED}])", it.text))[:1] else: ans_digits += [c for c in it.text if c in CIRCLED] ans_unique = sorted(set(ans_digits)) multi_ask = bool(re.search(r"모두|두\s*개|2\s*개|세\s*개|3\s*개", stem_raw)) if inferred: answer = str(CIRCLED.index(inferred) + 1) answer_display = inferred elif len(ans_unique) == 1: answer = str(CIRCLED.index(ans_unique[0]) + 1) answer_display = ans_unique[0] elif len(ans_unique) >= 2 and multi_ask: # 복수 정답: '1,4' 처럼 쉼표로 이은 번호 (채점은 집합 비교로 해야 함) answer = ",".join(str(CIRCLED.index(d) + 1) for d in ans_unique) answer_display = " ".join(ans_unique) flags.add("multi_answer") elif ans_items: reasons.append("answer_unparsed" if not ans_unique else "answer_ambiguous") elif qtype == "short_answer": pieces = [i.text for i in ans_items if i.kind != "figure"] if any(i.kind == "figure" for i in ans_items): reasons.append("answer_is_figure") answer_display = join_pieces(pieces) answer = strip_dollars(answer_display) if not answer and ans_items: reasons.append("answer_unparsed") accepted = [a for a in dict.fromkeys([answer, answer.replace(" ", "")]) if a] else: reasons.append("unknown_problem_type") # ---- 해설 sol_items = items_of("해설(텍스트)", "해설(이미지)") sol_vis = [i for i in sol_items if i.kind != "figure"] sol_figs = [i for i in sol_items if i.kind == "figure"] sol_raw = join_pieces([i.text for i in sol_vis]) if any(i.table_failed for i in sol_items): flags.add("solution_table_failed") # ---- 글자 깨짐 (문항·선택지·정답 / 해설을 따로 본다) dmg_main: set[str] = set() for i in stem_vis: dmg_main.update(damage_of(i.text)) for it in choice_items: # 선택지는 동그라미 숫자를 떼고 조각별로 검사 (정상적인 '1③' 오탐 방지) if it.kind == "figure": continue for txt in split_marked(it.text).values(): for one in txt.split("\u0000"): dmg_main.update(damage_of(one)) if qtype == "short_answer" and it in ans_items: dmg_main.update(damage_of(it.text)) if dmg_main: reasons.append("broken_math_in_stem_or_choice:" + ",".join(sorted(dmg_main))) dmg_sol = set(damage_of(sol_raw)) solution_md = None if not sol_raw: flags.add("solution_missing") elif dmg_sol: flags.add("solution_broken") else: solution_md = finalize_with_tables(sol_raw) if sol_figs: flags.add("solution_needs_figure") solution_md = None # 그림이 있어야 이해되는 해설은 학생에게 그대로 보이지 않고, 새로 만들 때까지 비워 둔다 # ---- 등급 if reasons: tier = "C" elif stem_figs or choice_figs: tier = "B" else: tier = "A" if unit_basis == "2015_fallback": flags.add("unit_by_2015_fallback") if um is None: flags.add("unit_unmapped") elif um.get("confidence") and um["confidence"] != "high": flags.add("unit_medium_confidence") fig_boxes = [{"class": i.cls, "bbox": i.bbox, "description": i.text[:300]} for i in stem_figs + choice_figs] fig_desc = " / ".join(i.text for i in stem_figs + choice_figs) or None stats.update(local) meta = { "dataset": "aihub-71859", "split": origin.get("split"), "zip": origin.get("zip"), "json": origin.get("json"), "school": raw.get("school"), "grade_text": raw.get("grade"), "semester": raw.get("semester"), "publisher": raw.get("publisher"), "revision_year": raw.get("revision_year"), "standard_2015": s2015, "standard_2022": s2022, "unit_code_2015": codes[0] if codes else None, "unit_code_2022": codes22[0] if codes22 else None, "unit_basis": unit_basis, "unit_confidence": (um or {}).get("confidence"), "difficulty_text": diff_txt, "problem_type_text": ptype_txt, "tier": tier, "reasons": reasons, "flags": sorted(flags), "needs_figure": bool(stem_figs or choice_figs), "figure_boxes": fig_boxes, "answer_display_md": finalize_with_tables(answer_display) if answer_display else None, "solution_raw_broken": finalize_with_tables(sol_raw) if (sol_raw and solution_md is None) else None, } row = { "source": "aihub", "source_ref": ref, "source_meta": meta, "rights_status": "unreviewed", "grade_code": gcode, "unit_id": (um or {}).get("unit_id"), "difficulty": DIFF_CODE.get(diff_txt), "score": None, "qtype": qtype, "stem_md": finalize_with_tables(stem_raw), "choices": choices, "figure_description": fig_desc, "figure_path": None, "answer": answer, "accepted_answers": accepted, "solution_md": solution_md, "intent": None, "verified": False, "verify_note": None, "status": "draft", } return row, tier # ================================================================ 입출력 def read_json(raw: bytes) -> dict | None: for enc in ("utf-8-sig", "utf-8", "cp949"): try: return json.loads(raw.decode(enc)) except Exception: continue return None def iter_label_files(root: Path, limit: int | None): n = 0 zips = sorted({p for pat in PATTERNS for p in root.rglob(pat)}) for zpath in zips: split = "training" if zpath.name.upper().startswith("TL_") else "validation" with zipfile.ZipFile(zpath) as zf: for info in zf.infolist(): if info.is_dir() or not info.filename.lower().endswith(".json"): continue data = read_json(zf.read(info)) yield data, {"split": split, "zip": zpath.name, "json": info.filename} n += 1 if limit and n >= limit: return if not zips: # zip 이 없으면 풀어 둔 JSON 폴더로 보고 읽는다 (시험용) for jp in sorted(root.rglob("*.json")): yield read_json(jp.read_bytes()), {"split": "loose", "zip": None, "json": jp.name} n += 1 if limit and n >= limit: return def load_all_units(path: Path) -> list[tuple[str, str]]: if not path.exists(): return [] text = path.read_text(encoding="utf-8") ids = re.findall(r"^\s*-\s*id:\s*([UM]\d+)", text, re.M) names = re.findall(r'^\s*name:\s*"([^"]+)"', text, re.M) return list(zip(ids, names)) if ids and len(ids) == len(names) else [] def main() -> None: ap = argparse.ArgumentParser(description="AI Hub 라벨링 zip -> 정제 JSONL") ap.add_argument("--root", type=Path, required=True, help="TL_*/VL_* zip 이 있는 폴더 (예: D:\\수학)") ap.add_argument("--out", type=Path, default=ROOT / "data" / "aihub_normalized") ap.add_argument("--unit-map", type=Path, default=ROOT / "configs" / "standard_unit_map.csv") ap.add_argument("--units-yaml", type=Path, default=ROOT / "configs" / "curriculum_units.yaml") ap.add_argument("--limit", type=int, help="맛보기: 앞에서 이 개수만 처리") ap.add_argument("--inspect", nargs="+", metavar="SOURCE_REF", help="문항 이름(예: S3_중등_1_000005)의 원본 상자 구조를 출력하고 끝냄") ap.add_argument("--dump-tables", type=int, default=0, help="표가 든 원본 N개를 tables_dump.jsonl 로 저장(변환 확인용)") a = ap.parse_args() if a.inspect: want = set(a.inspect) for data, origin in iter_label_files(a.root, None): nm = str(((data or {}).get("source_data_info") or {}).get("source_data_name") or "") if nm in want: print("=" * 70, "\n", nm, origin["zip"]) for blk in data.get("learning_data_info", []) or []: for b in blk.get("class_info_list", []) or []: print(f"[{blk.get('class_name')}] bbox={bbox_of(b)} {str(b.get('text_description'))[:160]!r}") want.discard(nm) if not want: break if want: print("찾지 못함:", sorted(want)) return unit_map = load_unit_map(a.unit_map) if unit_map and not unit_map.get("2022"): print(f"[경고] {a.unit_map} 에 code_2022_primary 열이 없습니다. 새 standard_unit_map.csv 로 덮어쓰세요. " "(지금은 모든 문항이 2015 코드로만 단원이 정해집니다)") if not unit_map: print(f"[알림] {a.unit_map} 를 읽지 못했습니다. 모든 문항의 unit_id 가 비게 됩니다.") a.out.mkdir(parents=True, exist_ok=True) stats, tier_count = Counter(), Counter() reason_count, flag_count = Counter(), Counter() seen: dict[str, str] = {} dups = 0 matrix: dict[tuple[str, str], Counter] = defaultdict(Counter) dump: list = [] if a.dump_tables else None failed_tables: list = [] files = {t: (a.out / f"aihub_{t}.jsonl").open("w", encoding="utf-8") for t in ("A", "B", "C")} total = 0 try: for data, origin in iter_label_files(a.root, a.limit): total += 1 if total % 2000 == 0: print(f" ... {total}개 처리") if not isinstance(data, dict): stats["json_parse_fail"] += 1 continue res = normalize_one(data, origin, unit_map, stats, dump) if res is None: continue row, tier = res ref = row["source_ref"] if ref in seen: dups += 1 continue seen[ref] = origin["zip"] or origin["json"] tier_count[tier] += 1 for r in row["source_meta"]["reasons"]: reason_count[r.split(":")[0] + (":" + r.split(":")[1] if ":" in r else "")] += 1 for fl in row["source_meta"]["flags"]: flag_count[fl] += 1 if "table_convert_failed" in row["source_meta"]["reasons"]: failed_tables.append({"source_ref": ref}) matrix[(row["unit_id"] or "?", row["difficulty"] or "?")][tier] += 1 files[tier].write(json.dumps(row, ensure_ascii=False) + "\n") finally: for f in files.values(): f.close() if dump: with (a.out / "tables_dump.jsonl").open("w", encoding="utf-8") as f: for d in dump[: a.dump_tables]: f.write(json.dumps(d, ensure_ascii=False) + "\n") if stats["tables_failed"]: with (a.out / "tables_failed.jsonl").open("w", encoding="utf-8") as f: for d in (dump or []): if "[[TABLE_FAILED]]" in d["converted"]: f.write(json.dumps(d, ensure_ascii=False) + "\n") # 커버리지 표 diff_order = ("low", "mid", "high") rows = [] unit_names = {u: n for u, n in load_all_units(a.units_yaml)} units = sorted({u for u, _ in matrix} | set(unit_names), key=lambda u: (u[0] != "U", u)) for u in units: r = {"unit_id": u, "unit_name": unit_names.get(u, ""), } for d in diff_order: c = matrix.get((u, d), Counter()) r[f"A_{d}"], r[f"usable_{d}"] = c["A"], c["A"] + c["B"] rows.append(r) with (a.out / "coverage_after.csv").open("w", encoding="utf-8-sig", newline="") as f: w = csv.DictWriter(f, fieldnames=["unit_id", "unit_name", "A_low", "A_mid", "A_high", "usable_low", "usable_mid", "usable_high"]) w.writeheader() w.writerows(rows) n_out = sum(tier_count.values()) total_ok = n_out L = [f"AI Hub 정제 결과 (읽은 JSON {total}개, 중복 source_ref {dups}개 제외, 출력 {n_out}개)", f"등급: A {tier_count['A']} | B {tier_count['B']} | C {tier_count['C']}", f" - A+B(사용 가능 후보) {tier_count['A'] + tier_count['B']}개 / 바로 쓸 수 있는 A {tier_count['A']}개"] L.append("C 가 된 이유(한 문항에 이유가 여러 개일 수 있음):") L += [f" - {k}: {v}" for k, v in reason_count.most_common()] or [" (없음)"] L.append("고친 것 / 표시한 것 (문항 수):") L += [f" - {k}: {v}" for k, v in flag_count.most_common()] or [" (없음)"] L.append(f"표 변환: 찾은 표 {stats['tables_found']}개 -> 마크다운 표 {stats['tables_md']}, " f"div 격자 {stats['tables_div_grid']}, 병합 칸이라 HTML 표 {stats['tables_html_fallback']}, 실패 {stats['tables_failed']}") if stats["json_parse_fail"] or stats["skipped_no_ref_or_grade"]: L.append(f"건너뜀: JSON 해석 실패 {stats['json_parse_fail']}, 이름·학년 정보 없음 {stats['skipped_no_ref_or_grade']}") no_unit = 0 unmapped = flag_count["unit_unmapped"] L.append(f"단원 매핑: 2022 기준 {total_ok - flag_count['unit_by_2015_fallback'] - unmapped}개, 2015 코드로 보충 {flag_count['unit_by_2015_fallback']}개, " f"매핑 실패 {unmapped}개, 신뢰도 낮음(검토 필요) {flag_count['unit_medium_confidence']}개") (a.out / "normalize_report.txt").write_text("\n".join(L) + "\n", encoding="utf-8") print("\n".join(L)) print(f"[저장] {a.out}") if __name__ == "__main__": main()