r"""EBSi 정답 및 해설 PDF -> 문항별 정답 + 해설(LaTeX) (3단계, 무료) * 정답표(1페이지 5칸 x 6줄 격자)를 읽어 1~21번 보기 번호, 22~30번 단답 숫자를 얻는다. 단답 숫자는 수식 글꼴 코드(변환표로 숫자화) 또는 일반 숫자. 정답이 번호보다 조금 아래인 시험, 번호만 기울임체인 시험, 옆 단 해설이 같은 줄에 있는 시험도 처리한다. (28회 모두 30/30 확인) 2021_11 의 ①~⑤ 는 pdfplumber 가 못 읽어서 pypdfium2 로 보충한다 (answer_source="table_pdfium"). * 해설은 "N. [출제의도]" 로 시작하는 문항 단위로 나눈다. (3단 편집: 페이지 -> 단 -> 위에서 아래) 각 문항 해설을 12_ebsi_latex.py 와 같은 방식으로 LaTeX 로 복원한다. * 객관식 대조(참고용): 해설은 보통 보기 번호 없이 값으로 끝나므로, 해설 맨 끝 ①~⑤ 가 없으면 마지막 수식의 마지막 '=' 뒤 값을 2단계 보기(data/ebsi/latex)와 비교한다. answer_check = ok / mismatch / no_choice_in_explanation / n/a(단답). 채점 기준은 항상 정답표. 사용 예 (PowerShell) python scripts\13_ebsi_solution.py --dir data\ebsi\h1 --out data\ebsi\solutions python scripts\13_ebsi_solution.py --pdf data\ebsi\h1\2022_09_hs1_solution.pdf --show 1 22 """ from __future__ import annotations import argparse, importlib.util, json, re, statistics, sys from collections import Counter from pathlib import Path import pdfplumber sys.path.insert(0, str(Path(__file__).resolve().parent)) import ebsi_tables as TBL HERE = Path(__file__).resolve().parent CIRC = "①②③④⑤" def _load(name, fname): spec = importlib.util.spec_from_file_location(name, HERE / fname) m = importlib.util.module_from_spec(spec) spec.loader.exec_module(m) return m LX = _load("ebsi_latex", "12_ebsi_latex.py") PUA_DIGIT = {k: v["latex"] for k, v in LX.PUA_MAP.items() if v.get("kind") == "digit" and v["latex"].isdigit()} def isdig(c): t = c["text"] return t.isascii() and t.isdigit() # ------------------------------------------------------------ 정답표 def _cy(c): return (c["top"] + c["bottom"]) / 2 def _kind(c): t = c["text"] return "circ" if t in CIRC else "asc" if isdig(c) else "pua" if f"{ord(t[0]):04X}" in PUA_DIGIT else None def _toks_of(cs): """글자 -> 토큰. 같은 줄(중심 차 3pt 이내)에서 바로 이어지는 같은 종류 숫자는 한 덩어리.""" toks = [] for c in sorted(cs, key=lambda c: (round(_cy(c)), c["x0"])): k = _kind(c) if k is None: continue last = toks[-1] if toks else None prev = last["cs"][-1] if last else None if (last and k == last["kind"] != "circ" and abs(_cy(c) - last["cy"]) < 3 # 번호 '29' + 정답 '126' 분리: 글꼴·크기·기울임(번호만 기울인 시험 있음)이 같아야 묶음 and c["fontname"] == prev["fontname"] and abs(c["size"] - prev["size"]) < 0.3 and abs(c["matrix"][2] - prev["matrix"][2]) < 0.01 and c["x0"] > last["cs"][-1]["x0"] + 1 and c["x0"] - last["cs"][-1]["x1"] < 3): # 글자 상자는 겹칠 수 있음 last["cs"].append(c) else: toks.append({"kind": k, "cs": [c], "cy": _cy(c)}) for t in toks: t["x0"], t["x1"] = t["cs"][0]["x0"], t["cs"][-1]["x1"] return toks def _tok_value(t): if t["kind"] == "circ": return {"kind": "choice", "value": CIRC.index(t["cs"][0]["text"]) + 1} if t["kind"] == "pua": return {"kind": "integer", "value": int("".join(PUA_DIGIT[f"{ord(c['text'][0]):04X}"] for c in t["cs"]))} return {"kind": "integer", "value": int("".join(c["text"] for c in t["cs"]))} # 2021_11 정답표의 ①~⑤는 pdfminer(pdfplumber)가 글자를 아예 버리고, pdfium 은 한자로 잘못 읽는다. # (화면 렌더링과 대조해 확인한 대응. 코드 순서도 ①->⑤ 순) PDFIUM_CIRC_FIX = {"榕": "①", "涌": "②", "湧": "③", "溶": "④", "熔": "⑤"} def pdfium_extra_chars(path: Path): """pdfplumber 가 못 읽은 정답표 보기 번호를 pypdfium2(pdfplumber 설치 시 함께 깔림)로 보충.""" import pypdfium2 as pdfium doc = pdfium.PdfDocument(str(path)) try: pg = doc[0] H = pg.get_height() tp = pg.get_textpage() out = [] for i in range(tp.count_chars()): t = tp.get_text_range(i, 1) if t in CIRC or t in PDFIUM_CIRC_FIX: l, b, r, top = tp.get_charbox(i) out.append({"text": PDFIUM_CIRC_FIX.get(t, t), "x0": l, "x1": r, "top": H - top, "bottom": H - b, "fontname": "pdfium", "size": 0, "matrix": (0, 0, 0, 0, 0, 0), "pdfium": True}) return out finally: doc.close() def parse_answers(pdf: pdfplumber.PDF, extra_chars=None): """1페이지 정답표(5칸 x 6줄, 칸마다 [번호][정답])를 글자 위치로 읽는다. 1) '1 2 3 4 5' 가 차례로 나오는 줄을 찾아 칸의 x 위치(번호 오른쪽 끝)와 간격을 얻는다. 2) 표의 x 범위 밖 글자(옆 단 해설)는 버린다. 3) 번호 토큰 = 칸 위치에 오른쪽 끝이 맞는 ASCII 숫자. 번호는 1,2,...,30 순서로만 받아들인다. 4) 정답 = 같은 칸(번호 오른쪽 ~ 다음 칸 시작) 안에서 세로 중심이 가까운(9pt) 첫 토큰. 정답 줄이 번호 줄보다 조금 아래에 있는 시험(2021_11 등)도 중심 기준이라 잡힌다.""" p = pdf.pages[0] allc = [c for c in p.chars if c["text"].strip() and _kind(c)] if extra_chars: # pdfplumber 글자와 겹치지 않는 것만 allc += [e for e in extra_chars if not any(abs(c["x0"] - e["x0"]) < 2 and abs(_cy(c) - _cy(e)) < 2 for c in allc)] toks = _toks_of(allc) # 1) 기준 줄 찾기 head = None for t in toks: if t["kind"] != "asc" or "".join(c["text"] for c in t["cs"]) != "1": continue row = sorted([u for u in toks if u["kind"] == "asc" and abs(u["cy"] - t["cy"]) < 3 and u["x0"] >= t["x0"]], key=lambda u: u["x0"]) nums = ["".join(c["text"] for c in u["cs"]) for u in row] if nums[:5] == ["1", "2", "3", "4", "5"]: head = row[:5] break if head is None: return {}, "정답표 위치를 못 찾음" M = [(u["x0"] + u["x1"]) / 2 for u in head] # 번호 칸 가운데 (번호는 가운데 정렬) R = [u["x1"] for u in head] pitch = (M[4] - M[0]) / 4 y0 = head[0]["cy"] - 8 x_lo, x_hi = head[0]["x0"] - pitch * 0.4, R[4] + pitch * 0.8 box = [t for t in toks if x_lo <= t["x0"] <= x_hi and t["cy"] >= y0] def col(t): # 번호 칸이면 칸 번호, 아니면 None if t["kind"] != "asc": return None mid = (t["x0"] + t["x1"]) / 2 for j, m in enumerate(M): if abs(mid - m) < 3.5: return j return None # 3) 번호 토큰을 순서대로 numbers, want = {}, 1 for t in sorted(box, key=lambda t: (round(t["cy"] / 4), t["x0"])): j = col(t) if j is None or want > 30: continue v = int("".join(c["text"] for c in t["cs"])) if v == want and j == (want - 1) % 5: numbers[v] = t want += 1 # 4) 정답 짝짓기 used = {id(t) for t in numbers.values()} ans = {} for n, nt in numbers.items(): j = (n - 1) % 5 right = R[j] + pitch - (R[0] - head[0]["x0"]) - 2 # 다음 칸 번호 시작 직전 cand = [t for t in box if id(t) not in used and nt["x1"] - 1 <= t["x0"] < right and abs(t["cy"] - nt["cy"]) < 9 and col(t) is None] if cand: a = min(cand, key=lambda t: (abs(t["cy"] - nt["cy"]) > 3, t["x0"])) ans[n] = _tok_value(a) ans[n]["source"] = "table_pdfium" if a["cs"][0].get("pdfium") else "table" used.add(id(a)) err = None if len(numbers) == 30 else f"정답표 번호 {len(numbers)}/30개만 찾음" return ans, err # ------------------------------------------------------------ 고3 선택과목 구간 (교육청 형식) # 고3 해설은 공통(1~22) 뒤에 [확률과 통계] [미적분] [기하] 구간이 차례로 있고, 구간마다 23~30번 정답표가 따로 있다. # 이 앱은 확률과 통계만 쓴다: 확통 구간 정답표로 23~30 정답을 읽고, 미적분·기하 구간부터는 해설에서 뺀다. SUBJ = (("확통", ("[확률과", "확률과")), ("미적분", ("[미적분",)), ("기하", ("[기하",))) PUA_DIG_CH = {chr(int(k, 16)): v for k, v in PUA_DIGIT.items()} # 수식 글꼴 숫자 글자 -> '0'~'9' PUA_DIG_CH |= {chr(0x24F5 + i): CIRC[i] for i in range(5)} # ⓵~⓹(이중 원 숫자, 2024_06 고3 정답표) -> ①~⑤ def section_headers(pdf): """선택과목 구간 머리 위치. '[확률과 통계]'(3·4·5·10월) 또는 '확률과 통계 정답'(7월). 미적분·기하는 '[미적분]' '[기하]' 또는 '미적분 정답' '기하 정답'.""" out = [] for pi, p in enumerate(pdf.pages): ws = p.extract_words() for j, w in enumerate(ws): t = w["text"] nxt = " ".join(x["text"] for x in ws[j + 1:j + 3]) name = None if t.startswith("[선택"): # 평가원 형식 '[선택: 확률과 통계]' '[선택: 미적분]' '[선택: 기하]' t = "[" + nxt.split()[0] if nxt else t if t.startswith("[확률과") or (t == "확률과" and nxt.startswith("통계")): name = "확통" elif t.startswith("[미적분") or (t == "미적분" and nxt.startswith("정답")): name = "미적분" elif t.startswith("[기하") or (t == "기하" and nxt.startswith("정답")): name = "기하" if name and not any(h["name"] == name for h in out): out.append({"name": name, "page": pi, "x": w["x0"], "x1": w["x1"], "top": w["top"]}) return out def select_of(pdf, exam: str): """고3 해설의 선택과목 구간 정보: {"skip": 확통 머리, "cut": 다음 선택과목 머리} (없으면 None). 13·14 가 같이 씀.""" if not exam.endswith("_hs3"): return None hd = {h["name"]: h for h in section_headers(pdf)} if "확통" not in hd: return None t = hd["확통"] later = [h for k, h in hd.items() if k != "확통" and (h["page"], h["x"], h["top"]) > (t["page"], t["x"], t["top"])] return {"skip": t, "cut": min(later, key=lambda h: (h["page"], h["x"], h["top"])) if later else None} def parse_select_answers(pdf, hdr): """확통 머리 아래 정답표 '23 ③ 24 ④ … 29 55 30 97' (숫자가 수식 글꼴 전용 코드일 수 있음, '29288' 처럼 붙기도 함).""" p = pdf.pages[hdr["page"]] cx = (hdr["x"] + hdr["x1"]) / 2 ws = [w for w in p.extract_words() if hdr["top"] + 3 < w["top"] < hdr["top"] + 60 and abs((w["x0"] + w["x1"]) / 2 - cx) < 190] return pair_answers(ws, r"(2[3-9]|30)\.?", range(23, 31), "table_select") def pair_answers(ws, num_pat, wanted, source, max_gap=60): """번호 단어(num_pat) 와 같은 줄 오른쪽 가장 가까운 값(①~⑤ 또는 숫자)을 짝짓는다. '29288' '01.②' 처럼 번호와 값이 한 단어인 것도 받는다. 값이 없는 번호 단어(문항 시작 '28. [출제의도]')는 무시. 같은 번호가 여럿이면 값이 있는 것 중 위쪽 첫 것.""" # 줄(세로 4pt 안) 단위로 왼쪽부터 읽으며 '번호 → 값' 을 차례로 받는다. 번호는 wanted 순서대로만. # (값 '25' 가 번호처럼 보여도 순서상 값 자리이면 값: 2021_07 '29 25 30 51') toks = [] for w in ws: w["t"] = "".join(PUA_DIG_CH.get(ch, ch) for ch in w["text"]) if re.fullmatch(r"[①②③④⑤]|\d+\.?(?:[①②③④⑤]|\d+)?", w["t"]): toks.append(w) toks.sort(key=lambda w: w["top"]) lines = [] for w in toks: if lines and abs(w["top"] - lines[-1][0]["top"]) < 4: lines[-1].append(w) else: lines.append([w]) order = list(wanted) ans, k, pend = {}, 0, None for line in lines: pend = None for w in sorted(line, key=lambda w: w["x0"]): if pend is not None: # 값 자리 pn, px = pend pend = None if re.fullmatch(r"[①②③④⑤]|\d+", w["t"]) and w["x0"] < px + max_gap: v = w["t"] ans[pn] = ({"kind": "choice", "value": CIRC.index(v) + 1} if v in CIRC else {"kind": "integer", "value": int(v)}) | {"source": source} k += 1 continue k += 1 # 값이 글자로 안 나온 칸(①~⑤ 누락): 건너뛰고 이 단어를 번호로 다시 봄 if k >= len(order): break m = re.fullmatch(num_pat + r"([①②③④⑤]|\d*)", w["t"]) if not m or int(m.group(1)) != order[k]: continue if m.group(2): # '29288' '01.②' v = m.group(2) ans[order[k]] = ({"kind": "choice", "value": CIRC.index(v) + 1} if v in CIRC else {"kind": "integer", "value": int(v)}) | {"source": source} k += 1 else: pend = (order[k], w["x1"]) return ans def pdfium_list_answers(path: Path, wanted): """pdfplumber 가 ①~⑤를 못 읽는 해설(2024_06 고3 등): pdfium 글자로 'NN. ④' 목록을 다시 읽는다. 번호가 차례로(1씩 증가) 이어지는 구간만 받는다(본문 속 '23. 출제의도' 등 오인 방지).""" import pypdfium2 as pdfium doc = pdfium.PdfDocument(str(path)) lo = min(wanted) for i in range(len(doc)): t = "".join(PUA_DIG_CH.get(ch, ch) for ch in doc[i].get_textpage().get_text_range()) found = {} for m in re.finditer(r"(?= len(wanted) - 1: return found return {} def parse_list_answers(pdf): """평가원 형식 1쪽 정답 목록 '01. ④ 02. ⑤ … 16. 2 … 22. 61' (01~22). 번호 단어 오른쪽 같은 줄의 가장 가까운 값. '01.②' 처럼 붙은 단어도 받는다. 문항 시작 '16. 출제의도' 는 값이 아니어서 걸리지 않음.""" return pair_answers(pdf.pages[0].extract_words(), r"(\d{2})\.", range(1, 23), "table_list", max_gap=30) # ------------------------------------------------------------ 해설 나누기 START = re.compile(r"(\d{1,2})\.(?:\[출제|출제의도)") # 평가원 고3 해설은 'N. 출제의도 :' def _lines(chars, tol=1.5): """공백 아닌 글자를 같은 top(±tol)끼리 줄로 묶는다. 줄 안은 x 순서.""" cs = sorted((c for c in chars if c["text"].strip()), key=lambda c: (c["top"], c["x0"])) lines = [] for c in cs: if lines and abs(c["top"] - lines[-1][0]["top"]) <= tol: lines[-1].append(c) else: lines.append([c]) return [sorted(l, key=lambda c: c["x0"]) for l in lines] WORD_NUM = re.compile(r"^\d{1,2}\.$") def find_starts(pdf): """'N. [출제의도]' 표지 찾기. 두 방식을 합친다. 1) 단어 방식: '7.' 다음 단어가 '[출제…' (글꼴이 달라 top 이 1.5pt 넘게 어긋나도 됨) 2) 글자 방식: 같은 top 의 글자만 이어 'N.[출제'. extract_words 가 머리줄과 바로 아랫줄을 섞어 버리는 경우(2024_10 5번: '5. 주[출어제진의...')를 잡는다. 단어 방식 결과를 우선하고, 거기서 빠진 번호만 글자 방식으로 보충.""" found = {} for pi, p in enumerate(pdf.pages): ws = p.extract_words() for j, w in enumerate(ws[:-1]): if WORD_NUM.match(w["text"]) and ws[j + 1]["text"].startswith(("[출제", "출제의도")) and abs(ws[j + 1]["top"] - w["top"]) < 3: found.setdefault(int(w["text"][:-1]), {"page": pi, "x": w["x0"], "top": w["top"], "n": int(w["text"][:-1])}) for s in _find_starts_chars(pdf): found.setdefault(s["n"], s) return list(found.values()) def _find_starts_chars(pdf): out = [] for pi, p in enumerate(pdf.pages): for line in _lines(p.chars): s = "".join(c["text"] for c in line) for m in START.finditer(s): c0 = line[m.start(1)] if m.start(1) > 0 and line[m.start(1) - 1]["text"].isdigit(): continue # '123.[출제' 같은 오인 방지 out.append({"page": pi, "x": c0["x0"], "top": c0["top"], "n": int(m.group(1))}) return out def header_bottom(p, default=None): """페이지 머리말의 아래 끝. 머리말 = '정답 및 해설' 줄 + 그 아래 25pt 안의 '…학력평가' 줄. (1페이지 본문 안내문 '※ 본 전국연합학력평가는…' 은 머리말이 아님) 못 찾으면 기본값. 기본값: A3(가로 841) 152, A4(가로 595) 115 — A4 본문은 120 부터라 152 로 자르면 단마다 첫 2~3줄이 사라졌음 (2020_11 해설 18번 '점 P의 좌표는 (2/3,4)…', 20번 머리 줄; 2021_03·2022_11·2024_10 도 같음).""" if default is None: default = 152 if p.width > 700 else 115 lines = [(l, "".join(c["text"] for c in l)) for l in _lines([c for c in p.chars if c["top"] < 170], tol=3)] title = [l for l, s in lines if "정답및해설" in s] if not title: # 제목 줄이 없는 쪽: 머리말 아래 가로 구분선(쪽 너비 60% 이상, 130pt 위)이 있으면 그 바로 아래부터 본문. # (2021_06_hs3 해설: 2쪽부터 선이 85pt, 본문 첫 줄이 99pt 라 115 로 자르면 단마다 첫 줄이 사라졌음 # — 5번 g'(1)=…, 11·13·15번 머리 줄) rules = [l["top"] for l in p.lines if l["top"] < 130 and (l["x1"] - l["x0"]) > p.width * 0.6] if rules: return min(default, max(rules) + 2) # 제목 줄도 구분선도 없는 A4 쪽: 본문 첫 줄이 99pt 부근이라 115 로 자르면 단마다 첫 줄이 사라졌음 # (2025_05_hs3 15·21·27·30번 머리 줄, 2025_06·2025_09 3번 머리, 2022_09·2024_09 첫 줄 등). # 85 위에는 시험 제목만 있고, 85~115 의 '최근 수정일'·'■ [공통…]' 같은 머리 글은 첫 문항보다 앞이라 버려짐. if p.width <= 700: return 85 return default t0 = min(c["top"] for c in title[0]) bot = max(max(c["bottom"] for c in l) for l, s in lines if ("정답및해설" in s or "학력평가" in s) and min(c["top"] for c in l) < t0 + 25) return bot + 2 def column_lefts(starts): xs = sorted(s["x"] for s in starts) cols = [] for x in xs: if cols and abs(x - cols[-1][-1]) < 12: cols[-1].append(x) else: cols.append([x]) return [min(c) for c in cols] def col_of(x, lefts): k = 0 for i, l in enumerate(lefts): if x >= l - 6: k = i return k def _in_any(cx, cy, boxes, pad=0.5): return any(b[0] + pad <= cx <= b[2] - pad and b[1] + pad <= cy <= b[3] - pad for b in boxes) def split_solutions(pdf, drop_figure_labels: bool = True, select=None): """drop_figure_labels: 그림(이미지) 위에 겹쳐 쓴 라벨 글자(꼭짓점 A, 축 x·y, 원 안의 식 등)는 본문에서 뺀다. (2020_06 해설 6번: 이미지 두 장 위에 '-2x², x³+1, A, D' 라벨이 글자로 올라가 본문 앞에 섞였음) 화면 대조용 잘라내기(14_ebsi_review.py)는 그림 범위를 보려고 False 로 부른다.""" starts = find_starts(pdf) if not starts: return {}, "해설 시작 표지를 못 찾음" lefts = column_lefts(starts) for s in starts: s["col"] = col_of(s["x"], lefts) # 고3 선택과목: select = {"skip": 확통 머리(정답표 구역), "cut": 미적분/기하 머리(여기부터 해설에서 뺌)} select = select or {} cut = select.get("cut") cut_key = (cut["page"], col_of(cut["x"], lefts), cut["top"] - 2) if cut else None skip = select.get("skip") if cut_key: starts = [s for s in starts if (s["page"], s["col"], s["top"]) < cut_key] skip_zone = None if skip: sc = col_of(skip["x"], lefts) below = [s["top"] for s in starts if s["page"] == skip["page"] and s["col"] == sc and s["top"] > skip["top"]] skip_zone = (skip["page"], sc, skip["top"] - 2, min(below) - 2 if below else skip["top"] + 60) starts.sort(key=lambda s: (s["page"], s["col"], s["top"])) out: dict[int, dict] = {s["n"]: {"segs": {}} for s in starts} for pi, p in enumerate(pdf.pages): body_bot = p.height * 0.91 # 쪽 번호(아래쪽 가운데의 큰 숫자, 13pt 이상)가 91% 선보다 위에 있으면 그 위까지만 본문. # (A4 판 쪽 번호는 753pt 에 있어 본문 '…정리하면 y=…이다. 1 이를 ㉡에…' 처럼 섞였음: 2021_06 해설 13번) pn = [c for c in p.chars if c["text"].isdigit() and c["top"] > p.height * 0.85 and c["size"] >= 13 and abs((c["x0"] + c["x1"]) / 2 - p.width / 2) < 40] if pn: body_bot = min(body_bot, min(c["top"] for c in pn) - 1) head = header_bottom(p) pst = [s for s in starts if s["page"] == pi] figs = [] if drop_figure_labels: for im in p.images: box = (im["x0"], im["top"], im["x1"], im["bottom"]) # 이미지 안에 한글이 4자 이상이면 본문 위에 걸친 이미지(배경·상자)로 보고 건드리지 않음. # (2020_03 12번 본문, 14번 문항 번호가 지워졌던 문제) 그림 라벨은 거의 한글이 아님. hang = sum(1 for c in p.chars if _hangul(c["text"]) and _in_any((c["x0"] + c["x1"]) / 2, (c["top"] + c["bottom"]) / 2, [box])) if hang < 4: # 영역을 넓히지 않음: 8pt 넓히면 그림 옆 본문의 첨자·분자까지 지워졌음(2024_09 9·17·21번). # 경계에 걸친 라벨 조각(') )' 등)은 화면 대조에서 처리. figs.append(box) hrows: dict[int, list[float]] = {} # 단별 한글 글자 높이 (옆 단 줄은 보지 않음) if figs: for c in p.chars: if _hangul(c["text"]): hrows.setdefault(col_of(c["x0"], lefts), []).append((c["top"] + c["bottom"]) / 2) for v in hrows.values(): v.sort() def hangul_row(cy, col, tol=2): import bisect rows = hrows.get(col, []) i = bisect.bisect_left(rows, cy - tol) return i < len(rows) and rows[i] <= cy + tol def in_fig_band(c, cy, col): """그림과 같은 높이 범위(같은 단)에 있는 라벨: 그림 위 'y=g(x)', 옆 'A' 처럼 이미지 상자 밖에 붙은 것. 본문 보호: 한글 줄 ±7pt(첨자·분자·분모 높이) 안의 글자는 제외하지 않음.""" cx = (c["x0"] + c["x1"]) / 2 for b in figs: # 그림의 단은 가운데 x 로 판정 (왼쪽 끝으로 하면 옆 단 경계에 걸친 그림이 이 단 것으로 잡혀 # 그 높이의 수식 줄이 라벨로 지워졌음: 2022_07_hs3 11번 'b-a=4 ⋯㉠', 20번 끝 계산) if b[1] <= cy <= b[3] and col_of((b[0] + b[2]) / 2, lefts) == col and not hangul_row(cy, col, 7): return True return False for c in p.chars: if not c["text"].strip(): continue cy = (c["top"] + c["bottom"]) / 2 if cy > body_bot or cy < head: continue col = col_of(c["x0"], lefts) if cut_key and (pi, col, cy) >= cut_key: continue # 미적분·기하 구간 if skip_zone and pi == skip_zone[0] and col == skip_zone[1] and skip_zone[2] <= cy < skip_zone[3]: continue # 확통 머리·정답표 if figs and ((_in_any((c["x0"] + c["x1"]) / 2, cy, figs) and not hangul_row(cy, col)) or in_fig_band(c, cy, col)): continue # 그림 라벨 (같은 단·같은 높이에 한글이 있으면 본문 줄이라 남김: 2023_06 27번 '① n≤5인 경우') same = [s for s in pst if s["col"] == col and s["top"] <= cy + 6] if same: owner = same[-1] else: prev = [s for s in starts if (s["page"], s["col"]) < (pi, col)] if not prev: continue # 첫 문항보다 앞(정답표 등) owner = prev[-1] # 문항 번호 글자 자체는 제외 out[owner["n"]]["segs"].setdefault((pi, col), []).append(c) return out, None def _hangul(ch: str) -> bool: return bool(ch) and "가" <= ch <= "힣" def render_solution(segs, ctx): """단/페이지 조각을 이어 붙인다. 조각 경계(단 끝 = 꽉 찬 줄)도 한글-한글이면 줄바꿈 표지.""" out = "" for key in sorted(segs): t = LX.render_question(segs[key], ctx, mark_breaks=True) if not t: continue if out: out += LX.LINE_BREAK if (_hangul(out[-1]) and _hangul(t[0])) else " " out += t return out # ------------------------------------------------------------ 줄바꿈 자리: 붙일까, 띄울까 # 붙인 형태가 자료에 없을 때만 쓰는 '뒷조각이 조사·어미뿐' 목록. # '하면/하고/하여' 는 넣지 않음: '~라 하면', '~야 하고' 처럼 띄어 쓰는 경우가 흔함. JOSA = {"을", "를", "이", "가", "은", "는", "의", "에", "도", "와", "과", "로", "으로", "에서", "이다", "다", "이고", "이므로", "므로", "이면", "면", "부터", "까지", "만", "고", "며", "라", "이라"} UNITS = ("가지", "개", "배", "번", "명", "째", "만큼", "시간", "등분", "자리", "장", "회", "층", "cm", "m") _PUNCT = ".,)]}·…:;!?'\"" def _strip(w: str) -> str: return w.rstrip(_PUNCT) def word_counts(texts): """줄 안쪽(줄바꿈 표지가 없는) 어절 빈도. 끝 문장부호를 뗀 형태도 함께 센다.""" c = Counter() for t in texts: for w in t.split(" "): if not w or LX.LINE_BREAK in w: continue c[w] += 1 s = _strip(w) if s != w: c[s] += 1 return c def resolve_breaks(text: str, counts: Counter) -> str: """'앞어절<표지>뒷어절' -> 붙인 형태가 자료에 있고 뒷조각보다 흔하면 붙임, 아니면 공백. 붙인 형태가 자료에 없을 때는 뒷조각이 조사·어미뿐이면 붙임.""" def decide(m): a, b = m.group(1), m.group(2) a_word = a.rsplit("$", 1)[-1] if "$" in a else a # 수식 뒤에 붙은 한글만 비교 if not a_word: # 앞이 수식으로 끝남: 뒷조각이 조사일 때만 붙임 ('$\angle BAC$|를'), 아니면 새 말('따라서') # 숫자로 끝나는 수식 뒤의 단위 명사도 붙임 ('$2$|가지', '$13$|개씩', '$\frac{1}{3}$|배') numeric = re.search(r"[0-9}]\$$", a) is not None if _strip(b) in JOSA or (numeric and _strip(b).startswith(UNITS)): return a + b return a + " " + b joined = _strip(a_word + b) cj, cb, ca = counts[joined], counts[_strip(b)], counts[_strip(a_word.lstrip("([{'\""))] # 붙이는 경우: # - 뒷조각이 조사·어미 (단독 단어가 될 수 없음; '이' 는 지시어일 수 있어 제외) # - 붙인 형태가 뒷조각 단독보다 흔함 # - 앞조각이 단독으로 나온 적이 없고 붙인 형태는 있음 ('나열|하면', '꼭짓|점의') # - 앞뒤 조각 모두 단독으로 나온 적이 없음 ('지|나게', '따|라가야') # (뒤 두 규칙은 앞조각이 조사로 끝나면 쓰지 않음: '[그림9]의|경우가', '좌변과|우변의' 는 띄어 씀. # 마지막 규칙은 앞조각이 세 글자 이하인 조각일 때만) a_core = _strip(a_word.lstrip("([{'\"")) a_josa_end = a_core[-1:] in "의로과와을를은는에가도" if ((_strip(b) in JOSA and _strip(b) != "이") or cj > cb or (cj == 0 and _strip(b) in JOSA) or (not a_josa_end and ca == 0 and cj > 0) or (not a_josa_end and len(a_core) <= 3 and ca == 0 and cb == 0) # 앞조각이 한 글자이고 붙인 형태가 자료에 3번 이상 ('넓이를 구|하는': '하는' 단독도 흔해 띄어졌음) or (len(a_core) == 1 and cj >= 3)): return a + b return a + " " + b pat = re.compile(r"(\S*)" + LX.LINE_BREAK + r"([^\s" + LX.LINE_BREAK + r"]*)") while LX.LINE_BREAK in text: new = pat.sub(decide, text, count=1) if new == text: text = text.replace(LX.LINE_BREAK, " ") break text = new return text def _norm(s: str) -> str: s = s.replace("$", "").replace("\\left", "").replace("\\right", "").replace("\\,", "") s = re.sub(r"\s+", "", s) s = re.sub(r"[.,。]+$", "", s) return s def explanation_choice(text: str, choices: list[str] | None): """해설이 가리키는 보기 번호와 그 근거. 1) 해설 맨 끝(마지막 20자)에 ①~⑤가 있으면 그것 ('circle') 2) 아니면 마지막 수식의 마지막 '=' 뒤 값이 보기 중 정확히 하나와 같으면 그 번호 ('value')""" tail = text.rstrip()[-20:] circ = [ch for ch in tail if ch in CIRC] if circ: return CIRC.index(circ[-1]) + 1, "circle" if not choices or len(choices) != 5: return None, None maths = re.findall(r"\$([^$]+)\$", text) if not maths: return None, None last = maths[-1].split("=")[-1] hit = [i + 1 for i, c in enumerate(choices) if _norm(c) and _norm(c) == _norm(last)] if len(hit) == 1: return hit[0], "value" return None, None def load_choices(latex_dir: Path | None, exam: str): f = latex_dir / f"{exam}.jsonl" if latex_dir else None if not f or not f.exists(): return {} out = {} with open(f, encoding="utf-8") as fh: for line in fh: q = json.loads(line) out[q["number"]] = q.get("choices") return out def inject_missing_glyphs(pdf, path: Path): """pdfplumber 가 버리는 글자(configs/ebsi_missing_glyphs.json: 2021_11 해설의 ㉠~㉣·ㄱㄴㄷ·ⅰ~ⅶ·∈·′·| 99개)를 페이지 글자 목록에 끼워 넣는다. 높이·크기는 같은 줄 왼쪽 이웃 글자(가로선 제외)를 따르고(첨자 오판 방지), 글꼴은 글 기호(㉠·ㄱ·ⅰ 등)면 한글 본문 글꼴, 수식 기호(′·|·∈)면 이웃 글꼴.""" f = HERE.parent / "configs" / "ebsi_missing_glyphs.json" if not f.exists(): return 0 rows = json.loads(f.read_text(encoding="utf-8")).get(path.name, []) texty = set("㉠㉡㉢㉣㉤ㄱㄴㄷㄹⅰⅱⅲⅳⅴⅵⅶ") for r in rows: p = pdf.pages[r["page"]] orig = [c for c in p.chars if not c.get("missing_glyph")] body = [c for c in orig if _hangul(c["text"])] bsize = statistics.median([c["size"] for c in body]) if body else 8.0 bfont = Counter(c["fontname"] for c in body).most_common(1)[0][0] if body else "missing" nb = [c for c in orig if c["text"].strip() and c["text"] != "" and r["x0"] - 15 <= c["x1"] <= r["x0"] + 1 and c["top"] < r["bottom"] and c["bottom"] > r["top"]] if nb: n = max(nb, key=lambda c: c["x1"]) top, bot, size = n["top"], n["bottom"], n["size"] else: cy = (r["top"] + r["bottom"]) / 2 top, bot, size, n = cy - bsize / 2, cy + bsize / 2, bsize, None font = bfont if r["text"] in texty or n is None else n["fontname"] p.chars.append({"text": r["text"], "x0": r["x0"], "x1": r["x1"], "top": top, "bottom": bot, "size": size, "fontname": font, "matrix": (1, 0, 0, 1, 0, 0), "upright": True, "doctop": top, "missing_glyph": True}) return len(rows) def process_pdf(path: Path, latex_dir: Path | None = None): exam = path.name.replace("_solution.pdf", "") problems = [] choices = load_choices(latex_dir, exam) with pdfplumber.open(path) as pdf: LX.set_eq_fonts(pdf) # 익명 글꼴(CIDFont+Fn) PDF 의 수식 글꼴 판정 inject_missing_glyphs(pdf, path) ans, err1 = parse_answers(pdf) if len(ans) < 30: # 글자를 못 읽은 칸이 있으면 pdfium 으로 한 번 더 ans, err1 = parse_answers(pdf, pdfium_extra_chars(path)) select = None if exam.endswith("_hs3"): if len([k for k in ans if k <= 22]) < 22: # 평가원 형식: 1쪽 '01. ④ …' 목록 ans = parse_list_answers(pdf) | {k: v for k, v in ans.items() if k <= 22} hd = {h["name"]: h for h in section_headers(pdf)} if "확통" in hd: t = hd["확통"] later = [h for k, h in hd.items() if k != "확통" and (h["page"], h["x"], h["top"]) > (t["page"], t["x"], t["top"])] select = {"skip": t, "cut": min(later, key=lambda h: (h["page"], h["x"], h["top"])) if later else None} sel = parse_select_answers(pdf, t) ans = {k: v for k, v in ans.items() if k <= 22} | sel # pdfplumber 가 ①~⑤를 못 읽은 칸: pdfium 글자로 보충 (빈 칸만) for rng in (range(1, 23), range(23, 31)): if any(k not in ans for k in rng): ans = pdfium_list_answers(path, rng) | ans ans = {k: v for k, v in ans.items() if 1 <= k <= 30} err1 = None if len(ans) == 30 else f"정답표 {len(ans)}/30 (공통+확통)" # 원본 이미지로 확인한 정답 보정 (정답표 글자가 깨진 판: 2021_11·2023_11 고3 은 쪽 그림 + OCR 글자 층) ao = ANSWER_OVERRIDES.get(exam, {}) if ao: ans = {k: v for k, v in ans.items()} | ao err1 = None if len(ans) >= 30 else err1 sol, err2 = split_solutions(pdf, select=select) for n in range(1, 31): ctx = LX.Ctx() segs = sol.get(n, {}).get("segs", {}) text = render_solution(segs, ctx) if segs else "" # '( ⅰ )' -> '(ⅰ)' (2021_11 은 괄호와 로마숫자 사이에 공백 글자가 있음) text = re.sub(r"\(\s*([ⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩ]+)\s*\)", r"(\1)", text) # '(ⅰ$)n = 2$' -> '(ⅰ) $n = 2$' (닫는 괄호가 수식에 붙어 들어간 경우: 2020_09_hs2 등) text = re.sub(r"\(([ⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩ]+)\$\)", r"(\1) $", text) # 영문 i 로 쓴 로마숫자가 수식 맨 앞에 붙은 경우: '$(i)a > 0$' -> '(ⅰ) $a > 0$', '$(i i)$' -> '(ⅱ)' # (2022_06_hs2 해설 21·30번) ROM = {"i": "ⅰ", "i i": "ⅱ", "i i i": "ⅲ", "i v": "ⅳ", "v": "ⅴ"} text = re.sub(r"\$\((i i i|i i|i v|i|v)\)\$", lambda g: "(" + ROM[g.group(1)] + ")", text) text = re.sub(r"\$\((i i i|i i|i v|i|v)\)(?=[^$])", lambda g: "(" + ROM[g.group(1)] + ") $", text) # '(ⅰ) , (ⅱ) 에' -> '(ⅰ), (ⅱ)에' text = re.sub(r"\(([ⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩ]+)\) (?=[,에])", r"(\1)", text) # '(ⅰ) $\sim($ⅲ)에' -> '(ⅰ) $\sim$ (ⅲ)에' (2024_09_hs2·2025_09_hs2) text = re.sub(r"\$\\sim\(\$([ⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩ]+)\)", r"$\\sim$ (\1)", text) # '$A \cap B$=$\{ 5,9 \}$' -> '$A \cap B = \{ 5,9 \}$' (2025_03_hs2) text = re.sub(r"(?<=[^)\s])\$=\$(?=[^(])", " = ", text) # 수식 안 '≦'·'≧' -> '\le'·'\ge' (2025_03_hs2 26번) text = text.replace("≦", r" \le ").replace("≧", r" \ge ") text = TBL.convert_tables(text) # 증감표·부호표 -> array (칸 수가 맞을 때만) # 빈칸 '(가)' 괄호가 수식 경계와 섞임 -> \boxed{(가)} (12 문제 본문과 같은 규칙; '즉, (가$)= - \frac{1}{n}$') text = re.sub(r"\(\$([가나다라마])\$\)", r"\\boxed{(\1)}", text) text = re.sub(r"\(\$([가나다라마])\)", r"\\boxed{(\1)}$", text) text = re.sub(r"\(([가나다라마])\$\)", r"$\\boxed{(\1)}", text) reasons = list(ctx.reasons) a = ans.get(n) if a is None: reasons.append("정답표에서 정답을 못 읽음") if not text: reasons.append("해설을 못 찾음") if "$$" in text or re.search(r"\?[0-9A-F]{4}", text): reasons.append("해설 수식 변환 점검 필요") problems.append({ "exam": exam, "number": n, "answer_kind": a["kind"] if a else None, "answer": a["value"] if a else None, "answer_source": a.get("source") if a else None, "explanation_choice": None, "explanation_choice_by": None, "explanation_latex": text, # 줄바꿈 표지 포함 (finalize 에서 정리) "answer_check": "n/a", "needs_review": bool(reasons), "review_reasons": reasons, "_choices": choices.get(n), }) errs = [e for e in (err1, err2) if e] return problems, errs REVIEW_DIR = Path("data/ebsi/review") def _load_answer_overrides(): """data/ebsi/review/answer_overrides.jsonl: {exam, number, kind(choice|integer), value, note}. 나중 줄 우선.""" f = Path(__file__).resolve().parents[1] / "data/ebsi/review/answer_overrides.jsonl" out: dict[str, dict] = {} if f.exists(): for line in open(f, encoding="utf-8"): if line.strip(): r = json.loads(line) out.setdefault(r["exam"], {})[r["number"]] = {"kind": r["kind"], "value": r["value"], "source": "manual"} return out ANSWER_OVERRIDES = _load_answer_overrides() def load_overrides(review_dir: Path = REVIEW_DIR): """화면 대조로 사람이 고친 해설: {(exam, number): explanation_latex}. 나중 줄이 앞 줄을 덮음.""" f = review_dir / "solution_overrides.jsonl" out = {} if f.exists(): for line in open(f, encoding="utf-8"): if line.strip(): r = json.loads(line) out[(r["exam"], r["number"])] = r["explanation_latex"] return out def load_review(review_dir: Path = REVIEW_DIR): """화면 대조 기록: {(exam, number): {"status": "verified"|"fixed", "date": ..., "note": ...}}""" f = review_dir / "solution_review.jsonl" out = {} if f.exists(): for line in open(f, encoding="utf-8"): if line.strip(): r = json.loads(line) out[(r["exam"], r["number"])] = r return out def finalize(q: dict, counts: Counter, overrides=None, review=None): """줄바꿈 표지 정리 -> (있으면) 사람이 고친 해설로 교체 -> 객관식 대조.""" q["explanation_latex"] = resolve_breaks(q["explanation_latex"], counts) key = (q["exam"], q["number"]) q["explanation_source"] = "auto" if overrides and key in overrides: q["explanation_latex"] = overrides[key] q["explanation_source"] = "manual" q["review_reasons"] = [] # 자동 변환 경고는 사람이 고친 본문에는 해당 없음 rv = (review or {}).get(key) q["visual_check"] = rv["status"] if rv else None # 원본 화면 대조 여부 (None = 아직) if rv and rv.get("text_sha"): import hashlib now = hashlib.sha1(" ".join(q["explanation_latex"].split()).encode("utf-8")).hexdigest()[:12] if now != rv["text_sha"]: q["visual_check"] = "stale" # 대조 뒤 규칙이 바뀌어 텍스트가 달라짐 -> 다시 대조해야 함 q["needs_review"] = bool(q["review_reasons"]) or q["visual_check"] in (None, "stale") exp_choice, exp_how = explanation_choice(q["explanation_latex"], q.pop("_choices")) q["explanation_choice"], q["explanation_choice_by"] = exp_choice, exp_how if q["answer_kind"] == "choice": q["answer_check"] = ("no_choice_in_explanation" if exp_choice is None else "ok" if exp_choice == q["answer"] else "mismatch") elif q["answer_kind"] == "integer": # 단답: 해설 마지막 수식의 마지막 '=' 뒤 값이 정답 정수와 같은지 v = explanation_value(q["explanation_latex"]) q["explanation_value"] = v q["answer_check"] = "no_value_in_explanation" if v is None else "ok" if v == q["answer"] else "mismatch" def explanation_value(text: str): """해설 끝의 값(정수)을 찾는다: 마지막 수식부터 거슬러 올라가며 '= 정수' 로 끝나는 첫 수식.""" maths = re.findall(r"\$([^$]+)\$", text) for m in reversed(maths[-3:]): last = _norm(m.split("=")[-1]) if re.fullmatch(r"-?\d+", last): return int(last) return None def main(): ap = argparse.ArgumentParser() ap.add_argument("--pdf", type=Path) ap.add_argument("--dir", type=Path) ap.add_argument("--out", type=Path, default=Path("data/ebsi/solutions")) ap.add_argument("--latex-dir", type=Path, default=Path("data/ebsi/latex"), help="2단계 결과(보기 내용). 해설 마지막 값과 보기를 대조할 때 씀") ap.add_argument("--show", nargs="*", type=int) a = ap.parse_args() pdfs = [a.pdf] if a.pdf else sorted(a.dir.glob("*_solution.pdf")) if a.dir else [] if not pdfs: sys.exit("처리할 PDF 가 없어요 (--pdf 또는 --dir)") a.out.mkdir(parents=True, exist_ok=True) tot = rev = mism = noans = vis_tot = 0 why = Counter() mismatches, nochoice = [], [] done = [(pdf, *process_pdf(pdf, a.latex_dir)) for pdf in pdfs] # 줄바꿈 판정용 어절 빈도: 이번 해설 전부 + 2단계 문제 본문/보기 corpus = [q["explanation_latex"] for _, items, _ in done for q in items] # 같은 학년 문제 본문만 (다른 학년 파일이 늘어나면 빈도가 바뀌어 이미 대조한 해설의 줄바꿈이 달라졌음: 2024_03_hs1 11번) grades = {p.name.split("_solution")[0].rsplit("_hs", 1)[-1] for p in pdfs} for f in sorted(x for x in a.latex_dir.glob("*.jsonl") if x.stem.rsplit("_hs", 1)[-1] in grades) \ if a.latex_dir and a.latex_dir.exists() else []: for line in open(f, encoding="utf-8"): q = json.loads(line) corpus.append(q.get("stem_latex", "")) corpus.extend(q.get("choices") or []) counts = word_counts(corpus) overrides, review = load_overrides(), load_review() for pdf, items, errs in done: for q in items: finalize(q, counts, overrides, review) exam = items[0]["exam"] with open(a.out / f"{exam}.jsonl", "w", encoding="utf-8") as f: for q in items: f.write(json.dumps(q, ensure_ascii=False) + "\n") got = sum(q["answer"] is not None for q in items) mm = sum(q["answer_check"] == "mismatch" for q in items) r = sum(bool(q["review_reasons"]) for q in items) vis = sum(q["visual_check"] in ("verified", "fixed") for q in items) stale = [q["number"] for q in items if q["visual_check"] == "stale"] if stale: errs = list(errs) + [f"대조 뒤 텍스트 바뀜(재대조 필요): {stale}"] vis_tot += vis tot += len(items); rev += r; mism += mm; noans += 30 - got for q in items: why.update(q["review_reasons"]) if q["answer_check"] == "mismatch": mismatches.append(q) elif q["answer_check"] in ("no_choice_in_explanation", "no_value_in_explanation"): nochoice.append(q) print(f"{exam}: 정답 {got}/30, 자동경고 {r}, 화면대조 {vis}/30, 보기번호 불일치 {mm} {'; '.join(errs)}") if a.show: for q in items: if q["number"] in a.show: print(f"\n[{exam} {q['number']}번] 정답={q['answer']} ({q['answer_kind']}) 검증={q['answer_check']}\n{q['explanation_latex'][:600]}") print(f"\n전체 {tot}문항: 정답 못 읽음 {noans}, 자동경고 {rev}, 화면대조 완료 {vis_tot}/{tot}, 보기번호 불일치 {mism}") for k, v in why.most_common(): print(f" - {k}: {v}") okc = sum(1 for f in [a.out / f"{p.name.replace('_solution.pdf', '')}.jsonl" for p in pdfs] for line in open(f, encoding="utf-8") if json.loads(line)["answer_check"] == "ok") print(f"\n[정답↔해설 대조] 일치 {okc} / 불일치 {len(mismatches)} / 자동 대조 불가 {len(nochoice)} (화면 대조로 확인)") print(" 객관식: 해설 끝 ①~⑤ 또는 마지막 '=' 뒤 값이 보기 하나와 같을 때 / 단답: 마지막 '= 정수' 가 정답과 같을 때") for q in mismatches: tail = q["explanation_latex"][-80:].replace("\n", " ") if q["answer_kind"] == "choice": got = f"정답표 {CIRC[q['answer'] - 1]} / 해설 {CIRC[q['explanation_choice'] - 1]}({q['explanation_choice_by']})" else: got = f"정답표 {q['answer']} / 해설 {q.get('explanation_value')}" print(f" 불일치 {q['exam']} {q['number']:>2}번: {got} …{tail}") by_exam = Counter(q["exam"] for q in nochoice) if nochoice: print(" 자동 대조 불가(시험별): " + ", ".join(f"{k} {v}" for k, v in sorted(by_exam.items()))) if __name__ == "__main__": main()