leejunyoung5819pdf-to-md

공개

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

858줄37 KB
1#!/usr/bin/env python3
2"""Convert a text-based PDF to UTF-8 Markdown with editable math notation."""
3
4from __future__ import annotations
5
6import argparse
7import ast
8import html
9import os
10import re
11import sys
12from collections import Counter
13from dataclasses import dataclass, replace
14from functools import lru_cache
15from pathlib import Path
16from statistics import median
17from tempfile import NamedTemporaryFile
18
19# Private-use characters verified against the HyhwpEQ font in the sample PDF.
20HWP_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}
29HWP_BAR = "\ue06d"
30HWP_BRACE_TOP, HWP_BRACE_MIDDLE, HWP_BRACE_BOTTOM = "\ue078", "\ue079", "\ue07a"
31HWP_BRACE = {HWP_BRACE_TOP: "{", HWP_BRACE_MIDDLE: "{", HWP_BRACE_BOTTOM: "{", "\ue07b": "|"}
32MATH_OPERATORS = frozenset("=+-\u00d7\u00f7\u2260<>\u2264\u2265\u00b1\u2192")
33LIMIT_OPERATORS = frozenset(("lim", "\u2211", "\u222b", "\u220f"))
34NAMED_OPERATORS = frozenset(("lim", "log", "ln", "sin", "cos", "tan"))
35TAG_ORDER = ("mark", "u", "del", "b", "em")
36MARKDOWN_SPECIAL = re.compile(r"([\\`*_\[\]~|#])")
37UNICODE_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)
44class 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)
63class Rule:
64 x0: float
65 x1: float
66 y: float
67 glyph: Glyph | None = None
68
69
70def 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)
95def 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
110def 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
135def 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
171def bounds(shape):
172 return shape["x0"], shape["top"], shape["x1"], shape["bottom"]
173
174
175def 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
183def 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
216def 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
252def 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
260def 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
275def script_text(operator, text):
276 return operator + (text if len(text) == 1 else f"({text})")
277
278
279def 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
286def 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
312def 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
320def 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
327def 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
332def 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
346def 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
389def 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
406def 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
457def 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
465def 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
475def 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
560def 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
570def 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
578def 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
599def 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
611def 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
642def markdown_text(text):
643 return MARKDOWN_SPECIAL.sub(r"\\\1", html.escape(text, quote=False))
644
645
646def 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
653def 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
676def is_closing_punctuation(text):
677 return len(text) == 1 and text in ".,?!:;)]}"
678
679
680def 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
728def 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
738def 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
755def 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
762def 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
773def 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
824def 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
857if __name__ == "__main__":
858 raise SystemExit(main())