Spaces:
Running

math-tutor / scripts /18_ebsi_solution_figures.py
seongui2030
deploy 2026-12-03 20:26
b146445
Raw History Blame Contribute Delete
6.69 kB
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()