leejunyoung5819pdf-to-md

공개

Convert text-based PDFs (including HWP equations) to UTF-8 Markdown with editable math notation

Add PDF to Markdown converter

Convert text-based PDFs (including HWP equation fonts) to UTF-8
Markdown with editable inline math notation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
작성자
이준영
작성 시각
커밋
3272e1f22804126a83cff2c3f7bc454756aab191
부모
없음 (첫 커밋)
이 시점의 파일 보기

변경된 파일 2개

+863-0
추가.gitignore+5-0
@@ -0,0 +1,5 @@
1추가: __pycache__/
2추가: *.py[cod]
3추가:
4추가: # Sample exam PDFs are copyrighted by their publishers; keep them local only.
5추가: tests/sample/*.pdf
추가pdf-to-md.py+858-0
@@ -0,0 +1,858 @@
1추가: #!/usr/bin/env python3
2추가: """Convert a text-based PDF to UTF-8 Markdown with editable math notation."""
3추가:
4추가: from __future__ import annotations
5추가:
6추가: import argparse
7추가: import ast
8추가: import html
9추가: import os
10추가: import re
11추가: import sys
12추가: from collections import Counter
13추가: from dataclasses import dataclass, replace
14추가: from functools import lru_cache
15추가: from pathlib import Path
16추가: from statistics import median
17추가: from tempfile import NamedTemporaryFile
18추가:
19추가: # Private-use characters verified against the HyhwpEQ font in the sample PDF.
20추가: HWP_SYMBOLS = {
21추가: **{0xE000 + i: c for i, c in enumerate("ABCDEFGHIJKLMNOPQRSTUVWXYZ")},
22추가: **{0xE034 + i: c for i, c in enumerate("1234567890")},
23추가: **{0xE044 + i: c for i, c in enumerate("()-=+[]{}")},
24추가: **{0xE0E5 + i: c for i, c in enumerate("abcdefghijklmnopqrstuvwxyz")},
25추가: 0xE04F: ":", 0xE052: ",", 0xE053: ".", 0xE055: "<", 0xE056: ">",
26추가: 0xE05B: "\u222b", 0xE05C: "\u221a", 0xE067: "\u2211", 0xE06E: "\u2192",
27추가: 0xE09D: "\u03b1", 0xE0AC: "\u03c0", 0xE0AE: "\u03c3", 0xE101: "|",
28추가: }
29추가: HWP_BAR = "\ue06d"
30추가: HWP_BRACE_TOP, HWP_BRACE_MIDDLE, HWP_BRACE_BOTTOM = "\ue078", "\ue079", "\ue07a"
31추가: HWP_BRACE = {HWP_BRACE_TOP: "{", HWP_BRACE_MIDDLE: "{", HWP_BRACE_BOTTOM: "{", "\ue07b": "|"}
32추가: MATH_OPERATORS = frozenset("=+-\u00d7\u00f7\u2260<>\u2264\u2265\u00b1\u2192")
33추가: LIMIT_OPERATORS = frozenset(("lim", "\u2211", "\u222b", "\u220f"))
34추가: NAMED_OPERATORS = frozenset(("lim", "log", "ln", "sin", "cos", "tan"))
35추가: TAG_ORDER = ("mark", "u", "del", "b", "em")
36추가: MARKDOWN_SPECIAL = re.compile(r"([\\`*_\[\]~|#])")
37추가: UNICODE_SCRIPTS = (
38추가: ("^", dict(zip("\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079\u207a\u207b\u207c\u207d\u207e\u207f", "0123456789+-=()n"))),
39추가: ("_", dict(zip("\u2080\u2081\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089\u208a\u208b\u208c\u208d\u208e", "0123456789+-=()"))),
40추가: )
41추가:
42추가:
43추가: @dataclass(frozen=True)
44추가: class Glyph:
45추가: text: str
46추가: x0: float
47추가: x1: float
48추가: center: float
49추가: baseline: float
50추가: size: float
51추가: tags: frozenset[str] = frozenset()
52추가: math: bool = False
53추가: horizontal: bool = True
54추가: scope: int | None = None
55추가: script_reach: float = 0.0
56추가:
57추가: @property
58추가: def x(self):
59추가: return (self.x0 + self.x1) / 2
60추가:
61추가:
62추가: @dataclass(frozen=True)
63추가: class Rule:
64추가: x0: float
65추가: x1: float
66추가: y: float
67추가: glyph: Glyph | None = None
68추가:
69추가:
70추가: def font_styles(page):
71추가: from pdfminer.pdftypes import dict_value, resolve1
72추가:
73추가: styles = {}
74추가: fonts = dict_value(page.page_obj.resources.get("Font", {}))
75추가: for reference in fonts.values():
76추가: # A single broken font dictionary should not abort the whole page;
77추가: # named_styles() still provides a fallback from the font name.
78추가: try:
79추가: font = page.pdf.rsrcmgr.get_font(getattr(reference, "objid", None), dict_value(reference))
80추가: descriptor = getattr(font, "descriptor", None) or {}
81추가: flags = int(resolve1(descriptor.get("Flags", 0)) or 0)
82추가: weight = resolve1(descriptor.get("FontWeight", 0))
83추가: except Exception:
84추가: continue
85추가: tags = set()
86추가: if flags & 64 or font.italic_angle:
87추가: tags.add("em")
88추가: if flags & (1 << 18) or (isinstance(weight, (int, float)) and weight >= 600):
89추가: tags.add("b")
90추가: styles[font.fontname] = tags
91추가: return styles
92추가:
93추가:
94추가: @lru_cache(maxsize=256)
95추가: def named_styles(name):
96추가: if name.startswith("b'") or name.startswith('b"'):
97추가: try:
98추가: name = ast.literal_eval(name).decode("cp949")
99추가: except (ValueError, SyntaxError, UnicodeDecodeError):
100추가: pass
101추가: tags = set()
102추가: if re.search(r"italic|oblique|slanted|(?:[-,](?:bi|it|i))$|기울임", name, re.I):
103추가: tags.add("em")
104추가: # "DemiLight" (e.g. Noto Sans CJK) is a light weight, not a bold one.
105추가: if re.search(r"bold|demi(?!-?light)|black|heavy|(?:[-,](?:bd|bi|b))$|굵|견명조|견고딕", name, re.I):
106추가: tags.add("b")
107추가: return tags
108추가:
109추가:
110추가: def visible_characters(page):
111추가: from pdfplumber.utils import dedupe_chars
112추가:
113추가: if not any(r["fill"] and r["non_stroking_color"] in (1, (1,), (1, 1, 1))
114추가: for r in page.rects):
115추가: return page.dedupe_chars(tolerance=0.85, extra_attrs=("fontname", "size")).chars
116추가:
117추가: # PDF editors sometimes paint an opaque panel over the original header.
118추가: # Walk backward so that the panel hides only characters drawn before it.
119추가: characters, masks = [], []
120추가: objects = list(page.iter_layout_objects(page.layout._objs))
121추가: for obj in reversed(objects):
122추가: if obj["object_type"] == "char":
123추가: x = (obj["x0"] + obj["x1"]) / 2
124추가: y = (obj["top"] + obj["bottom"]) / 2
125추가: if not any(x0 <= x <= x1 and top <= y <= bottom for x0, top, x1, bottom in masks):
126추가: characters.append(obj)
127추가: elif (obj["object_type"] == "rect" and obj["fill"]
128추가: and obj["width"] >= 24 and obj["height"] >= 12
129추가: and obj["non_stroking_color"] in (1, (1,), (1, 1, 1))):
130추가: masks.append(bounds(obj))
131추가: characters.reverse()
132추가: return dedupe_chars(characters, tolerance=0.85, extra_attrs=("fontname", "size"))
133추가:
134추가:
135추가: def page_glyphs(page, unknown):
136추가: styles = font_styles(page)
137추가: scope = 0
138추가: was_math = False
139추가: for char in visible_characters(page):
140추가: font = char["fontname"]
141추가: text = char["text"]
142추가: if not text or char["size"] <= 0:
143추가: continue
144추가: tags = styles.get(font, set()) | named_styles(font)
145추가: a, b, c, d, x, y = char["matrix"]
146추가: horizontal = abs(b) <= abs(a) * 0.08
147추가: if horizontal and d and 0.08 < abs(c / d) < 0.7:
148추가: tags.add("em")
149추가: is_math = "hyhwpeq" in font.lower()
150추가: if is_math:
151추가: # Math letters are often slanted on purpose; that is notation, not
152추가: # emphasis, and an <em> tag would split the inline code span.
153추가: tags.discard("em")
154추가: if is_math and not was_math:
155추가: scope += 1
156추가: was_math = is_math
157추가: if is_math and len(text) == 1:
158추가: text = HWP_SYMBOLS.get(ord(text), text)
159추가: if (len(text) == 1 and "\ue000" <= text <= "\uf8ff"
160추가: and text != HWP_BAR and text not in HWP_BRACE):
161추가: unknown[ord(text)] += 1
162추가: text = f"[U+{ord(text):04X}]"
163추가: if text.startswith("(cid:") or "\ufffd" in text:
164추가: unknown[0xFFFD] += 1
165추가: center = (char["top"] + char["bottom"]) / 2
166추가: baseline = page.point2coord((x, y))[1] if horizontal else center
167추가: yield Glyph(text, char["x0"], char["x1"], center, baseline, char["size"],
168추가: frozenset(tags), is_math, horizontal, scope if is_math else None)
169추가:
170추가:
171추가: def bounds(shape):
172추가: return shape["x0"], shape["top"], shape["x1"], shape["bottom"]
173추가:
174추가:
175추가: def path_is_closed(shape):
176추가: points = shape.get("pts") or []
177추가: path = shape.get("path") or []
178추가: return ((path and path[-1][0] == "h")
179추가: or (len(points) >= 4 and all(abs(a - b) <= 0.75
180추가: for a, b in zip(points[0], points[-1]))))
181추가:
182추가:
183추가: def drawing_regions(page):
184추가: rules, verticals, boxes = [], [], []
185추가: for shape in page.lines + page.rects + page.curves:
186추가: x0, top, x1, bottom = bounds(shape)
187추가: width, height = x1 - x0, bottom - top
188추가: if not (shape["stroke"] or shape["fill"]):
189추가: continue
190추가: if height <= 2 and width >= 2:
191추가: rules.append(Rule(x0, x1, (top + bottom) / 2))
192추가: elif width <= 2 and height >= 2:
193추가: verticals.append((x0, top, x1, bottom))
194추가: elif path_is_closed(shape) and width >= 4 and height >= 4:
195추가: color = shape["non_stroking_color"]
196추가: colored = isinstance(color, (tuple, list)) and len(color) == 3 and max(color) - min(color) > 0.12
197추가: if shape["stroke"] or (shape["fill"] and colored):
198추가: boxes.append((x0, top, x1, bottom))
199추가:
200추가: # Some generators draw each of the four sides as an independent path.
201추가: for upper in rules:
202추가: lefts = [v for v in verticals if abs(v[0] - upper.x0) <= 1.5
203추가: and abs(v[1] - upper.y) <= 1.5 and v[3] - v[1] >= 4]
204추가: for left in lefts:
205추가: right = next((v for v in verticals if abs(v[2] - upper.x1) <= 1.5
206추가: and abs(v[1] - left[1]) <= 1.5 and abs(v[3] - left[3]) <= 1.5), None)
207추가: if right and any(abs(lower.y - left[3]) <= 1.5
208추가: and abs(lower.x0 - upper.x0) <= 1.5
209추가: and abs(lower.x1 - upper.x1) <= 1.5 for lower in rules):
210추가: boxes.append((left[0], upper.y, right[2], left[3]))
211추가: boxes = [b for b in boxes if b[2] - b[0] < page.width * 0.88
212추가: or b[3] - b[1] < page.height * 0.78]
213추가: return list(dict.fromkeys(rules)), list(dict.fromkeys(verticals)), list(dict.fromkeys(boxes))
214추가:
215추가:
216추가: def annotation_regions(page):
217추가: from pdfminer.pdftypes import dict_value, resolve1
218추가: from pdfminer.psparser import literal_name
219추가:
220추가: tags = {
221추가: "Underline": "u", "StrikeOut": "del", "Highlight": "mark",
222추가: "Square": "mark", "Circle": "mark", "Polygon": "mark", "Squiggly": "mark",
223추가: }
224추가: left, bottom, right, top = page.page_obj.mediabox
225추가:
226추가: def to_page(x, y):
227추가: if page.rotation == 90:
228추가: return page.point2coord((y - bottom, right - x))
229추가: if page.rotation == 180:
230추가: return page.point2coord((right - x, top - y))
231추가: if page.rotation == 270:
232추가: return page.point2coord((top - y, x - left))
233추가: return page.point2coord((x - left, y - bottom))
234추가:
235추가: for reference in resolve1(page.page_obj.annots) or []:
236추가: annotation = dict_value(reference)
237추가: subtype = resolve1(annotation.get("Subtype"))
238추가: tag = tags.get(literal_name(subtype)) if subtype else None
239추가: rect = resolve1(annotation.get("Rect")) or []
240추가: if not tag or len(rect) != 4 or resolve1(annotation.get("F", 0)) & 3:
241추가: continue
242추가: quads = resolve1(annotation.get("QuadPoints")) or []
243추가: if len(quads) >= 8 and len(quads) % 8 == 0:
244추가: groups = [quads[i:i+8] for i in range(0, len(quads), 8)]
245추가: else:
246추가: groups = [rect]
247추가: for group in groups:
248추가: xs, ys = zip(*(to_page(resolve1(x), resolve1(y)) for x, y in zip(group[::2], group[1::2])))
249추가: yield (min(xs), min(ys), max(xs), max(ys)), tag
250추가:
251추가:
252추가: def apply_regions(glyphs, regions):
253추가: return [
254추가: replace(g, tags=g.tags.union(tag for (x0, y0, x1, y1), tag in regions
255추가: if x0 <= g.x <= x1 and y0 <= g.center <= y1))
256추가: for g in glyphs
257추가: ]
258추가:
259추가:
260추가: def line_decorations(glyphs, rules):
261추가: for rule in rules:
262추가: for tag, low, high in (("u", -0.04, 0.26), ("del", -0.58, -0.18)):
263추가: hits = [g for g in glyphs if g.horizontal and not g.text.isspace()
264추가: and rule.x0 <= g.x <= rule.x1
265추가: and low <= (rule.y - g.baseline) / g.size <= high]
266추가: if not hits:
267추가: continue
268추가: left, right = min(g.x0 for g in hits), max(g.x1 for g in hits)
269추가: size = median(g.size for g in hits)
270추가: if left - rule.x0 <= 0.8 * size and rule.x1 - right <= 0.8 * size:
271추가: yield (rule.x0, min(g.center for g in hits) - 0.1, rule.x1,
272추가: max(g.center for g in hits) + 0.1), tag
273추가:
274추가:
275추가: def script_text(operator, text):
276추가: return operator + (text if len(text) == 1 else f"({text})")
277추가:
278추가:
279추가: def normalize_unicode_scripts(text):
280추가: for operator, symbols in UNICODE_SCRIPTS:
281추가: pattern = f"[{''.join(symbols)}]+"
282추가: text = re.sub(pattern, lambda m: script_text(operator, "".join(symbols[c] for c in m[0])), text)
283추가: return text
284추가:
285추가:
286추가: def math_text(glyphs):
287추가: text = ""
288추가: previous = None
289추가: prose_space = False
290추가: for glyph in sorted(glyphs, key=lambda g: g.x0):
291추가: part = glyph.text.replace("\u2212", "-")
292추가: if part.isspace():
293추가: prose_space |= not glyph.math
294추가: continue
295추가: if text and previous:
296추가: gap = glyph.x0 - previous.x1
297추가: operator = re.match(r"(?:lim|log|ln|sin|cos|tan)(?:$|[_^])", previous.text)
298추가: spaced = (prose_space or part in MATH_OPERATORS or previous.text in MATH_OPERATORS
299추가: or part == ":" or previous.text in (",", ":") or previous.text[0] in "∫∑∏"
300추가: or (operator and (part != "(" or previous.text.startswith("lim")))
301추가: or (glyph.math != previous.math and gap > glyph.size * 0.12)
302추가: or gap > glyph.size * 0.38)
303추가: unary_minus = previous.text == "-" and (text == "-" or text[:-1].rstrip()[-1:] in ("=", "(", "[", ",", "+", "-"))
304추가: if spaced and not unary_minus and part[0] not in ")]}," and text[-1] not in "([{":
305추가: text += " "
306추가: text += part
307추가: previous = glyph
308추가: prose_space = False
309추가: return normalize_unicode_scripts(text)
310추가:
311추가:
312추가: def combine(glyphs, text, anchor, baseline=None, size=None):
313추가: return replace(anchor, text=text, math=True,
314추가: x0=min(g.x0 for g in glyphs), x1=max(g.x1 for g in glyphs),
315추가: baseline=anchor.baseline if baseline is None else baseline,
316추가: size=anchor.size if size is None else size,
317추가: tags=frozenset.intersection(*(g.tags for g in glyphs)))
318추가:
319추가:
320추가: def nearest_row(glyphs, target, tolerance):
321추가: if not glyphs:
322추가: return []
323추가: anchor = min(glyphs, key=lambda g: abs(g.baseline - target))
324추가: return [g for g in glyphs if abs(g.baseline - anchor.baseline) <= tolerance]
325추가:
326추가:
327추가: def replace_glyphs(glyphs, used, new):
328추가: consumed = {id(g) for g in used}
329추가: return [g for g in glyphs if id(g) not in consumed] + [new]
330추가:
331추가:
332추가: def join_operator_names(glyphs):
333추가: for i in range(len(glyphs) - 1):
334추가: for length in (3, 2):
335추가: run = glyphs[i:i + length]
336추가: name = "".join(g.text for g in run)
337추가: first = run[0]
338추가: if (len(run) == length and name in NAMED_OPERATORS
339추가: and first.scope is not None
340추가: and all(g.scope == first.scope and abs(g.baseline - first.baseline) <= first.size * 0.2
341추가: for g in run)
342추가: and all(0 <= b.x0 - a.x0 <= first.size for a, b in zip(run, run[1:]))):
343추가: yield run, combine(run, name, first)
344추가:
345추가:
346추가: def attach_limit_scripts(glyphs):
347추가: for base in [g for g in glyphs if g.text in LIMIT_OPERATORS and g.scope is not None]:
348추가: groups = {}
349추가: is_limit = base.text == "lim"
350추가: for sign, operator in ((1, "_"), (-1, "^")):
351추가: if is_limit:
352추가: offset, min_size, max_size = 0.72, 0.40, 0.83
353추가: min_shift, max_shift = 0.46, 1.20
354추가: x0, x1 = base.x0 - 0.5 * base.size, base.x1 + 0.48 * base.size
355추가: else:
356추가: offset, min_size, max_size = 0.52, 0.25, 0.52
357추가: min_shift, max_shift = 0.24, 0.85
358추가: if base.text == "∫":
359추가: x0, x1 = base.x1 - 0.17 * base.size, base.x1 + 0.35 * base.size
360추가: else:
361추가: x0, x1 = base.x0 - 0.23 * base.size, base.x1 + 0.23 * base.size
362추가: def fits(glyph):
363추가: # A fraction drawn as a separate text object can straddle the
364추가: # integral's original baseline even when it is a bound.
365추가: separate_bound = base.text == "∫" and glyph.math and ")/(" in glyph.text
366추가: return (glyph is not base and glyph.horizontal
367추가: and (glyph.scope == base.scope or separate_bound)
368추가: and glyph.text not in LIMIT_OPERATORS and glyph.text != HWP_BAR
369추가: and x0 <= glyph.x <= x1 and min_size <= glyph.size / base.size <= max_size
370추가: and (0.16 if separate_bound else min_shift)
371추가: <= sign * (glyph.baseline - base.baseline) / base.size <= max_shift)
372추가:
373추가: options = [g for g in glyphs if fits(g)]
374추가: if options:
375추가: groups[operator] = nearest_row(options, base.baseline + sign * base.size * offset,
376추가: base.size * 0.14)
377추가: if groups or not is_limit:
378추가: scripts = {op: math_text(group) for op, group in groups.items()}
379추가: if is_limit and "_" in scripts:
380추가: # One-sided limits: "x → 0 -" should read "x → 0-".
381추가: scripts["_"] = re.sub(r" ([+-])$", r"\1", scripts["_"])
382추가: text = base.text + "".join(script_text(op, value) for op, value in scripts.items())
383추가: used = [base, *(g for group in groups.values() for g in group)]
384추가: baseline = base.baseline if is_limit else base.center + 0.17 * base.size
385추가: glyphs = replace_glyphs(glyphs, used, combine(used, text, base, baseline, size=base.size if is_limit else base.size * 0.56))
386추가: return glyphs
387추가:
388추가:
389추가: def resize_delimiters(glyphs):
390추가: adjusted = []
391추가: for glyph in glyphs:
392추가: if glyph.scope is not None and glyph.text in "()[]{}|" and glyph.size >= 8:
393추가: neighbors = [g for g in glyphs if g.scope == glyph.scope and g.text not in "()[]{}|"
394추가: and g.text != HWP_BAR and abs(g.x - glyph.x) <= glyph.size * 1.85
395추가: and abs(g.center - glyph.center) <= glyph.size * 0.44
396추가: and glyph.size * 0.40 <= g.size <= glyph.size * 1.05]
397추가: if neighbors:
398추가: size = max(g.size for g in neighbors)
399추가: if glyph.size >= 1.35 * size:
400추가: glyph = replace(glyph, size=size, baseline=glyph.center + 0.3 * size,
401추가: script_reach=glyph.size * 0.62)
402추가: adjusted.append(glyph)
403추가: return adjusted
404추가:
405추가:
406추가: def attach_scripts(glyphs, extra=()):
407추가: extras = {id(g) for g in extra}
408추가: available = [*glyphs, *extra]
409추가: for original in sorted(glyphs, key=lambda g: (g.size, g.x0)):
410추가: if (not original.horizontal or original.text[0] in "∫∑∏"
411추가: or original.text.startswith("lim_")
412추가: or not (original.math or re.fullmatch("[A-Za-z0-9]", original.text))):
413추가: continue
414추가: if not re.search(r"[\w)\]}|]$", original.text) or original.text.startswith("[U+"):
415추가: continue
416추가: base = next((g for g in available if g is original), None)
417추가: if base is None:
418추가: continue
419추가: if not base.math and any(
420추가: g is not base and not g.math and g.text.isalpha()
421추가: and 0 <= base.x0 - g.x0 <= base.size
422추가: and abs(g.baseline - base.baseline) < base.size * 0.15
423추가: and abs(base.x0 - g.x1) < base.size * 0.14 for g in glyphs
424추가: ):
425추가: continue
426추가: used = [base]
427추가: suffix = ""
428추가: for sign, operator in ((1, "_"), (-1, "^")):
429추가: options = [g for g in available if g.horizontal and g not in used and not g.text.isspace()
430추가: and g.text != HWP_BAR and g.scope == base.scope
431추가: and (g.math or re.fullmatch(r"[A-Za-z0-9+()=-]", g.text))
432추가: and 0.42 <= g.size / base.size <= 0.85
433추가: and base.size * 0.19 <= sign * (g.baseline - base.baseline)
434추가: <= max(base.size * 0.94, base.script_reach)
435추가: and g.x0 >= base.x1 - base.size * 0.28]
436추가: run = []
437추가: end = max(g.x1 for g in used)
438추가: for g in sorted(options, key=lambda g: g.x0):
439추가: if g.x0 - end > base.size * 0.32:
440추가: break
441추가: if run and abs(g.baseline - run[0].baseline) > base.size * 0.22:
442추가: continue
443추가: run.append(g)
444추가: end = max(end, g.x1)
445추가: if run:
446추가: used.extend(run)
447추가: suffix += script_text(operator, math_text(run))
448추가: if suffix:
449추가: available = replace_glyphs(available, used, combine(used, base.text + suffix, base))
450추가: if extra:
451추가: return ([g for g in available if id(g) not in extras],
452추가: [g for g in available if id(g) in extras])
453추가: return available
454추가:
455추가:
456추가:
457추가: def math_scope(glyphs, rule):
458추가: if rule.glyph:
459추가: return rule.glyph.scope
460추가: nearby = [g.scope for g in glyphs if g.scope is not None and g.horizontal
461추가: and rule.x0 <= g.x <= rule.x1 and abs(g.baseline - rule.y) <= g.size * 1.1]
462추가: return Counter(nearby).most_common(1)[0][0] if nearby else None
463추가:
464추가:
465추가: def fraction_row(glyphs, y, sign, size):
466추가: candidates = [g for g in glyphs if size * 0.16 <= sign * (g.baseline - y) <= size * 1.55]
467추가: if not candidates:
468추가: return []
469추가: largest = max(g.size for g in candidates)
470추가: bases = [g for g in candidates if g.size >= min(largest * 0.80, size * 0.77)]
471추가: anchor = min(bases, key=lambda g: abs(g.baseline - y - sign * size * 0.68))
472추가: return [g for g in candidates if abs(g.baseline - anchor.baseline) <= size * 0.23]
473추가:
474추가:
475추가: def rebuild_bars(glyphs, rules):
476추가: bars = [Rule(g.x0, g.x1, g.baseline - 0.31 * g.size, g)
477추가: for g in glyphs if g.scope is not None and g.text == HWP_BAR]
478추가: fraction_rules = set()
479추가: for rule in sorted([*bars, *rules], key=lambda r: r.x1 - r.x0):
480추가: bar = rule.glyph
481추가: scope = math_scope(glyphs, rule)
482추가: x0, x1, y = rule.x0, rule.x1, rule.y
483추가: nearby = [g for g in glyphs if g.horizontal and g.scope == scope
484추가: and g.text not in (HWP_BAR, "√") and not g.text.isspace()
485추가: and x0 - 0.75 <= g.x <= x1 + 0.75
486추가: and abs(g.baseline - y) <= max(g.size * 2.05, bar.size * 1.65 if bar else 0)
487추가: and (scope is not None or g.math or re.fullmatch(r"[A-Za-z0-9()+.,=/−-]", g.text))]
488추가: if not nearby:
489추가: continue
490추가: size = bar.size if bar else median(g.size for g in nearby)
491추가: roots = [g for g in glyphs if bar and g.scope == scope and g.text == "√"
492추가: and abs(g.x1 - x0) <= size * 0.27
493추가: and abs(g.baseline - y - size * 0.6) <= size * 0.85]
494추가: if roots:
495추가: root = min(roots, key=lambda g: abs(g.x1 - x0))
496추가: body = [g for g in nearby if y + size * 0.05 < g.baseline <= y + size * 1.65]
497추가: index = [g for g in glyphs if g.scope == scope and g.x0 >= root.x0 - size * 0.2
498추가: and g.x1 <= x0 + size * 0.15 and g.text != HWP_BAR
499추가: and 0.35 <= g.size / root.size <= 0.64
500추가: and root.baseline - g.baseline >= size * 0.18]
501추가: if body:
502추가: radicand = math_text(attach_scripts(resize_delimiters(body)))
503추가: text = f"root({math_text(index)}, {radicand})" if index else f"sqrt({radicand})"
504추가: used = [bar, root, *body, *index]
505추가: glyphs = replace_glyphs(glyphs, used, combine(used, text, root))
506추가: continue
507추가:
508추가: numerator = fraction_row(nearby, y, -1, size)
509추가: denominator = fraction_row(nearby, y, 1, size)
510추가: arrow = next((g for g in nearby if bar and g.text == "→"
511추가: and abs(g.baseline - bar.baseline) < size * 0.12
512추가: and abs(g.x0 - x1) < size * 0.36), None)
513추가: if arrow or not numerator or not denominator:
514추가: if bar and denominator:
515추가: group = denominator
516추가: if max(g.x1 for g in group) - min(g.x0 for g in group) >= (x1 - x0) * 0.45:
517추가: command = "vec" if arrow else "overline"
518추가: text = f"{command}({math_text(group)})"
519추가: markers = [bar, arrow] if arrow else [bar]
520추가: glyphs = replace_glyphs(glyphs, [*markers, *group], combine(group, text, group[0]))
521추가: continue
522추가:
523추가: if not bar:
524추가: width = max(max(g.x1 for g in row) - min(g.x0 for g in row)
525추가: for row in (numerator, denominator))
526추가: if x1 - x0 > width + size * 1.55:
527추가: continue
528추가: if any(abs(median(g.x for g in row) - (x1 + x0) / 2) > (x1 - x0) * 0.28
529추가: for row in (numerator, denominator)):
530추가: continue
531추가: if min(g.baseline - y for g in denominator) < size * 0.40:
532추가: continue
533추가:
534추가: upper_y = median(g.baseline for g in numerator)
535추가: lower_y = median(g.baseline for g in denominator)
536추가: extra = [g for g in nearby if g not in numerator and g not in denominator]
537추가: rows = []
538추가: remaining = []
539추가: for group, row_y, other_y in ((numerator, upper_y, lower_y), (denominator, lower_y, upper_y)):
540추가: scripts = [g for g in extra if abs(g.baseline - row_y) <= abs(g.baseline - other_y)]
541추가: group = resize_delimiters(group)
542추가: rebuilt, leftover = attach_scripts(group, scripts) if scripts else (attach_scripts(group), [])
543추가: rows.append(math_text(rebuilt))
544추가: remaining.extend(leftover)
545추가: if not all(rows):
546추가: continue
547추가:
548추가: baseline = (upper_y + lower_y) / 2
549추가: used = [g for g in nearby if g not in remaining]
550추가: compound = combine(used, f"({rows[0]})/({rows[1]})", bar or used[0], baseline, size)
551추가: compound = replace(compound, x0=x0, x1=x1, center=baseline - size * 0.3)
552추가: if bar:
553추가: used.append(bar)
554추가: else:
555추가: fraction_rules.add(rule)
556추가: glyphs = replace_glyphs(glyphs, used, compound)
557추가: return glyphs, fraction_rules
558추가:
559추가:
560추가: def reconstruct_math(glyphs, rules):
561추가: for run, name in list(join_operator_names(glyphs)):
562추가: glyphs = replace_glyphs(glyphs, run, name)
563추가: glyphs, fraction_rules = rebuild_bars(glyphs, rules)
564추가: glyphs = attach_limit_scripts(glyphs)
565추가: glyphs = attach_scripts(resize_delimiters(glyphs))
566추가: glyphs = [replace(g, text="-") if g.text == HWP_BAR else g for g in glyphs]
567추가: return join_prime_marks(glyphs), fraction_rules
568추가:
569추가:
570추가: def join_prime_marks(glyphs):
571추가: for mark in [g for g in glyphs if g.text in ("′", "″", "‴") and not g.math]:
572추가: if any(g.math and -0.15 * mark.size <= mark.x0 - g.x1 <= 0.35 * mark.size
573추가: and abs(g.baseline - mark.baseline) <= mark.size * 0.24 for g in glyphs):
574추가: glyphs = replace_glyphs(glyphs, [mark], replace(mark, math=True))
575추가: return glyphs
576추가:
577추가:
578추가: def reading_regions(page, glyphs, verticals, rules):
579추가: middle = (page.bbox[0] + page.bbox[2]) / 2
580추가: dividers = [v for v in verticals if abs((v[0] + v[2]) / 2 - middle) < page.width * 0.12
581추가: and v[3] - v[1] > page.height * 0.42]
582추가: if dividers:
583추가: x0, top, x1, bottom = max(dividers, key=lambda v: v[3] - v[1])
584추가: split = (x0 + x1) / 2
585추가: # A full-width heading can be painted over the top of the divider.
586추가: header_rules = [r.y for r in rules if top <= r.y <= top + page.height * 0.07
587추가: and r.x0 <= split - page.width * 0.3
588추가: and r.x1 >= split + page.width * 0.3]
589추가: top = max(header_rules, default=top)
590추가: body = [g for g in glyphs if top <= g.center <= bottom]
591추가: left = [g for g in body if g.x < split]
592추가: right = [g for g in body if g.x >= split]
593추가: if len(left) >= 10 and len(right) >= 10:
594추가: return ([g for g in glyphs if g.center < top], left, right,
595추가: [g for g in glyphs if g.center > bottom])
596추가: return (glyphs,)
597추가:
598추가:
599추가: def text_lines(glyphs):
600추가: lines = []
601추가: for glyph in sorted(glyphs, key=lambda g: (g.baseline, g.x0)):
602추가: if lines:
603추가: anchor = lines[-1][0]
604추가: if abs(glyph.baseline - anchor.baseline) <= max(2.2, min(glyph.size, anchor.size) * 0.34):
605추가: lines[-1].append(glyph)
606추가: continue
607추가: lines.append([glyph])
608추가: return [sorted(line, key=lambda g: g.x0) for line in lines]
609추가:
610추가:
611추가: def reconstruct_cases(glyphs):
612추가: # A tall brace is drawn as a middle piece plus separate top and bottom pieces.
613추가: for brace in [g for g in glyphs if g.text == HWP_BRACE_MIDDLE]:
614추가: pieces = [g for g in glyphs if g.scope == brace.scope and g.text in HWP_BRACE
615추가: and abs(g.x0 - brace.x0) < 1.0]
616추가: if (not any(g.text == HWP_BRACE_TOP for g in pieces)
617추가: or not any(g.text == HWP_BRACE_BOTTOM for g in pieces)):
618추가: continue
619추가: top, bottom = min(g.baseline for g in pieces), max(g.baseline for g in pieces)
620추가: values = [g for g in glyphs if g.scope == brace.scope and g not in pieces
621추가: and brace.x1 <= g.x0 < brace.x1 + brace.size * 2 and top <= g.baseline <= bottom]
622추가: rows = []
623추가: used = list(pieces)
624추가: for value in sorted(values, key=lambda g: g.baseline):
625추가: row = [g for g in glyphs if g not in used and g.x0 >= value.x0 - 0.2
626추가: and abs(g.baseline - value.baseline) <= brace.size * 0.24]
627추가: if not row:
628추가: continue
629추가: row.sort(key=lambda g: g.x0)
630추가: # Leave a neighboring table cell or separate column outside the expression.
631추가: stop = next((i for i in range(1, len(row))
632추가: if row[i].x0 - row[i - 1].x1 > brace.size * 2.3), len(row))
633추가: row = row[:stop]
634추가: rows.append(math_text(row))
635추가: used.extend(row)
636추가: if len(rows) >= 2:
637추가: new = combine(used, "cases(" + ", ".join(rows) + ")", brace)
638추가: glyphs = replace_glyphs(glyphs, used, new)
639추가: return [replace(g, text=HWP_BRACE[g.text]) if g.text in HWP_BRACE else g for g in glyphs]
640추가:
641추가:
642추가: def markdown_text(text):
643추가: return MARKDOWN_SPECIAL.sub(r"\\\1", html.escape(text, quote=False))
644추가:
645추가:
646추가: def code_span(text):
647추가: # Use a fence longer than any backtick run inside the text (CommonMark).
648추가: fence = "`" * (max((len(run) for run in re.findall(r"`+", text)), default=0) + 1)
649추가: padding = " " if text.startswith("`") or text.endswith("`") else ""
650추가: return f"{fence}{padding}{text}{padding}{fence}"
651추가:
652추가:
653추가: def join_tagged(chunks):
654추가: """Join (text, tags) chunks, keeping a tag open across neighbouring chunks
655추가: that share it instead of emitting <mark>a</mark> <mark>b</mark>."""
656추가: out, opened, pending_space = [], [], False
657추가: for text, tags in chunks:
658추가: if text == " ":
659추가: pending_space = bool(out)
660추가: continue
661추가: wanted = [tag for tag in TAG_ORDER if tag in tags]
662추가: keep = 0
663추가: while keep < min(len(opened), len(wanted)) and opened[keep] == wanted[keep]:
664추가: keep += 1
665추가: out.extend(f"</{tag}>" for tag in reversed(opened[keep:]))
666추가: if pending_space:
667추가: out.append(" ")
668추가: pending_space = False
669추가: out.extend(f"<{tag}>" for tag in wanted[keep:])
670추가: opened = wanted
671추가: out.append(text)
672추가: out.extend(f"</{tag}>" for tag in reversed(opened))
673추가: return "".join(out)
674추가:
675추가:
676추가: def is_closing_punctuation(text):
677추가: return len(text) == 1 and text in ".,?!:;)]}"
678추가:
679추가:
680추가: def render_line(glyphs):
681추가: chunks = []
682추가: i = 0
683추가: previous = None
684추가: while i < len(glyphs):
685추가: glyph = glyphs[i]
686추가: if glyph.text.isspace():
687추가: if chunks and chunks[-1][0] != " ":
688추가: chunks.append((" ", frozenset()))
689추가: i += 1
690추가: continue
691추가: if previous and chunks and chunks[-1][0] != " ":
692추가: gap = glyph.x0 - previous.x1
693추가: if gap > min(glyph.size, previous.size) * 0.19 and not is_closing_punctuation(glyph.text):
694추가: chunks.append((" ", frozenset()))
695추가: end = i + 1
696추가: while end < len(glyphs):
697추가: candidate = glyphs[end]
698추가: prior = glyphs[end - 1]
699추가: if candidate.math != glyph.math or candidate.tags != glyph.tags:
700추가: break
701추가: if candidate.text.isspace() and (
702추가: end + 1 == len(glyphs) or glyphs[end + 1].tags != glyph.tags
703추가: or glyphs[end + 1].math != glyph.math
704추가: ):
705추가: break
706추가: if glyph.math and candidate.x0 - prior.x1 > min(prior.size, candidate.size) * 0.8:
707추가: break
708추가: end += 1
709추가: run = glyphs[i:end]
710추가: if glyph.math:
711추가: value = code_span(math_text(run))
712추가: else:
713추가: parts = []
714추가: prior = run[0]
715추가: for part in run:
716추가: if (parts and part.x0 - prior.x1 > min(prior.size, part.size) * 0.19
717추가: and not is_closing_punctuation(part.text)):
718추가: parts.append(" ")
719추가: parts.append(part.text)
720추가: prior = part
721추가: value = markdown_text(re.sub(r"\s+", " ", "".join(parts)))
722추가: chunks.append((value, glyph.tags))
723추가: previous = run[-1]
724추가: i = end
725추가: return escape_line_start(join_tagged(chunks).strip())
726추가:
727추가:
728추가: def escape_line_start(line):
729추가: # A problem number such as "2." should stay verbatim in the rendered Markdown.
730추가: line = re.sub(r"^(\d+)([.)])(?= |$)", r"\1\\\2", line)
731추가: # Keep a leading "-"/"+" from becoming a list item, and a line of "-" or "="
732추가: # from turning the previous line into a setext heading.
733추가: if re.fullmatch(r"[-=]+ *", line):
734추가: return "\\" + line
735추가: return re.sub(r"^([-+])(?= |$)", r"\\\1", line)
736추가:
737추가:
738추가: def convert_page(page, unknown):
739추가: glyphs = list(page_glyphs(page, unknown))
740추가: if not glyphs:
741추가: return ""
742추가: rules, verticals, boxes = drawing_regions(page)
743추가: regions = [(b, "mark") for b in boxes]
744추가: regions.extend(annotation_regions(page))
745추가: glyphs = apply_regions(glyphs, regions)
746추가: expressions, fraction_rules = reconstruct_math(glyphs, rules)
747추가: decor = list(line_decorations(expressions, [r for r in rules if r not in fraction_rules]))
748추가: expressions = apply_regions(expressions, decor)
749추가: return "\n\n".join(
750추가: "\n".join(line for row in text_lines(reconstruct_cases(region)) if (line := render_line(row)))
751추가: for region in reading_regions(page, expressions, verticals, rules) if region
752추가: )
753추가:
754추가:
755추가: def fallback_page(page):
756추가: """Plain-text rendering used when the layout heuristics fail on a page."""
757추가: text = (page.extract_text() or "").translate(HWP_SYMBOLS)
758추가: return "\n".join(escape_line_start(line) for raw in text.splitlines()
759추가: if (line := markdown_text(raw.strip())))
760추가:
761추가:
762추가: def output_mode(destination):
763추가: # NamedTemporaryFile creates files with mode 0600; give the result the mode
764추가: # an ordinary new file would get (or keep the mode of the file we replace).
765추가: try:
766추가: return destination.stat().st_mode & 0o7777
767추가: except FileNotFoundError:
768추가: umask = os.umask(0)
769추가: os.umask(umask)
770추가: return 0o666 & ~umask
771추가:
772추가:
773추가: def convert(source, destination):
774추가: import pdfplumber
775추가:
776추가: unknown = Counter()
777추가: empty_pages = []
778추가: failed_pages = []
779추가: total = 0
780추가: temporary = None
781추가: try:
782추가: with pdfplumber.open(source, strict_metadata=False) as pdf:
783추가: with NamedTemporaryFile(mode="w", encoding="utf-8", newline="\n",
784추가: dir=destination.parent, prefix=f".{destination.name}.",
785추가: suffix=".tmp", delete=False) as output:
786추가: temporary = Path(output.name)
787추가: for page in pdf.pages:
788추가: try:
789추가: content = convert_page(page, unknown)
790추가: except (KeyboardInterrupt, MemoryError):
791추가: raise
792추가: except Exception as error:
793추가: # One unusual page should not discard the whole document.
794추가: failed_pages.append(f"{page.page_number} ({type(error).__name__}: {error})")
795추가: content = fallback_page(page)
796추가: finally:
797추가: page.close()
798추가: if not content.strip():
799추가: empty_pages.append(page.page_number)
800추가: continue
801추가: if total:
802추가: output.write("\n\n---\n\n")
803추가: output.write(content)
804추가: total += 1
805추가: if not total:
806추가: raise ValueError("추출할 수 있는 텍스트가 없습니다. 이미지 PDF는 OCR이 필요합니다.")
807추가: output.write("\n")
808추가: os.chmod(temporary, output_mode(destination))
809추가: os.replace(temporary, destination)
810추가: finally:
811추가: if temporary is not None:
812추가: temporary.unlink(missing_ok=True)
813추가:
814추가: if failed_pages:
815추가: print("레이아웃 분석에 실패해 일반 텍스트로 변환한 페이지: " + ", ".join(failed_pages),
816추가: file=sys.stderr)
817추가: if empty_pages:
818추가: print("텍스트가 없는 페이지: " + ", ".join(map(str, empty_pages)), file=sys.stderr)
819추가: if unknown:
820추가: codes = ", ".join(f"U+{code:04X} ({count}개)" for code, count in sorted(unknown.items()))
821추가: print(f"확인할 수 없는 문자: {codes}", file=sys.stderr)
822추가:
823추가:
824추가: def main():
825추가: parser = argparse.ArgumentParser(description="텍스트가 포함된 PDF를 Markdown으로 변환합니다.")
826추가: parser.add_argument("--file", required=True, type=Path, help="원본 PDF 경로")
827추가: parser.add_argument("--output", type=Path,
828추가: help="출력 Markdown 경로 (생략하면 원본 PDF 옆에 .md로 저장)")
829추가: args = parser.parse_args()
830추가: source = args.file.expanduser()
831추가: destination = (args.output or source.with_suffix(".md")).expanduser()
832추가: if not source.is_file():
833추가: parser.error(f"PDF 파일을 찾을 수 없습니다. {source}")
834추가: if destination.is_dir():
835추가: parser.error(f"출력 경로가 디렉터리입니다. 파일 경로를 지정하세요. {destination}")
836추가: if source.resolve() == destination.resolve() or (destination.exists() and source.samefile(destination)):
837추가: parser.error("원본 PDF와 출력 파일의 경로를 다르게 지정하세요.")
838추가: if not destination.parent.is_dir():
839추가: parser.error(f"출력 디렉터리가 없습니다. {destination.parent}")
840추가:
841추가: try:
842추가: from pdfminer.pdfdocument import PDFPasswordIncorrect, PDFTextExtractionNotAllowed
843추가: from pdfminer.pdfparser import PDFSyntaxError
844추가: from pdfplumber.utils.exceptions import MalformedPDFException, PdfminerException
845추가: except ImportError:
846추가: parser.exit(1, 'pdfplumber가 필요합니다. python3 -m pip install "pdfplumber>=0.11.9,<1"\n')
847추가:
848추가: try:
849추가: convert(source, destination)
850추가: except (OSError, ValueError, PDFSyntaxError, PDFPasswordIncorrect,
851추가: PDFTextExtractionNotAllowed, PdfminerException, MalformedPDFException) as error:
852추가: message = str(error) or type(error).__name__
853추가: parser.exit(1, f"변환 실패. {message}\n")
854추가: return 0
855추가:
856추가:
857추가: if __name__ == "__main__":
858추가: raise SystemExit(main())