r"""EBSi 해설 PDF -> 해설 그림 조각 (무료·API 불필요). 만드는 것 (data/ 는 GitHub 에 올리지 않음) data/ebsi/figures/<시험>/sNN_figK.png NN번 해설의 K번째 그림(삽입 이미지 + 라벨) data/ebsi/figures/<시험>_solution.jsonl {"exam","number","figures":[{"path","page","bbox","crop_bbox"}]} 규칙 - 그림 = 해설 PDF 의 삽입 이미지(12pt 이상). 나란히 놓인 이미지(16pt 안)는 한 그림으로 합침. - 어느 문항 해설인지: 13_ebsi_solution 과 같은 규칙(같은 단에서 그림 위쪽에 있는 마지막 'N. [출제의도]' 시작점, 없으면 앞 단·앞 쪽의 마지막 문항). - 라벨: 10_ebsi_chunk._figure_labels (문제 그림과 같은 규칙)으로 찾아 조각 범위에 포함. - 이미지 안에 한글이 많은 것(본문 배경 상자 등, 4자 이상)은 그림이 아님 -> 제외 (13번과 같은 기준). 사용 예 (PowerShell) python scripts\18_ebsi_solution_figures.py --dir data\ebsi\h1 """ from __future__ import annotations import argparse, importlib.util, json, sys from pathlib import Path HERE = Path(__file__).resolve().parent PAD = 4.0 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 def process_pdf(pdf_path: Path, out_root: Path, dpi: int): import pdfplumber m13 = _load("ebsi_solution", "13_ebsi_solution.py") ck = _load("ebsi_chunk", "10_ebsi_chunk.py") exam = pdf_path.name.replace("_solution.pdf", "") odir = out_root / exam odir.mkdir(parents=True, exist_ok=True) scale = dpi / 72.0 found: dict[int, list] = {} with pdfplumber.open(str(pdf_path)) as pdf: m13.inject_missing_glyphs(pdf, pdf_path) starts = m13.find_starts(pdf) lefts = m13.column_lefts(starts) for s in starts: s["col"] = m13.col_of(s["x"], lefts) # 고3: 확률과 통계 다음 선택과목(미적분·기하) 구간부터는 그림을 붙이지 않음 (13 과 같은 기준) cut_key = None if exam.endswith("_hs3"): hd = {h["name"]: h for h in m13.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"])] if later: c = min(later, key=lambda h: (h["page"], h["x"], h["top"])) cut_key = (c["page"], m13.col_of(c["x"], lefts), c["top"] - 2) starts = [s for s in starts if (s["page"], s["col"], s["top"]) < cut_key] for old in odir.glob("s*_fig*.png"): # 이전 실행의 해설 그림 조각 정리 old.unlink() starts.sort(key=lambda s: (s["page"], s["col"], s["top"])) for pi, p in enumerate(pdf.pages): head = m13.header_bottom(p) imgs = [] for im in p.images: if im["x1"] - im["x0"] <= 12 or im["bottom"] - im["top"] <= 12 or im["top"] < head - 2: continue box = (im["x0"], im["top"], im["x1"], im["bottom"]) hang = sum(1 for c in p.chars if m13._hangul(c["text"]) and m13._in_any((c["x0"] + c["x1"]) / 2, (c["top"] + c["bottom"]) / 2, [box])) if hang >= 4: continue imgs.append({"x0": im["x0"], "top": im["top"], "x1": im["x1"], "bottom": im["bottom"]}) if not imgs: continue groups = ck._clusters(imgs, gap=16) img = None for g in groups: bx0, bt, bx1, bb = g[:4] col = m13.col_of(bx0 + 1, lefts) if cut_key and (pi, col, bt) >= cut_key: continue same =[s for s in starts if s["page"] == pi and s["col"] == col and s["top"] <= bt + 6] if same: owner = same[-1]["n"] else: prev = [s for s in starts if (s["page"], s["col"]) < (pi, col)] if not prev: continue owner = prev[-1]["n"] cx0 = lefts[col] - 6 cx1 = (lefts[col + 1] - 6) if col + 1 < len(lefts) else p.width - 20 cs = [c for c in p.chars if c["text"].strip() and cx0 <= c["x0"] < cx1 and bt - 40 <= c["top"] and c["bottom"] <= bb + 40] labs = ck._figure_labels(cs, bx0, bt, bx1, bb) x0 = min([bx0] + [c["x0"] for c in labs]); t = min([bt] + [c["top"] for c in labs]) x1 = max([bx1] + [c["x1"] for c in labs]); b = max([bb] + [c["bottom"] for c in labs]) cb = [round(max(cx0, x0 - PAD), 2), round(max(0, t - PAD), 2), round(min(cx1, x1 + PAD), 2), round(min(p.height, b + PAD), 2)] if img is None: img = p.to_image(resolution=dpi).original.convert("RGB") k = len(found.setdefault(owner, [])) + 1 fp = odir / f"s{owner:02d}_fig{k}.png" img.crop((int(cb[0] * scale), int(cb[1] * scale), int(cb[2] * scale + 0.999), int(cb[3] * scale + 0.999))).save(fp, optimize=True) found[owner].append({"path": fp.relative_to(out_root).as_posix(), "page": pi + 1, "bbox": [round(v, 2) for v in (bx0, bt, bx1, bb)], "crop_bbox": cb}) with open(out_root / f"{exam}_solution.jsonl", "w", encoding="utf-8") as f: for n in sorted(found): f.write(json.dumps({"exam": exam, "number": n, "figures": found[n]}, ensure_ascii=False) + "\n") return exam, found 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/figures")) ap.add_argument("--dpi", type=int, default=200) 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)") tot_items = tot_figs = 0 for pdf in pdfs: exam, found = process_pdf(pdf, a.out, a.dpi) n = sum(len(v) for v in found.values()) tot_items += len(found) tot_figs += n print(f"{exam}: 그림 있는 해설 {len(found)}문항 (그림 {n}개)") print(f"\n전체: 그림 있는 해설 {tot_items}문항, 그림 {tot_figs}개") if __name__ == "__main__": main()