leejunyoung5819pdf-to-md

공개

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

1,404줄63 KB
1#!/usr/bin/env python3
2"""Convert a text-based PDF to UTF-8 Markdown with LaTeX math ($...$, $$...$$)."""
3
4from __future__ import annotations
5
6import argparse
7import ast
8import html
9import os
10import re
11import sys
12import unicodedata
13from collections import Counter
14from dataclasses import dataclass, replace
15from functools import lru_cache
16from pathlib import Path
17from statistics import median
18from tempfile import NamedTemporaryFile
19
20# Private-use characters verified against the HyhwpEQ font in the sample PDF.
21HWP_SYMBOLS = {
22 **{0xE000 + i: c for i, c in enumerate("ABCDEFGHIJKLMNOPQRSTUVWXYZ")},
23 **{0xE034 + i: c for i, c in enumerate("1234567890")},
24 **{0xE044 + i: c for i, c in enumerate("()-=+[]{}")},
25 **{0xE0E5 + i: c for i, c in enumerate("abcdefghijklmnopqrstuvwxyz")},
26 0xE04F: ":", 0xE052: ",", 0xE053: ".", 0xE055: "<", 0xE056: ">",
27 0xE05B: "\u222b", 0xE05C: "\u221a", 0xE067: "\u2211", 0xE06E: "\u2192",
28 0xE09D: "\u03b1", 0xE0AC: "\u03c0", 0xE0AE: "\u03c3", 0xE101: "|",
29}
30HWP_BAR = "\ue06d"
31# Fonts whose glyphs are math: OpenType math fonts (Cambria Math, STIX, Latin
32# Modern Math, DejaVu Math TeX Gyre, MathJax/KaTeX) and classic TeX fonts.
33MATH_FONT = re.compile(r"math|stix|xits|(?:^|\+)(?:cm(?:mi|sy|ex|r|bx|ti)\d+|msam|msbm|eufm|rsfs)",
34 re.I)
35HWP_BRACE_TOP, HWP_BRACE_MIDDLE, HWP_BRACE_BOTTOM = "\ue078", "\ue079", "\ue07a"
36TABLE = "" # text of a stand-in glyph whose `latex` holds a Markdown table
37CHARACTER_FIXES = {
38 "\u2236": ":", # RATIO
39 # A tall left brace assembled from pieces (TeX, Word) works like HWP's.
40 "\u23a7": HWP_BRACE_TOP, "\u23a8": HWP_BRACE_MIDDLE, "\u23a9": HWP_BRACE_BOTTOM,
41 "\u23aa": "\ue07b",
42}
43HWP_BRACE = {HWP_BRACE_TOP: "{", HWP_BRACE_MIDDLE: "{", HWP_BRACE_BOTTOM: "{", "\ue07b": "|"}
44MATH_OPERATORS = frozenset("=+-\u00d7\u00f7\u2260<>\u2264\u2265\u00b1\u2192")
45LIMIT_OPERATORS = frozenset(("lim", "\u2211", "\u222b", "\u220f"))
46NAMED_OPERATORS = frozenset(("lim", "log", "ln", "sin", "cos", "tan"))
47TAG_ORDER = ("mark", "u", "del", "b", "em")
48MARKDOWN_SPECIAL = re.compile(r"([\\`*_\[\]~|#$])")
49GREEK = dict(zip(
50 "αβγδεζηθικλμνξπρστυφχψωΓΔΘΛΞΠΣΥΦΨΩ",
51 ("alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi pi rho sigma "
52 "tau upsilon phi chi psi omega Gamma Delta Theta Lambda Xi Pi Sigma Upsilon Phi Psi Omega").split(),
53))
54LATEX_SYMBOLS = {
55 **{c: "\\" + name for c, name in GREEK.items()},
56 "×": r"\times", "÷": r"\div", "≠": r"\neq", "≤": r"\le", "≥": r"\ge", "±": r"\pm",
57 "∓": r"\mp", "→": r"\to", "←": r"\leftarrow", "↔": r"\leftrightarrow",
58 "⇒": r"\Rightarrow", "⇔": r"\Leftrightarrow", "∞": r"\infty", "∫": r"\int",
59 "∑": r"\sum", "∏": r"\prod", "√": r"\surd", "⋅": r"\cdot", "·": r"\cdot", "∙": r"\cdot",
60 "⋯": r"\cdots", "…": r"\ldots", "⋮": r"\vdots", "′": "'", "″": "''", "‴": "'''",
61 "∪": r"\cup", "∩": r"\cap", "∈": r"\in", "∉": r"\notin", "∋": r"\ni", "⊂": r"\subset",
62 "⊃": r"\supset", "⊆": r"\subseteq", "⊇": r"\supseteq", "∅": r"\varnothing",
63 "∀": r"\forall", "∃": r"\exists", "≈": r"\approx", "≒": r"\fallingdotseq",
64 "≡": r"\equiv", "∼": r"\sim", "∝": r"\propto", "∠": r"\angle", "△": r"\triangle",
65 "⊥": r"\perp", "∥": r"\parallel", "°": r"^{\circ}", "∴": r"\therefore",
66 "∵": r"\because", "∘": r"\circ", "−": "-", "{": r"\{", "}": r"\}", "%": r"\%",
67 "#": r"\#", "&": r"\&", "$": r"\$", "_": r"\_", "\\": r"\backslash", "~": r"\sim",
68 "^": r"\wedge",
69}
70# Korean (and other CJK) text inside a formula must be wrapped in \text{...}.
71CJK_TEXT = re.compile(r"( ?)([ᄀ-ᇿ㄰-㆏㈀-㋿一-鿿가-힣]"
72 r"(?:[ ᄀ-ᇿ㄰-㆏㈀-㋿一-鿿가-힣]*"
73 r"[ᄀ-ᇿ㄰-㆏㈀-㋿一-鿿가-힣])?)")
74# Line openings that begin a new paragraph: "<b>12.</b>", "3\.", "①", "ㄱ.", "(가)", "\* ".
75BLOCK_START = re.compile(r"(?:<b>)?\d{1,2}\\?[.)]|[①-⑳❶-➓]|[ㄱ-ㅎ]\.|"
76 r"\([가-힣]\)|\\\* ")
77UNICODE_SCRIPTS = (
78 ("^", dict(zip("\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079\u207a\u207b\u207c\u207d\u207e\u207f", "0123456789+-=()n"))),
79 ("_", dict(zip("\u2080\u2081\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089\u208a\u208b\u208c\u208d\u208e", "0123456789+-=()"))),
80)
81
82
83@dataclass(frozen=True)
84class Glyph:
85 text: str
86 x0: float
87 x1: float
88 center: float
89 baseline: float
90 size: float
91 tags: frozenset[str] = frozenset()
92 math: bool = False
93 horizontal: bool = True
94 scope: int | None = None
95 script_reach: float = 0.0
96 # `text` keeps a plain notation such as "(1)/(3)" that the layout
97 # heuristics match against; `latex` holds what is written to Markdown.
98 latex: str | None = None
99
100 @property
101 def x(self):
102 return (self.x0 + self.x1) / 2
103
104 @property
105 def tex(self):
106 return self.latex if self.latex is not None else latex_symbol(self.text)
107
108
109@dataclass(frozen=True)
110class Rule:
111 x0: float
112 x1: float
113 y: float
114 glyph: Glyph | None = None
115
116
117def font_styles(page):
118 from pdfminer.pdftypes import dict_value, resolve1
119
120 styles = {}
121 fonts = dict_value(page.page_obj.resources.get("Font", {}))
122 for reference in fonts.values():
123 # A single broken font dictionary should not abort the whole page;
124 # named_styles() still provides a fallback from the font name.
125 try:
126 font = page.pdf.rsrcmgr.get_font(getattr(reference, "objid", None), dict_value(reference))
127 descriptor = getattr(font, "descriptor", None) or {}
128 flags = int(resolve1(descriptor.get("Flags", 0)) or 0)
129 weight = resolve1(descriptor.get("FontWeight", 0))
130 except Exception:
131 continue
132 tags = set()
133 if flags & 64 or font.italic_angle:
134 tags.add("em")
135 if flags & (1 << 18) or (isinstance(weight, (int, float)) and weight >= 600):
136 tags.add("b")
137 styles[font.fontname] = tags
138 return styles
139
140
141@lru_cache(maxsize=256)
142def named_styles(name):
143 if name.startswith("b'") or name.startswith('b"'):
144 try:
145 name = ast.literal_eval(name).decode("cp949")
146 except (ValueError, SyntaxError, UnicodeDecodeError):
147 pass
148 tags = set()
149 if re.search(r"italic|oblique|slanted|(?:[-,](?:bi|it|i))$|기울임", name, re.I):
150 tags.add("em")
151 # "DemiLight" (e.g. Noto Sans CJK) is a light weight, not a bold one.
152 if re.search(r"bold|demi(?!-?light)|black|heavy|(?:[-,](?:bd|bi|b))$|굵|견명조|견고딕", name, re.I):
153 tags.add("b")
154 return tags
155
156
157def visible_characters(page):
158 from pdfplumber.utils import dedupe_chars
159
160 if not any(r["fill"] and r["non_stroking_color"] in (1, (1,), (1, 1, 1))
161 for r in page.rects):
162 return page.dedupe_chars(tolerance=0.85, extra_attrs=("fontname", "size")).chars
163
164 # PDF editors sometimes paint an opaque panel over the original header.
165 # Walk backward so that the panel hides only characters drawn before it.
166 characters, masks = [], []
167 objects = list(page.iter_layout_objects(page.layout._objs))
168 for obj in reversed(objects):
169 if obj["object_type"] == "char":
170 x = (obj["x0"] + obj["x1"]) / 2
171 y = (obj["top"] + obj["bottom"]) / 2
172 if not any(x0 <= x <= x1 and top <= y <= bottom for x0, top, x1, bottom in masks):
173 characters.append(obj)
174 elif (obj["object_type"] == "rect" and obj["fill"]
175 and obj["width"] >= 24 and obj["height"] >= 12
176 and obj["non_stroking_color"] in (1, (1,), (1, 1, 1))):
177 masks.append(bounds(obj))
178 characters.reverse()
179 return dedupe_chars(characters, tolerance=0.85, extra_attrs=("fontname", "size"))
180
181
182def page_glyphs(page, unknown):
183 styles = font_styles(page)
184 scope = 0
185 was_math = False
186 for char in visible_characters(page):
187 font = char["fontname"]
188 text = char["text"]
189 if not text or char["size"] <= 0:
190 continue
191 tags = styles.get(font, set()) | named_styles(font)
192 a, b, c, d, x, y = char["matrix"]
193 horizontal = abs(b) <= abs(a) * 0.08
194 if horizontal and d and 0.08 < abs(c / d) < 0.7:
195 tags.add("em")
196 hwp = "hyhwpeq" in font.lower()
197 # HWP equations use the HyhwpEQ font; TeX-style engines (LaTeX, MathJax,
198 # Word) use a math font and/or Mathematical Alphanumeric letters (𝑥).
199 is_math = hwp or bool(MATH_FONT.search(font)) or is_math_letter(text)
200 if is_math:
201 # Math letters are often slanted on purpose; that is notation, not
202 # emphasis, and an <em> tag would split the formula.
203 tags.discard("em")
204 if is_math and not was_math:
205 scope += 1
206 # Text-font ASCII letters inside a formula ("log", "sin" in some
207 # generators) must not split it into separate math scopes.
208 if is_math or not re.fullmatch(r"[A-Za-z]", text):
209 was_math = is_math
210 if hwp and len(text) == 1:
211 text = HWP_SYMBOLS.get(ord(text), text)
212 text = normalize_character(text)
213 if (len(text) == 1 and "\ue000" <= text <= "\uf8ff"
214 and text != HWP_BAR and text not in HWP_BRACE):
215 unknown[ord(text)] += 1
216 text = f"[U+{ord(text):04X}]"
217 if any(ord(c) < 32 for c in text):
218 # A font without a Unicode map: pdfminer hands back raw glyph codes.
219 text = "\ufffd"
220 if text.startswith("(cid:") or "\ufffd" in text:
221 unknown[0xFFFD] += 1
222 center = (char["top"] + char["bottom"]) / 2
223 baseline = page.point2coord((x, y))[1] if horizontal else center
224 yield Glyph(text, char["x0"], char["x1"], center, baseline, char["size"],
225 frozenset(tags), is_math, horizontal, scope if is_math else None)
226
227
228def is_math_letter(text):
229 # Mathematical Alphanumeric Symbols (𝑥, 𝐴, 𝜋, ...) plus italic h (ℎ, U+210E),
230 # which Unicode keeps outside that block.
231 return len(text) == 1 and ("\U0001d400" <= text <= "\U0001d7ff" or text == "ℎ")
232
233
234def normalize_character(text):
235 if len(text) != 1:
236 return text
237 # 𝑥 → x, 𝜋 → π, and halfwidth jamo ᄀ → ㄱ (used for 보기 items).
238 if is_math_letter(text) or "ᅠ" <= text <= "ᅵ":
239 return unicodedata.normalize("NFKC", text)
240 return CHARACTER_FIXES.get(text, text)
241
242
243def bounds(shape):
244 return shape["x0"], shape["top"], shape["x1"], shape["bottom"]
245
246
247def path_is_closed(shape):
248 points = shape.get("pts") or []
249 path = shape.get("path") or []
250 return ((path and path[-1][0] == "h")
251 or (len(points) >= 4 and all(abs(a - b) <= 0.75
252 for a, b in zip(points[0], points[-1]))))
253
254
255def drawing_regions(page):
256 rules, verticals, boxes = [], [], []
257 for shape in page.lines + page.rects + page.curves:
258 x0, top, x1, bottom = bounds(shape)
259 width, height = x1 - x0, bottom - top
260 if not (shape["stroke"] or shape["fill"]):
261 continue
262 if height <= 2 and width >= 2:
263 rules.append(Rule(x0, x1, (top + bottom) / 2))
264 elif width <= 2 and height >= 2:
265 verticals.append((x0, top, x1, bottom))
266 elif path_is_closed(shape) and width >= 4 and height >= 4:
267 color = shape["non_stroking_color"]
268 colored = isinstance(color, (tuple, list)) and len(color) == 3 and max(color) - min(color) > 0.12
269 if shape["stroke"] or (shape["fill"] and colored):
270 boxes.append((x0, top, x1, bottom))
271
272 # Some generators draw each of the four sides as an independent path.
273 for upper in rules:
274 lefts = [v for v in verticals if abs(v[0] - upper.x0) <= 1.5
275 and abs(v[1] - upper.y) <= 1.5 and v[3] - v[1] >= 4]
276 for left in lefts:
277 right = next((v for v in verticals if abs(v[2] - upper.x1) <= 1.5
278 and abs(v[1] - left[1]) <= 1.5 and abs(v[3] - left[3]) <= 1.5), None)
279 if right and any(abs(lower.y - left[3]) <= 1.5
280 and abs(lower.x0 - upper.x0) <= 1.5
281 and abs(lower.x1 - upper.x1) <= 1.5 for lower in rules):
282 boxes.append((left[0], upper.y, right[2], left[3]))
283 boxes = [b for b in boxes if b[2] - b[0] < page.width * 0.88
284 or b[3] - b[1] < page.height * 0.78]
285 return list(dict.fromkeys(rules)), list(dict.fromkeys(verticals)), list(dict.fromkeys(boxes))
286
287
288def annotation_regions(page):
289 from pdfminer.pdftypes import dict_value, resolve1
290 from pdfminer.psparser import literal_name
291
292 tags = {
293 "Underline": "u", "StrikeOut": "del", "Highlight": "mark",
294 "Square": "mark", "Circle": "mark", "Polygon": "mark", "Squiggly": "mark",
295 }
296 left, bottom, right, top = page.page_obj.mediabox
297
298 def to_page(x, y):
299 if page.rotation == 90:
300 return page.point2coord((y - bottom, right - x))
301 if page.rotation == 180:
302 return page.point2coord((right - x, top - y))
303 if page.rotation == 270:
304 return page.point2coord((top - y, x - left))
305 return page.point2coord((x - left, y - bottom))
306
307 for reference in resolve1(page.page_obj.annots) or []:
308 annotation = dict_value(reference)
309 subtype = resolve1(annotation.get("Subtype"))
310 tag = tags.get(literal_name(subtype)) if subtype else None
311 rect = resolve1(annotation.get("Rect")) or []
312 if not tag or len(rect) != 4 or resolve1(annotation.get("F", 0)) & 3:
313 continue
314 quads = resolve1(annotation.get("QuadPoints")) or []
315 if len(quads) >= 8 and len(quads) % 8 == 0:
316 groups = [quads[i:i+8] for i in range(0, len(quads), 8)]
317 else:
318 groups = [rect]
319 for group in groups:
320 xs, ys = zip(*(to_page(resolve1(x), resolve1(y)) for x, y in zip(group[::2], group[1::2])))
321 yield (min(xs), min(ys), max(xs), max(ys)), tag
322
323
324def apply_regions(glyphs, regions):
325 return [
326 replace(g, tags=g.tags.union(tag for (x0, y0, x1, y1), tag in regions
327 if x0 <= g.x <= x1 and y0 <= g.center <= y1))
328 for g in glyphs
329 ]
330
331
332def line_decorations(glyphs, rules):
333 for rule in rules:
334 for tag, low, high in (("u", -0.04, 0.26), ("del", -0.58, -0.18)):
335 hits = [g for g in glyphs if g.horizontal and not g.text.isspace()
336 and rule.x0 <= g.x <= rule.x1
337 and low <= (rule.y - g.baseline) / g.size <= high]
338 if not hits:
339 continue
340 left, right = min(g.x0 for g in hits), max(g.x1 for g in hits)
341 size = median(g.size for g in hits)
342 if left - rule.x0 <= 0.8 * size and rule.x1 - right <= 0.8 * size:
343 yield (rule.x0, min(g.center for g in hits) - 0.1, rule.x1,
344 max(g.center for g in hits) + 0.1), tag
345
346
347def script_text(operator, text):
348 return operator + (text if len(text) == 1 else f"({text})")
349
350
351def latex_script(operator, text):
352 text = text.strip()
353 if operator == "^" and re.fullmatch(r"'+", text):
354 return text # a raised prime: f'(x), not f^{'}(x)
355 if re.fullmatch(r"[A-Za-z0-9]|\\[A-Za-z]+", text):
356 return operator + text
357 return f"{operator}{{{text}}}"
358
359
360def latex_symbol(text):
361 if text in LATEX_SYMBOLS:
362 return LATEX_SYMBOLS[text]
363 if text in NAMED_OPERATORS:
364 return "\\" + text
365 if text.startswith("[U+"):
366 return rf"\text{{{text}}}"
367 return text
368
369
370def normalize_unicode_scripts(text, latex=False):
371 attach = latex_script if latex else script_text
372 for operator, symbols in UNICODE_SCRIPTS:
373 pattern = f"[{''.join(symbols)}]+"
374 text = re.sub(pattern, lambda m: attach(operator, "".join(symbols[c] for c in m[0])), text)
375 return text
376
377
378def math_text(glyphs, latex=False):
379 """Join glyphs into one expression.
380
381 The spacing decisions always use the plain `text`, so both notations agree;
382 with latex=True the joined pieces are each glyph's LaTeX form instead.
383 """
384 text = ""
385 out = ""
386 previous = None
387 prose_space = False
388 for glyph in sorted(glyphs, key=lambda g: g.x0):
389 part = glyph.text.replace("\u2212", "-")
390 if part.isspace():
391 prose_space |= not glyph.math
392 continue
393 piece = glyph.tex if latex else part
394 if text and previous:
395 gap = glyph.x0 - previous.x1
396 before = previous.text.replace("\u2212", "-") # "−" is a minus too
397 operator = re.match(r"(?:lim|log|ln|sin|cos|tan)(?:$|[_^])", before)
398 spaced = (prose_space or part in MATH_OPERATORS or before in MATH_OPERATORS
399 or part == ":" or before in (",", ":") or before[0] in "∫∑∏"
400 or (operator and (part != "(" or before.startswith("lim")))
401 or (glyph.math != previous.math and gap > glyph.size * 0.12)
402 or gap > glyph.size * 0.38)
403 unary_minus = before == "-" and (text == "-" or text[:-1].rstrip()[-1:] in ("=", "(", "[", ",", "+", "-"))
404 if spaced and not unary_minus and part[0] not in ")]}," and text[-1] not in "([{":
405 text += " "
406 out += " "
407 elif re.search(r"\\[A-Za-z]+$", out) and piece[:1].isalpha():
408 out += " " # "\pi x", not the undefined command "\pix"
409 text += part
410 out += piece
411 previous = glyph
412 prose_space = False
413 return normalize_unicode_scripts(out if latex else text, latex)
414
415
416def finish_latex(tex):
417 """Final touches for a whole formula: wrap Korean text and let parentheses
418 around a fraction grow with it."""
419 tex = CJK_TEXT.sub(lambda m: rf"\text{{{m[1]}{m[2]}}}", tex)
420 return auto_size_parentheses(tex)
421
422
423def auto_size_parentheses(tex):
424 pairs = []
425 groups = [[]] # open "(" positions per brace group; \left/\right cannot cross groups
426 i = 0
427 while i < len(tex):
428 char = tex[i]
429 if char == "\\":
430 word = re.match(r"\\(?:[A-Za-z]+|.)", tex[i:])[0]
431 i += len(word)
432 if word in (r"\left", r"\right"):
433 i += 1 # its delimiter is already sized
434 continue
435 if char == "{":
436 groups.append([])
437 elif char == "}" and len(groups) > 1:
438 groups.pop()
439 elif char == "(":
440 groups[-1].append(i)
441 elif char == ")" and groups[-1]:
442 start = groups[-1].pop()
443 if r"\frac" in tex[start:i]:
444 pairs.append((start, i))
445 i += 1
446 if not pairs:
447 return tex
448 replacements = {}
449 for start, end in pairs:
450 replacements[start] = r"\left("
451 replacements[end] = r"\right)"
452 return "".join(replacements.get(i, c) for i, c in enumerate(tex))
453
454
455def combine(glyphs, text, latex, anchor, baseline=None, size=None):
456 return replace(anchor, text=text, latex=latex, math=True,
457 x0=min(g.x0 for g in glyphs), x1=max(g.x1 for g in glyphs),
458 baseline=anchor.baseline if baseline is None else baseline,
459 size=anchor.size if size is None else size,
460 tags=frozenset.intersection(*(g.tags for g in glyphs)))
461
462
463def nearest_row(glyphs, target, tolerance):
464 if not glyphs:
465 return []
466 anchor = min(glyphs, key=lambda g: abs(g.baseline - target))
467 return [g for g in glyphs if abs(g.baseline - anchor.baseline) <= tolerance]
468
469
470def replace_glyphs(glyphs, used, new):
471 consumed = {id(g) for g in used}
472 return [g for g in glyphs if id(g) not in consumed] + [new]
473
474
475def join_operator_names(glyphs):
476 for i in range(len(glyphs) - 1):
477 for length in (3, 2):
478 run = glyphs[i:i + length]
479 name = "".join(g.text for g in run)
480 first = run[0]
481 if (len(run) == length and name in NAMED_OPERATORS
482 and first.scope is not None
483 and all(g.scope == first.scope and abs(g.baseline - first.baseline) <= first.size * 0.2
484 for g in run)
485 and all(0 <= b.x0 - a.x0 <= first.size for a, b in zip(run, run[1:]))):
486 yield run, combine(run, name, "\\" + name, first)
487 elif (len(run) == length and name in NAMED_OPERATORS
488 and (anchor := prose_operator(glyphs, i, length))):
489 # Some generators set "sin", "log" or "lim" in the text font while
490 # the rest of the formula uses the math font; join the formula.
491 yield run, combine(run, name, "\\" + name, replace(first, scope=anchor.scope))
492
493
494def prose_operator(glyphs, i, length):
495 """Return a math glyph that an operator name in the text font belongs to."""
496 run = glyphs[i:i + length]
497 first, last = run[0], run[-1]
498 if not all(g.scope is None and g.horizontal
499 and abs(g.baseline - first.baseline) <= first.size * 0.2 for g in run):
500 return None
501 if not all(-0.5 <= b.x0 - a.x1 <= first.size * 0.2 for a, b in zip(run, run[1:])):
502 return None
503 # "limit", "slim" or "login" is a word, not an operator.
504 neighbours = [glyphs[j] for j in (i - 1, i + length) if 0 <= j < len(glyphs)]
505 if any(g.text.isascii() and g.text.isalpha() and g.scope is None
506 and min(abs(g.x0 - last.x1), abs(first.x0 - g.x1)) < first.size * 0.3
507 for g in neighbours):
508 return None
509 size = first.size
510 candidates = [g for g in glyphs if g.scope is not None and g.horizontal and (
511 # the argument or a subscript right after it: sin(x), log_2 x, lim_{x→0}
512 (-0.5 <= g.x0 - last.x1 <= size * 1.2 and -0.6 * size <= g.baseline - first.baseline <= 0.8 * size)
513 # math right before it: 3 sin x
514 or (-0.5 <= first.x0 - g.x1 <= size * 0.8 and abs(g.baseline - first.baseline) <= 0.3 * size)
515 # a limit's subscript underneath
516 or (first.x0 - size <= g.x <= last.x1 + size
517 and 0.35 * size <= g.baseline - first.baseline <= 1.2 * size and g.size <= size * 0.9))]
518 return min(candidates, key=lambda g: abs(g.x - (first.x0 + last.x1) / 2), default=None)
519
520
521def attach_limit_scripts(glyphs):
522 for base in [g for g in glyphs if g.text in LIMIT_OPERATORS and g.scope is not None]:
523 groups = {}
524 is_limit = base.text == "lim"
525 for sign, operator in ((1, "_"), (-1, "^")):
526 if is_limit:
527 offset, min_size, max_size = 0.72, 0.40, 0.83
528 min_shift, max_shift = 0.46, 1.20
529 x0, x1 = base.x0 - 0.5 * base.size, base.x1 + 0.48 * base.size
530 else:
531 offset, min_size, max_size = 0.52, 0.25, 0.52
532 min_shift, max_shift = 0.24, 0.85
533 if base.text == "∫":
534 x0, x1 = base.x1 - 0.17 * base.size, base.x1 + 0.35 * base.size
535 else:
536 x0, x1 = base.x0 - 0.23 * base.size, base.x1 + 0.23 * base.size
537 def fits(glyph):
538 # A fraction drawn as a separate text object can straddle the
539 # integral's original baseline even when it is a bound.
540 separate_bound = base.text == "∫" and glyph.math and ")/(" in glyph.text
541 return (glyph is not base and glyph.horizontal
542 and (glyph.scope == base.scope or separate_bound)
543 and glyph.text not in LIMIT_OPERATORS and glyph.text != HWP_BAR
544 and x0 <= glyph.x <= x1 and min_size <= glyph.size / base.size <= max_size
545 and (0.16 if separate_bound else min_shift)
546 <= sign * (glyph.baseline - base.baseline) / base.size <= max_shift)
547
548 options = [g for g in glyphs if fits(g)]
549 if options:
550 groups[operator] = nearest_row(options, base.baseline + sign * base.size * offset,
551 base.size * 0.14)
552 if groups or not is_limit:
553 scripts = {op: math_text(group) for op, group in groups.items()}
554 latex_scripts = {op: math_text(group, latex=True) for op, group in groups.items()}
555 if is_limit and "_" in scripts:
556 # One-sided limits: "x → 0 -" reads "x → 0-", in LaTeX "x \to 0^-".
557 scripts["_"] = re.sub(r" ([+-])$", r"\1", scripts["_"])
558 latex_scripts["_"] = re.sub(r" ?([+-])$", r"^\1", latex_scripts["_"])
559 text = base.text + "".join(script_text(op, value) for op, value in scripts.items())
560 latex = base.tex + "".join(latex_script(op, value) for op, value in latex_scripts.items())
561 used = [base, *(g for group in groups.values() for g in group)]
562 baseline = base.baseline if is_limit else base.center + 0.17 * base.size
563 glyphs = replace_glyphs(glyphs, used, combine(used, text, latex, base, baseline,
564 size=base.size if is_limit else base.size * 0.56))
565 return glyphs
566
567
568def resize_delimiters(glyphs):
569 adjusted = []
570 for glyph in glyphs:
571 if glyph.scope is not None and glyph.text in "()[]{}|" and glyph.size >= 8:
572 neighbors = [g for g in glyphs if g.scope == glyph.scope and g.text not in "()[]{}|"
573 and g.text != HWP_BAR and abs(g.x - glyph.x) <= glyph.size * 1.85
574 and abs(g.center - glyph.center) <= glyph.size * 0.44
575 and glyph.size * 0.40 <= g.size <= glyph.size * 1.05]
576 if neighbors:
577 size = max(g.size for g in neighbors)
578 if glyph.size >= 1.35 * size:
579 glyph = replace(glyph, size=size, baseline=glyph.center + 0.3 * size,
580 script_reach=glyph.size * 0.62)
581 adjusted.append(glyph)
582 return adjusted
583
584
585def attach_scripts(glyphs, extra=()):
586 extras = {id(g) for g in extra}
587 available = [*glyphs, *extra]
588 for original in sorted(glyphs, key=lambda g: (g.size, g.x0)):
589 if (not original.horizontal or original.text[0] in "∫∑∏"
590 or original.text.startswith("lim_")
591 or not (original.math or re.fullmatch("[A-Za-z0-9]", original.text))):
592 continue
593 if not re.search(r"[\w)\]}|]$", original.text) or original.text.startswith("[U+"):
594 continue
595 base = next((g for g in available if g is original), None)
596 if base is None:
597 continue
598 if not base.math and any(
599 g is not base and not g.math and g.text.isalpha()
600 and 0 <= base.x0 - g.x0 <= base.size
601 and abs(g.baseline - base.baseline) < base.size * 0.15
602 and abs(base.x0 - g.x1) < base.size * 0.14 for g in glyphs
603 ):
604 continue
605 used = [base]
606 suffix = ""
607 latex_suffix = ""
608 reach = max(base.size * 0.94, base.script_reach)
609 if encloses_fraction(available, base):
610 reach = max(reach, base.size * 1.4) # a tall ")" reports a normal size
611 for sign, operator in ((1, "_"), (-1, "^")):
612 options = [g for g in available if g.horizontal and g not in used and not g.text.isspace()
613 and g.text != HWP_BAR and g.scope == base.scope
614 and (g.math or re.fullmatch(r"[A-Za-z0-9+()=-]", g.text))
615 and 0.42 <= g.size / base.size <= 0.85
616 and base.size * 0.19 <= sign * (g.baseline - base.baseline)
617 <= reach
618 and g.x0 >= base.x1 - base.size * 0.28]
619 run = []
620 end = max(g.x1 for g in used)
621 for g in sorted(options, key=lambda g: g.x0):
622 if g.x0 - end > base.size * 0.32:
623 break
624 if run and abs(g.baseline - run[0].baseline) > base.size * 0.22:
625 continue
626 run.append(g)
627 end = max(end, g.x1)
628 if run:
629 used.extend(run)
630 suffix += script_text(operator, math_text(run))
631 latex_suffix += latex_script(operator, math_text(run, latex=True))
632 if suffix:
633 base_tex = base.tex
634 if base.latex is not None and re.search(r"[_^]", base_tex):
635 base_tex = f"{{{base_tex}}}" # avoid a "double superscript" error
636 available = replace_glyphs(available, used, combine(
637 used, base.text + suffix, base_tex + latex_suffix, base))
638 if extra:
639 return ([g for g in available if id(g) not in extras],
640 [g for g in available if id(g) in extras])
641 return available
642
643
644
645def encloses_fraction(glyphs, closing):
646 """Whether ")" or "]" closes a group that contains a fraction."""
647 if closing.text not in (")", "]") or closing.scope is None:
648 return False
649 openings = [g for g in glyphs if g.text in ("(", "[") and g.scope == closing.scope
650 and g.x1 <= closing.x0 and abs(g.baseline - closing.baseline) <= closing.size * 0.2]
651 if not openings:
652 return False
653 opening = max(openings, key=lambda g: g.x0)
654 return any(g.latex and r"\frac" in g.latex and g.scope == closing.scope
655 and g.x0 >= opening.x1 - 0.5 and g.x1 <= closing.x0 + 0.5 for g in glyphs)
656
657
658def math_scope(glyphs, rule):
659 if rule.glyph:
660 return rule.glyph.scope
661 nearby = [g.scope for g in glyphs if g.scope is not None and g.horizontal
662 and rule.x0 <= g.x <= rule.x1 and abs(g.baseline - rule.y) <= g.size * 1.1]
663 return Counter(nearby).most_common(1)[0][0] if nearby else None
664
665
666def fraction_row(glyphs, y, sign, size):
667 candidates = [g for g in glyphs if size * 0.16 <= sign * (g.baseline - y) <= size * 1.55]
668 if not candidates:
669 return []
670 largest = max(g.size for g in candidates)
671 bases = [g for g in candidates if g.size >= min(largest * 0.80, size * 0.77)]
672 anchor = min(bases, key=lambda g: abs(g.baseline - y - sign * size * 0.68))
673 return [g for g in candidates if abs(g.baseline - anchor.baseline) <= size * 0.23]
674
675
676def rebuild_bars(glyphs, rules):
677 bars = [Rule(g.x0, g.x1, g.baseline - 0.31 * g.size, g)
678 for g in glyphs if g.scope is not None and g.text == HWP_BAR]
679 fraction_rules = set()
680 for rule in sorted([*bars, *rules], key=lambda r: r.x1 - r.x0):
681 bar = rule.glyph
682 x0, x1, y = rule.x0, rule.x1, rule.y
683 # TeX-style engines draw a radical as a "√" glyph plus a separate line
684 # (the vinculum) starting at the glyph's right edge, level with its top.
685 # A taller radical reports the same font size, so its bar can sit well
686 # above the glyph's nominal top.
687 radical = None if bar else next(
688 (g for g in glyphs if g.text == "√" and g.scope is not None
689 and abs(g.x1 - x0) <= g.size * 0.3
690 and -g.size * 1.2 <= y - (g.center - g.size * 0.5) <= g.size * 0.4), None)
691 scope = radical.scope if radical else math_scope(glyphs, rule)
692 nearby = [g for g in glyphs if g.horizontal and g.scope == scope
693 and g.text not in (HWP_BAR, "√") and not g.text.isspace()
694 and x0 - 0.75 <= g.x <= x1 + 0.75
695 and abs(g.baseline - y) <= max(g.size * 2.05, bar.size * 1.65 if bar else 0)
696 and (scope is not None or g.math or re.fullmatch(r"[A-Za-z0-9()+.,=/−-]", g.text))]
697 if not nearby:
698 continue
699 size = bar.size if bar else median(g.size for g in nearby)
700 roots = [radical] if radical else [
701 g for g in glyphs if bar and g.scope == scope and g.text == "√"
702 and abs(g.x1 - x0) <= size * 0.27
703 and abs(g.baseline - y - size * 0.6) <= size * 0.85]
704 if roots:
705 root = min(roots, key=lambda g: abs(g.x1 - x0))
706 body = [g for g in nearby if y + size * 0.05 < g.baseline <= y + size * 1.65]
707 index = [g for g in glyphs if g.scope == scope and g.x0 >= root.x0 - size * 0.2
708 and g.x1 <= x0 + size * 0.15 and g.text != HWP_BAR
709 and 0.35 <= g.size / root.size <= 0.64
710 and root.baseline - g.baseline >= size * 0.18]
711 if radical:
712 # The index sits on the radical's upper arm; without this bound a
713 # small "3" belonging to a radical higher up would be taken too.
714 index = [g for g in index if -radical.size * 0.9 <= g.center - radical.center <= 0]
715 if body:
716 rebuilt = attach_scripts(resize_delimiters(body))
717 radicand = math_text(rebuilt)
718 latex_radicand = math_text(rebuilt, latex=True)
719 if index:
720 text = f"root({math_text(index)}, {radicand})"
721 latex = rf"\sqrt[{math_text(index, latex=True)}]{{{latex_radicand}}}"
722 else:
723 text = f"sqrt({radicand})"
724 latex = rf"\sqrt{{{latex_radicand}}}"
725 used = [g for g in (bar, root, *body, *index) if g is not None]
726 glyphs = replace_glyphs(glyphs, used, combine(used, text, latex, root))
727 if not bar:
728 fraction_rules.add(rule) # consumed; not an underline either
729 continue
730
731 numerator = fraction_row(nearby, y, -1, size)
732 denominator = fraction_row(nearby, y, 1, size)
733 arrow = next((g for g in nearby if bar and g.text == "→"
734 and abs(g.baseline - bar.baseline) < size * 0.12
735 and abs(g.x0 - x1) < size * 0.36), None)
736 if arrow or not numerator or not denominator:
737 if bar and denominator:
738 group = denominator
739 if max(g.x1 for g in group) - min(g.x0 for g in group) >= (x1 - x0) * 0.45:
740 command = "vec" if arrow else "overline"
741 text = f"{command}({math_text(group)})"
742 latex_command = r"\overrightarrow" if arrow else r"\overline"
743 latex = f"{latex_command}{{{math_text(group, latex=True)}}}"
744 markers = [bar, arrow] if arrow else [bar]
745 glyphs = replace_glyphs(glyphs, [*markers, *group],
746 combine(group, text, latex, group[0]))
747 continue
748
749 if not bar:
750 width = max(max(g.x1 for g in row) - min(g.x0 for g in row)
751 for row in (numerator, denominator))
752 if x1 - x0 > width + size * 1.55:
753 continue
754 if any(abs(median(g.x for g in row) - (x1 + x0) / 2) > (x1 - x0) * 0.28
755 for row in (numerator, denominator)):
756 continue
757 if min(g.baseline - y for g in denominator) < size * 0.40:
758 continue
759
760 upper_y = median(g.baseline for g in numerator)
761 lower_y = median(g.baseline for g in denominator)
762 extra = [g for g in nearby if g not in numerator and g not in denominator]
763 rows = []
764 latex_rows = []
765 remaining = []
766 for group, row_y, other_y in ((numerator, upper_y, lower_y), (denominator, lower_y, upper_y)):
767 scripts = [g for g in extra if abs(g.baseline - row_y) <= abs(g.baseline - other_y)]
768 group = resize_delimiters(group)
769 rebuilt, leftover = attach_scripts(group, scripts) if scripts else (attach_scripts(group), [])
770 rows.append(math_text(rebuilt))
771 latex_rows.append(math_text(rebuilt, latex=True))
772 remaining.extend(leftover)
773 if not all(rows):
774 continue
775
776 baseline = (upper_y + lower_y) / 2
777 used = [g for g in nearby if g not in remaining]
778 compound = combine(used, f"({rows[0]})/({rows[1]})",
779 rf"\frac{{{latex_rows[0]}}}{{{latex_rows[1]}}}",
780 bar or used[0], baseline, size)
781 compound = replace(compound, x0=x0, x1=x1, center=baseline - size * 0.3)
782 if bar:
783 used.append(bar)
784 else:
785 fraction_rules.add(rule)
786 glyphs = replace_glyphs(glyphs, used, compound)
787 return glyphs, fraction_rules
788
789
790def rebuild_binomials(glyphs):
791 """(n over r) drawn as parentheses around two stacked rows with no bar."""
792 for opening in [g for g in glyphs if g.text == "(" and g.scope is not None]:
793 if not any(g is opening for g in glyphs):
794 continue
795 size = opening.size
796 closing = min((g for g in glyphs if g.text == ")" and g.scope == opening.scope
797 and 0 <= g.x0 - opening.x1 <= size * 2.5
798 and abs(g.baseline - opening.baseline) <= size * 0.2),
799 key=lambda g: g.x0, default=None)
800 if closing is None:
801 continue
802 inside = [g for g in glyphs if g.scope == opening.scope and not g.text.isspace()
803 and g.x0 >= opening.x1 - 0.5 and g.x1 <= closing.x0 + 0.5
804 and abs(g.center - opening.center) <= size]
805 rows = text_lines(inside)
806 if len(rows) != 2 or not all(g.size <= size * 0.85 for g in inside):
807 continue
808 upper, lower = rows
809 if not (min(g.baseline for g in lower) - max(g.baseline for g in upper) >= size * 0.4
810 and max(g.baseline for g in upper) < opening.baseline < min(g.baseline for g in lower) + size * 0.2):
811 continue
812 used = [opening, *inside, closing]
813 text = f"C({math_text(upper)}, {math_text(lower)})"
814 latex = rf"\binom{{{math_text(upper, latex=True)}}}{{{math_text(lower, latex=True)}}}"
815 glyphs = replace_glyphs(glyphs, used, combine(used, text, latex, opening))
816 return glyphs
817
818
819def reconstruct_math(glyphs, rules):
820 for run, name in list(join_operator_names(glyphs)):
821 glyphs = replace_glyphs(glyphs, run, name)
822 glyphs, fraction_rules = rebuild_bars(glyphs, rules)
823 glyphs = rebuild_binomials(glyphs)
824 glyphs = attach_limit_scripts(glyphs)
825 glyphs = attach_scripts(resize_delimiters(glyphs))
826 glyphs = [replace(g, text="-") if g.text == HWP_BAR else g for g in glyphs]
827 return join_prime_marks(glyphs), fraction_rules
828
829
830def join_prime_marks(glyphs):
831 for mark in [g for g in glyphs if g.text in ("′", "″", "‴") and not g.math]:
832 if any(g.math and -0.15 * mark.size <= mark.x0 - g.x1 <= 0.35 * mark.size
833 and abs(g.baseline - mark.baseline) <= mark.size * 0.24 for g in glyphs):
834 glyphs = replace_glyphs(glyphs, [mark], replace(mark, math=True))
835 return glyphs
836
837
838def reading_regions(page, glyphs, verticals, rules):
839 middle = (page.bbox[0] + page.bbox[2]) / 2
840 dividers = [v for v in verticals if abs((v[0] + v[2]) / 2 - middle) < page.width * 0.12
841 and v[3] - v[1] > page.height * 0.42]
842 if dividers:
843 x0, top, x1, bottom = max(dividers, key=lambda v: v[3] - v[1])
844 split = (x0 + x1) / 2
845 # A full-width heading can be painted over the top of the divider.
846 header_rules = [r.y for r in rules if top <= r.y <= top + page.height * 0.07
847 and r.x0 <= split - page.width * 0.3
848 and r.x1 >= split + page.width * 0.3]
849 top = max(header_rules, default=top)
850 body = [g for g in glyphs if top <= g.center <= bottom]
851 left = [g for g in body if g.x < split]
852 right = [g for g in body if g.x >= split]
853 if len(left) >= 10 and len(right) >= 10:
854 return ([g for g in glyphs if g.center < top], left, right,
855 [g for g in glyphs if g.center > bottom])
856 return gutter_regions(page, glyphs, rules) or (glyphs,)
857
858
859def gutter_regions(page, glyphs, rules):
860 """Split a two-column page that has no divider line.
861
862 Looks for a vertical gutter near the middle that text lines do not cross,
863 then reads band by band: a full-width text line, or a horizontal rule or
864 box edge that spans both columns, ends a band, and inside a band the left column is read
865 before the right one.
866 """
867 lines = [line for line in text_lines(glyphs) if any(not g.text.isspace() for g in line)]
868 if len(lines) < 6:
869 return None
870 gutter = 1.2 * median(g.size for g in glyphs)
871
872 def side(line, split):
873 # Spaces can sit in the gutter itself, so only visible glyphs decide.
874 line = [g for g in line if not g.text.isspace()]
875 left = [g for g in line if g.x1 <= split]
876 right = [g for g in line if g.x0 >= split]
877 if len(left) + len(right) < len(line):
878 return "cross" # a glyph straddles the split
879 if left and right:
880 gap = min(g.x0 for g in right) - max(g.x1 for g in left)
881 return "both" if gap >= gutter else "cross"
882 return "left" if left else "right"
883
884 middle = (page.bbox[0] + page.bbox[2]) / 2
885 best = None
886 for step in range(-int(page.width * 0.15), int(page.width * 0.15) + 1, 2):
887 split = middle + step
888 sides = [side(line, split) for line in lines]
889 key = (sides.count("cross"), abs(step))
890 if best is None or key < best[0]:
891 best = (key, split, sides)
892 (crossing, _), split, sides = best
893 left_lines = sum(s in ("left", "both") for s in sides)
894 right_lines = sum(s in ("right", "both") for s in sides)
895 if left_lines < 3 or right_lines < 3 or crossing * 2 > len(lines) - crossing:
896 return None
897
898 def spans(x0, x1):
899 return x0 <= split - page.width * 0.2 and x1 >= split + page.width * 0.2
900
901 # Any panel spanning both columns counts, however pale its fill; the
902 # full-page background is not a panel.
903 panels = [bounds(r) for r in page.rects if r["height"] < page.height * 0.78]
904 breaks = sorted([r.y for r in rules if spans(r.x0, r.x1)]
905 + [y for b in panels if spans(b[0], b[2]) for y in (b[1], b[3])])
906 regions, left, right, full = [], [], [], []
907 previous_y = None
908 for line, where in zip(lines, sides):
909 line_y = min(g.center for g in line)
910 if previous_y is not None and any(previous_y < y < line_y for y in breaks):
911 regions.extend(r for r in (left, right, full) if r)
912 left, right, full = [], [], []
913 previous_y = line_y
914 if where == "cross":
915 if left or right:
916 regions.extend(r for r in (left, right) if r)
917 left, right = [], []
918 full.extend(line)
919 continue
920 if full:
921 regions.append(full)
922 full = []
923 left.extend(g for g in line if g.x < split)
924 right.extend(g for g in line if g.x >= split)
925 regions.extend(r for r in (left, right, full) if r)
926 return regions
927
928
929def text_lines(glyphs):
930 lines = []
931 for glyph in sorted(glyphs, key=lambda g: (g.baseline, g.x0)):
932 if lines:
933 anchor = lines[-1][0]
934 if abs(glyph.baseline - anchor.baseline) <= max(2.2, min(glyph.size, anchor.size) * 0.34):
935 lines[-1].append(glyph)
936 continue
937 lines.append([glyph])
938 return [sorted(line, key=lambda g: g.x0) for line in lines]
939
940
941def reconstruct_cases(glyphs):
942 # A tall brace is drawn as a middle piece plus separate top and bottom pieces.
943 for brace in [g for g in glyphs if g.text == HWP_BRACE_MIDDLE]:
944 # Extension pieces between them may come through as plain "{" glyphs.
945 pieces = [g for g in glyphs if g.scope == brace.scope and abs(g.x0 - brace.x0) < 1.0
946 and (g.text in HWP_BRACE or g.text == "{")]
947 if (not any(g.text == HWP_BRACE_TOP for g in pieces)
948 or not any(g.text == HWP_BRACE_BOTTOM for g in pieces)):
949 continue
950 top, bottom = min(g.baseline for g in pieces), max(g.baseline for g in pieces)
951 values = [g for g in glyphs if g.scope == brace.scope and g not in pieces
952 and brace.x1 - 0.5 <= g.x0 < brace.x1 + brace.size * 2 # may touch the brace
953 and top <= g.baseline <= bottom]
954 rows = []
955 latex_rows = []
956 used = list(pieces)
957 for value in sorted(values, key=lambda g: g.baseline):
958 # Start each row at its leftmost glyph, or the row loses its start.
959 mates = [g for g in values if g not in used
960 and abs(g.baseline - value.baseline) <= brace.size * 0.24]
961 if not mates:
962 continue
963 value = min(mates, key=lambda g: g.x0)
964 row = [g for g in glyphs if g not in used and g.x0 >= value.x0 - 0.2
965 and abs(g.baseline - value.baseline) <= brace.size * 0.24]
966 if not row:
967 continue
968 row.sort(key=lambda g: g.x0)
969 # Leave a neighboring table cell or separate column outside the expression.
970 stop = next((i for i in range(1, len(row))
971 if row[i].x0 - row[i - 1].x1 > brace.size * 2.3), len(row))
972 row = row[:stop]
973 rows.append(math_text(row))
974 # The widest gap separates a value from its condition: "1 & x > 0".
975 size = median(g.size for g in row)
976 gaps = [(row[i].x0 - row[i - 1].x1, i) for i in range(1, len(row))]
977 gap, split = max(gaps, default=(0, 0))
978 if gap > size * 0.9:
979 latex_rows.append(f"{math_text(row[:split], latex=True)} & "
980 f"{math_text(row[split:], latex=True)}")
981 else:
982 latex_rows.append(math_text(row, latex=True))
983 used.extend(row)
984 if len(rows) >= 2:
985 latex = r"\begin{cases} " + r" \\ ".join(latex_rows) + r" \end{cases}"
986 # Sit on the baseline of what precedes the brace ("g(t) ="), so the
987 # whole formula stays on one line.
988 before = [g for g in glyphs if g.scope == brace.scope and g not in used
989 and g.x1 <= brace.x0 + 0.5 and abs(g.baseline - brace.baseline) <= brace.size]
990 baseline = max(before, key=lambda g: g.x1).baseline if before else None
991 new = combine(used, "cases(" + ", ".join(rows) + ")", latex, brace, baseline)
992 glyphs = replace_glyphs(glyphs, used, new)
993 return [replace(g, text=HWP_BRACE[g.text]) if g.text in HWP_BRACE else g for g in glyphs]
994
995
996def markdown_text(text):
997 return MARKDOWN_SPECIAL.sub(r"\\\1", html.escape(text, quote=False))
998
999
1000def join_tagged(chunks):
1001 """Join (text, tags) chunks, keeping a tag open across neighbouring chunks
1002 that share it instead of emitting <mark>a</mark> <mark>b</mark>."""
1003 out, opened, pending_space = [], [], False
1004 for text, tags in chunks:
1005 if text == " ":
1006 pending_space = bool(out)
1007 continue
1008 wanted = [tag for tag in TAG_ORDER if tag in tags]
1009 keep = 0
1010 while keep < min(len(opened), len(wanted)) and opened[keep] == wanted[keep]:
1011 keep += 1
1012 out.extend(f"</{tag}>" for tag in reversed(opened[keep:]))
1013 if pending_space:
1014 out.append(" ")
1015 pending_space = False
1016 out.extend(f"<{tag}>" for tag in wanted[keep:])
1017 opened = wanted
1018 out.append(text)
1019 out.extend(f"</{tag}>" for tag in reversed(opened))
1020 return "".join(out)
1021
1022
1023def is_closing_punctuation(text):
1024 return len(text) == 1 and text in ".,?!:;)]}"
1025
1026
1027def absorb_touching_letters(glyphs):
1028 """Move text-font ASCII letters/digits that touch a formula into it.
1029
1030 "P$(5, 1)$" would not render: Markdown math may not open right after a
1031 letter or digit, nor close right before one. "$P(5, 1)$" is also what
1032 the PDF means.
1033 """
1034 glyphs = list(glyphs)
1035 changed = True
1036 while changed:
1037 changed = False
1038 for i, glyph in enumerate(glyphs):
1039 if glyph.math or not re.fullmatch(r"[A-Za-z0-9]", glyph.text):
1040 continue
1041 for j in (i - 1, i + 1):
1042 if not 0 <= j < len(glyphs) or not glyphs[j].math:
1043 continue
1044 other = glyphs[j]
1045 gap = other.x0 - glyph.x1 if j > i else glyph.x0 - other.x1
1046 if gap <= min(glyph.size, other.size) * 0.15:
1047 glyphs[i] = replace(glyph, math=True, tags=other.tags)
1048 changed = True
1049 break
1050 return glyphs
1051
1052
1053def render_line(glyphs, inline=False):
1054 """Render one text line. With inline=True (a table cell) the result stays
1055 on one line: no display formula, no blockquote, no raw "|" in math."""
1056 tables = [g for g in glyphs if g.text == TABLE]
1057 if tables:
1058 rest = [g for g in glyphs if g.text != TABLE]
1059 parts = [render_line(rest, inline)] if rest else []
1060 return "\n".join([*parts, *(f"\n{t.latex}\n" for t in tables)])
1061 glyphs = absorb_touching_letters(glyphs)
1062 chunks = []
1063 i = 0
1064 previous = None
1065 while i < len(glyphs):
1066 glyph = glyphs[i]
1067 if glyph.text.isspace():
1068 if chunks and chunks[-1][0] != " ":
1069 chunks.append((" ", frozenset(), False))
1070 i += 1
1071 continue
1072 if previous and chunks and chunks[-1][0] != " ":
1073 gap = glyph.x0 - previous.x1
1074 if gap > min(glyph.size, previous.size) * 0.19 and not is_closing_punctuation(glyph.text):
1075 chunks.append((" ", frozenset(), False))
1076 end = i + 1
1077 while end < len(glyphs):
1078 candidate = glyphs[end]
1079 prior = glyphs[end - 1]
1080 if candidate.math != glyph.math or candidate.tags != glyph.tags:
1081 break
1082 if candidate.text.isspace() and (
1083 end + 1 == len(glyphs) or glyphs[end + 1].tags != glyph.tags
1084 or glyphs[end + 1].math != glyph.math
1085 ):
1086 break
1087 if glyph.math and candidate.x0 - prior.x1 > min(prior.size, candidate.size) * 0.8:
1088 break
1089 end += 1
1090 run = glyphs[i:end]
1091 if glyph.math:
1092 tex = finish_latex(math_text(run, latex=True)).strip()
1093 chunks.append((tex, glyph.tags, True))
1094 previous = run[-1]
1095 i = end
1096 continue
1097 else:
1098 parts = []
1099 prior = run[0]
1100 for part in run:
1101 if (parts and part.x0 - prior.x1 > min(prior.size, part.size) * 0.19
1102 and not is_closing_punctuation(part.text)):
1103 parts.append(" ")
1104 parts.append(part.text)
1105 prior = part
1106 value = markdown_text(re.sub(r"\s+", " ", "".join(parts)))
1107 chunks.append((value, glyph.tags, False))
1108 previous = run[-1]
1109 i = end
1110
1111 # Two formulas with nothing between them would print "$a$$b$", which
1112 # Markdown reads as display math; make them one formula.
1113 merged = []
1114 for value, tags, is_math in chunks:
1115 if is_math and merged and merged[-1][2] and merged[-1][1] == tags:
1116 merged[-1] = (f"{merged[-1][0]} {value}", tags, True)
1117 else:
1118 merged.append((value, tags, is_math))
1119 chunks = merged
1120
1121 words = [chunk for chunk in chunks if chunk[0] != " "]
1122 if not words:
1123 return ""
1124 if inline:
1125 # Table cells are boxes by nature, and a raw "|" would split the cell.
1126 chunks = [(re.sub(r"(?<!\\)\|", r"\\vert ", value) if is_math else value,
1127 tags - {"mark"}, is_math) for value, tags, is_math in chunks]
1128 chunks = [(f"${latex_decorations(value, tags)}$", frozenset()) if is_math else (value, tags)
1129 for value, tags, is_math in chunks]
1130 return join_tagged(chunks).strip()
1131 # A line drawn wholly inside a box becomes a blockquote. Wrapping it in
1132 # <mark> would stop many Markdown viewers from rendering the math inside.
1133 quote = all("mark" in tags for _, tags, _ in words)
1134 if quote:
1135 chunks = [(value, tags - {"mark"}, is_math) for value, tags, is_math in chunks]
1136 if len(words) == 1 and words[0][2] and not quote and not (words[0][1] - {"mark"}):
1137 # A formula on a line of its own becomes a display block.
1138 return f"\n$${words[0][0]}$$\n"
1139 # Never put math inside HTML tags; carry its formatting in LaTeX instead.
1140 chunks = [(f"${latex_decorations(value, tags)}$", frozenset()) if is_math else (value, tags)
1141 for value, tags, is_math in chunks]
1142 line = escape_line_start(join_tagged(chunks).strip())
1143 return f"> {line}" if quote else line
1144
1145
1146def latex_decorations(tex, tags):
1147 for tag, command in (("b", r"\boldsymbol"), ("del", r"\cancel"), ("u", r"\underline")):
1148 if tag in tags:
1149 tex = f"{command}{{{tex}}}"
1150 return tex
1151
1152
1153def escape_line_start(line):
1154 # A problem number such as "2." should stay verbatim in the rendered Markdown.
1155 line = re.sub(r"^(\d+)([.)])(?= |$)", r"\1\\\2", line)
1156 # Keep a leading "-"/"+" from becoming a list item, and a line of "-" or "="
1157 # from turning the previous line into a setext heading.
1158 if re.fullmatch(r"[-=]+ *", line):
1159 return "\\" + line
1160 return re.sub(r"^([-+])(?= |$)", r"\\\1", line)
1161
1162
1163def table_glyph(glyphs, grid):
1164 """A stand-in glyph that carries a rendered Markdown table in `latex`."""
1165 visible = [g for g in glyphs if not g.text.isspace()]
1166 rendered = [["<br>".join(text for line in text_lines(cell)
1167 if (text := render_line(line, inline=True))) for cell in row]
1168 for row in grid]
1169 width = max(len(row) for row in rendered)
1170 rendered = [row + [""] * (width - len(row)) for row in rendered]
1171 markdown = "\n".join(["| " + " | ".join(rendered[0]) + " |", "|" + " --- |" * width]
1172 + ["| " + " | ".join(row) + " |" for row in rendered[1:]])
1173 x0, x1 = min(g.x0 for g in visible), max(g.x1 for g in visible)
1174 top = min(g.center for g in visible)
1175 return Glyph(TABLE, x0, x1, top, top, median(g.size for g in visible), latex=markdown)
1176
1177
1178def ruled_tables(page, glyphs):
1179 """Tables drawn with grid lines, found by pdfplumber's line-based finder.
1180
1181 The finder also reports page frames, layout cards and graph grids, so a
1182 candidate counts only when it has at least 2x2 cells, 80% of them filled
1183 (a page-header frame has 3 of 4), and every cell holds a short item
1184 rather than a paragraph.
1185 """
1186 try:
1187 tables = page.find_tables()
1188 except Exception:
1189 return glyphs
1190 for table in tables:
1191 rows = [row.cells for row in table.rows]
1192 if len(rows) < 2 or max(len(row) for row in rows) < 2:
1193 continue
1194 x0, top, x1, bottom = table.bbox
1195 inside = [g for g in glyphs if g.text != TABLE
1196 and x0 <= g.x <= x1 and top <= g.center <= bottom]
1197 grid = [[[g for g in inside if cell and cell[0] <= g.x <= cell[2] and cell[1] <= g.center <= cell[3]]
1198 if cell else [] for cell in row] for row in rows]
1199 cells = [[g for g in cell if not g.text.isspace()] for row in grid for cell in row]
1200 if sum(1 for cell in cells if cell) < 0.8 * len(cells):
1201 continue
1202 if any(len(cell) > 30 or len(text_lines(cell)) > 3 for cell in cells):
1203 continue
1204 taken = {id(g) for g in inside}
1205 glyphs = [g for g in glyphs if id(g) not in taken] + [table_glyph(inside, grid)]
1206 return glyphs
1207
1208
1209def column_layout(row):
1210 """Split a text line at wide gaps; a table row has three or more columns."""
1211 visible = [g for g in row if not g.text.isspace()]
1212 if len(visible) < 3:
1213 return None
1214 size = median(g.size for g in visible)
1215 columns = [[visible[0]]]
1216 for glyph in visible[1:]:
1217 if glyph.x0 - columns[-1][-1].x1 >= size * 1.5:
1218 columns.append([glyph])
1219 else:
1220 columns[-1].append(glyph)
1221 return columns if len(columns) >= 3 else None
1222
1223
1224def columns_align(upper, lower):
1225 if len(upper) != len(lower):
1226 return False
1227 for a, b in zip(upper, lower):
1228 a0, a1 = min(g.x0 for g in a), max(g.x1 for g in a)
1229 b0, b1 = min(g.x0 for g in b), max(g.x1 for g in b)
1230 slack = median(g.size for g in a + b) * 0.5
1231 if a0 - slack > b1 or b0 - slack > a1: # the column ranges must overlap
1232 return False
1233 return True
1234
1235
1236def aligned_tables(rows):
1237 """Tables without vertical lines: three or more consecutive lines that
1238 split into the same columns at the same positions."""
1239 result, i = [], 0
1240 while i < len(rows):
1241 layouts = [column_layout(rows[i])]
1242 j = i
1243 while layouts[-1] and j + 1 < len(rows):
1244 following = column_layout(rows[j + 1])
1245 if not following or not columns_align(layouts[-1], following):
1246 break
1247 layouts.append(following)
1248 j += 1
1249 if layouts[0] and len(layouts) >= 3:
1250 glyphs = [g for row in rows[i:j + 1] for g in row]
1251 result.append([table_glyph(glyphs, layouts)])
1252 i = j + 1
1253 else:
1254 result.append(rows[i])
1255 i += 1
1256 return result
1257
1258
1259def convert_page(page, unknown):
1260 glyphs = list(page_glyphs(page, unknown))
1261 if not glyphs:
1262 return ""
1263 rules, verticals, boxes = drawing_regions(page)
1264 regions = [(b, "mark") for b in boxes]
1265 regions.extend(annotation_regions(page))
1266 glyphs = apply_regions(glyphs, regions)
1267 expressions, fraction_rules = reconstruct_math(glyphs, rules)
1268 decor = list(line_decorations(expressions, [r for r in rules if r not in fraction_rules]))
1269 expressions = apply_regions(expressions, decor)
1270 expressions = ruled_tables(page, expressions)
1271 blocks = []
1272 for region in reading_regions(page, expressions, verticals, rules):
1273 rows = aligned_tables(text_lines(reconstruct_cases(region)))
1274 lines = [line for row in rows if (line := render_line(row))]
1275 out = []
1276 for line in lines:
1277 quoted = line.startswith("> ")
1278 if out and out[-1].startswith("> ") != quoted:
1279 # Separate a blockquote from plain lines, or the next plain line
1280 # would be pulled into the quote as a lazy continuation.
1281 out.append("")
1282 elif out and out[-1] not in ("", ">") and (
1283 BLOCK_START.match(line.removeprefix("> "))
1284 or is_heading(line) or is_heading(out[-1])):
1285 # A new problem, choice row, 보기 item, condition or a heading
1286 # (a line set wholly in bold) gets its own paragraph; lines
1287 # wrapped mid-sentence keep flowing together.
1288 out.append(">" if quoted else "")
1289 out.append(line)
1290 if out:
1291 blocks.append("\n".join(out))
1292 # Display formulas bring their own blank lines; collapse any extras.
1293 return re.sub(r"\n{3,}", "\n\n", "\n\n".join(blocks)).strip()
1294
1295
1296def is_heading(line):
1297 return re.fullmatch(r"(?:> )?<b>(?:(?!</?b>).)+</b>", line) is not None
1298
1299
1300def fallback_page(page):
1301 """Plain-text rendering used when the layout heuristics fail on a page."""
1302 text = (page.extract_text() or "").translate(HWP_SYMBOLS)
1303 text = re.sub(r"[\x00-\x08\x0b-\x1f]+", "�", text) # raw glyph codes
1304 return "\n".join(escape_line_start(line) for raw in text.splitlines()
1305 if (line := markdown_text(raw.strip())))
1306
1307
1308def output_mode(destination):
1309 # NamedTemporaryFile creates files with mode 0600; give the result the mode
1310 # an ordinary new file would get (or keep the mode of the file we replace).
1311 try:
1312 return destination.stat().st_mode & 0o7777
1313 except FileNotFoundError:
1314 umask = os.umask(0)
1315 os.umask(umask)
1316 return 0o666 & ~umask
1317
1318
1319def convert(source, destination):
1320 import pdfplumber
1321
1322 unknown = Counter()
1323 empty_pages = []
1324 failed_pages = []
1325 total = 0
1326 temporary = None
1327 try:
1328 with pdfplumber.open(source, strict_metadata=False) as pdf:
1329 with NamedTemporaryFile(mode="w", encoding="utf-8", newline="\n",
1330 dir=destination.parent, prefix=f".{destination.name}.",
1331 suffix=".tmp", delete=False) as output:
1332 temporary = Path(output.name)
1333 for page in pdf.pages:
1334 try:
1335 content = convert_page(page, unknown)
1336 except (KeyboardInterrupt, MemoryError):
1337 raise
1338 except Exception as error:
1339 # One unusual page should not discard the whole document.
1340 failed_pages.append(f"{page.page_number} ({type(error).__name__}: {error})")
1341 content = fallback_page(page)
1342 finally:
1343 page.close()
1344 if not content.strip():
1345 empty_pages.append(page.page_number)
1346 continue
1347 if total:
1348 output.write("\n\n---\n\n")
1349 output.write(content)
1350 total += 1
1351 if not total:
1352 raise ValueError("추출할 수 있는 텍스트가 없습니다. 이미지 PDF는 OCR이 필요합니다.")
1353 output.write("\n")
1354 os.chmod(temporary, output_mode(destination))
1355 os.replace(temporary, destination)
1356 finally:
1357 if temporary is not None:
1358 temporary.unlink(missing_ok=True)
1359
1360 if failed_pages:
1361 print("레이아웃 분석에 실패해 일반 텍스트로 변환한 페이지: " + ", ".join(failed_pages),
1362 file=sys.stderr)
1363 if empty_pages:
1364 print("텍스트가 없는 페이지: " + ", ".join(map(str, empty_pages)), file=sys.stderr)
1365 if unknown:
1366 codes = ", ".join(f"U+{code:04X} ({count}개)" for code, count in sorted(unknown.items()))
1367 print(f"확인할 수 없는 문자: {codes}", file=sys.stderr)
1368
1369
1370def main():
1371 parser = argparse.ArgumentParser(description="텍스트가 포함된 PDF를 Markdown으로 변환합니다.")
1372 parser.add_argument("--file", required=True, type=Path, help="원본 PDF 경로")
1373 parser.add_argument("--output", type=Path,
1374 help="출력 Markdown 경로 (생략하면 원본 PDF 옆에 .md로 저장)")
1375 args = parser.parse_args()
1376 source = args.file.expanduser()
1377 destination = (args.output or source.with_suffix(".md")).expanduser()
1378 if not source.is_file():
1379 parser.error(f"PDF 파일을 찾을 수 없습니다. {source}")
1380 if destination.is_dir():
1381 parser.error(f"출력 경로가 디렉터리입니다. 파일 경로를 지정하세요. {destination}")
1382 if source.resolve() == destination.resolve() or (destination.exists() and source.samefile(destination)):
1383 parser.error("원본 PDF와 출력 파일의 경로를 다르게 지정하세요.")
1384 if not destination.parent.is_dir():
1385 parser.error(f"출력 디렉터리가 없습니다. {destination.parent}")
1386
1387 try:
1388 from pdfminer.pdfdocument import PDFPasswordIncorrect, PDFTextExtractionNotAllowed
1389 from pdfminer.pdfparser import PDFSyntaxError
1390 from pdfplumber.utils.exceptions import MalformedPDFException, PdfminerException
1391 except ImportError:
1392 parser.exit(1, 'pdfplumber가 필요합니다. python3 -m pip install "pdfplumber>=0.11.9,<1"\n')
1393
1394 try:
1395 convert(source, destination)
1396 except (OSError, ValueError, PDFSyntaxError, PDFPasswordIncorrect,
1397 PDFTextExtractionNotAllowed, PdfminerException, MalformedPDFException) as error:
1398 message = str(error) or type(error).__name__
1399 parser.exit(1, f"변환 실패. {message}\n")
1400 return 0
1401
1402
1403if __name__ == "__main__":
1404 raise SystemExit(main())